• 函数-函数进阶-斐波那契


    我们讲过,generator保存的是算法,每次调用next(g) 就计算出g 的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出stopIteration 的错误

    当然,上面这种不断调用 next(g) 实在是太变态了,正确的方法是使用for循环,因为generator也是可迭代对象:

    >>> g = (x*x for x in range(10))
    >>> for n in g:
    ...  print(n)
    ...
    0
    1
    4
    9
    16
    25
    36
    49
    64
    81
    >>>

    所以,我们创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。

    generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for循环无法实现的时候,还可以用函数来实现。

    比如,著名的斐波那契(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:

    1,1,2,3,5,8,13,21,34,。。。。

    斐波那契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易:

    def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
    print(b)
    a, b = b, a+b
    n = n + 1
    return 'done'


    注意,赋值语句:
    a,b = b, a+b

    def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
    yield b
    a, b = b, a+b
    n = n + 1
    return 'done'

    print(fib(10))
    执行结果:
    <generator object fib at 0x00000200080FAA98>


    def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
    yield b
    a, b = b, a+b
    n = n + 1
    return 'done'
    f = fib(10)
    print(fib(10))
    print(next(f))
    print(next(f))
    print(next(f))
    print(next(f))
    print(next(f))
    print(next(f))

    执行结果:
    <generator object fib at 0x000001EEC0AAAB88>
    1
    1
    2
    3
    5
    8

    for i in f:
      print(i)
    执行结果:
    <generator object fib at 0x00000261EB7EAB88>
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55

    yield b #把函数的执行过程冻结在这一步,并且把B的值 返回给外面的next()
    
    
  • 相关阅读:
    C#动态调用webservice方法
    WinForm客户端调用 WebService时 如何启用Session
    C# 调用 Web Service 时出现 : 407 Proxy Authentication Required错误的解决办法
    ms sql 在任何位置 添加列
    Python requests
    LookupError: unknown encoding: cp65001
    [转]HTTP请求模型和头信息参考
    【原】使用StarUML画用例图
    【微信转载】Google是如何做测试的
    手机SD卡损坏补救措施
  • 原文地址:https://www.cnblogs.com/kingforn/p/10937424.html
Copyright © 2020-2023  润新知