Chapter06 抽象

函数设计与应用
如何将语句组织成函数

计算斐波那契数列:
    >>> fibs = [0,1]
    >>> fibs
    [0, 1]
    >>> for i in range(8):
        fibs.append(fibs[-2]+fibs[-1])
        
    >>> fibs
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

创建函数
    >>> import math
    >>> x = 1
    >>> y = math.sqrt
    >>> callable(y)
    True
    >>> callable(x)
    False
    
    >>> def hello(name):
        return 'Hello, ' + name + '!'

    >>> hello(world)
    Traceback (most recent call last):
      File "<pyshell#28>", line 1, in <module>
        hello(world)
    NameError: name 'world' is not defined
    
    >>> hello('world')
    'Hello, world!'
    
记录函数
    如果在函数的开头写下字符串,它就会作为函数的一部分进行存储,这称为文档字符串。
    >>> def square(x):
    'Calculates the square of the number x.'
    return x*x
    访问文档字符串
    >>> square.__doc__
    'Calculates the square of the number x.'
    __doc__是函数属性
    
    >>> help(square)
    Help on function square in module __main__:
    square(x)
        Calculates the square of the number x.
        
并非真正的函数
    >>> def test():
        print 'This is a test.'
        return

    >>> x = test()
    This is a test.
    >>> test()
    This is a test.
    >>> x
    >>>
    
改变参数?
    >>> def try_to_change(n):
        n = 'Mr.Merisc'

    >>> name = 'Mrs.mm'
    >>> name
    'Mrs.mm'
    >>> try_to_change(name)
    >>> name
    'Mrs.mm'
    >>>
    为什么没有改变name?
    具体的工作方式:
    >>> name = 'Mrs.mm'
    >>> n = name            #这句的作用:传参数
    >>> n = 'Mr.Merisc'        #在函数内部完成的
    >>> name
    'Mrs.mm'
    >>>
    结果显而易见。当变量n改变的时候,变量name不变。
    
字符串(以及数字和元组)是不可变的,即无法被修改。
但是考虑一下如果将可变的数据结构如列表做参数。。。
    >>> def change(n):
        n[0] = 'Mr.Merisc'
        
    >>> names = ['Mrs.mm','Mrs.m']
    >>> change(names)
    >>> names
    ['Mr.Merisc', 'Mrs.m']
    很明显这样是可以修改的。
    
关键字参数和默认值
    >>> def hello_1(greeting, name):
        print '%s, %s' % (greeting, name)    
    >>> def hello_2(name, greeting):
        print '%s, %s' % (name, greeting)

    >>> hello_1('Hello', 'World')
    Hello, World
    >>> hello_2('Hello', 'World')
    Hello, World
    >>>
    参数的顺序也是可以改变的,同时提供参数的名字
    >>> hello_1(name='world', greeting='hello')
    hello, world
    >>> hello_1(name='hello', greeting='world')
    world, hello
    
收集参数
    >>> def print_params(*params):
        print params

    >>> print_params('Testing')
    ('Testing',)                    #注意这里有个逗号,打印元组
    >>> print_params(1,2,3)
    (1, 2, 3)
    *表示将所有的值放置在同一个元组中。
    
    >>> def print_params2(title, *param):
    print title
    print param    
    >>> print_params2('Params:', 1,2,3)
    Params:
    (1, 2, 3)
    
    但是不能用没有的关键字参数
    >>> print_params2('Hmm.....', something=42)
    Traceback (most recent call last):
      File "<pyshell#103>", line 1, in <module>
        print_params2('Hmm.....', something=42)
    TypeError: print_params2() got an unexpected keyword argument 'something'
    >>>
    
    解决办法:
    **
    >>> def print_params3(**params):
    print params        
    >>> print_params3(x=1, y=2, z=3)
    {'y': 2, 'x': 1, 'z': 3}
    >>>
    返回的是字典而不是元组。
    
    放一起试试:
    >>> def print_params4(x,y,z=3, *pospar, **keypar):
            print x,y,z
            print pospar
            print keypar
    
    >>> print_params4(1,2,3,5,6,7, foo = 1, bar = 2)
    1 2 3
    (5, 6, 7)
    {'foo': 1, 'bar': 2}
    

两个经典:
    阶乘和幂
    >>> def factorial(n):
        result = n
        for i in range(1,n):
            result *= i
        return result

    >>> factorial(4)
    24
    >>> def factorial(n):
        if n == 1:
            return 1
        else:
            return n*factorial(n-1)

        
    >>> factorial(4)
    24
    
    二元查找
    >>> 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)

            
    >>> seq = [34,67,8,123,4,100,94]
    >>> seq.sort()
    >>> seq
    [4, 8, 34, 67, 94, 100, 123]
    >>> search(seq,34)
    Traceback (most recent call last):
      File "<pyshell#174>", line 1, in <module>
        search(seq,34)
    TypeError: search() takes exactly 4 arguments (2 given)
    >>> search(seq,34,0,7)
    2
    >>>
    
    
小结:
    抽象
    函数定义
    参数
    作用域
    递归
    函数型编程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信知阁

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值