• python 抽象



    抽象

    创建函数
    >>> def hello(name):
     return 'hello,'+name+'!'

    >>> hello('qiaochao')
    'hello,qiaochao!'

    函数注释
    1)以#开头
    2)直接写上字符串

    函数定义可以嵌套
    >>> def foo():
     def bar():
      print 'hello aaa '
     bar()
     
    >>> foo()
    hello aaa

    函数递归调用:
    >>> def jiecheng(n):
     if n == 1 :
      return 1
     else:
      return n*jiecheng(n-1)
     
    >>> jiecheng(10)
    3628800

    二元查找:
    def search(sequence,number,lower,upper):
     if lower == upper :
      assert number == sequence[upper]
      return upper
     else :
      middle = (lower + upper) // 2
      if(number > sequence[middle]):
       return search(sequence,number,middle+1,upper)
      else:
       return search(sequence,number,lower,middle)

    print search([1,2,3,4,5,6,7,8,9,10],7,0,9)
    6

    ----------------------------------------------------------------


    >>> def hello(greeting,name):
     print '%s , %s!' % (greeting,name)
      
    >>> hello(greeting='hello',name='qiaoc')
    hello , qiaoc!
    注意:这里可以指定参数传值,这样就不会担心值对应的参数对不对 --- 关键字参数


    >>> def hello(greeting='hi ',name='qiaochao'):
     print '%s , %s!' % (greeting,name)

    >>> hello()
    hi  , qiaochao!
    注意:定义函数可以让参数有默认值

    ------------------------------------------------------------------

    收集参数

    >>> def print_params(title,*params):
     print title
     print params

    >>> print_params('Params:',1,2,2)
    Params:
    (1, 2, 2)
    >>> print_params('ass :')
    ass :
    ()
    注意:*的意思是收集参数,如果不提供任何供收集的元素,params就是个空元组

    >>> def print_params_1(**params):   -----** 字典参数
     print params

    >>> print_params_1(x=1,y=2,c=3)
    {'y': 2, 'x': 1, 'c': 3}

    >>> def print_params_2(x,y,z=3,*params,**keybar):
     print x,y,z
     print params
     print keybar

    >>> print_params_2(1,2,3,5,6,7,foo=1,bar=2)
    1 2 3
    (5, 6, 7)
    {'foo': 1, 'bar': 2}
    >>> print_params_2(1,2)
    1 2 3
    ()
    {}

    反转过程
    >>> def add(x,y):
     return x+y

    >>> params=(1,2)
    >>> add(*params)
    3

    ** --- 也适用于字典参数

    -----------------------------------------------------------------------

    全局变量   ----  global 定义
    >>> x=1
    >>> def change_global():
     global x
     x=x+1

    >>> x
    1
    >>> change_global()
    >>> x
    2

    ---------------------------------------------------------------------------

  • 相关阅读:
    【C++、回溯】LeetCode52. N皇后 II
    【C++、回溯】LeetCode39. 组合总和
    递归方法和回溯方法模板
    【C++】LeetCode面试题 08.06. 汉诺塔问题
    【C++、快速排序巧用】LeetCode215 数组中的第K个最大元素
    【multimap在文件处理中显奇效】将文本文件的每行内容,按照行首6个数字的升序,重新排序
    【C++、partition】快速排序算法实现
    【C++】归并排序实现
    【C++】LeetCode147 对链表进行插入排序
    更换与还原Android Studio的主题
  • 原文地址:https://www.cnblogs.com/java20130722/p/3206912.html
Copyright © 2020-2023  润新知