斐波拉契数列(Fibonacci)实现

著名的斐波拉契数列(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      # 赋值语句,相当于:t = (b, a + b)  a = t[0]  b = t[1],t是一个tuple
        n = n + 1
    return 'done'

ret = fib(10)                # n为希望生成的斐波那契数列数量
print(ret)                   # 打印函数返回值 

生成器方式实现斐波那契数列:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b      # 赋值语句,相当于:t = (b, a + b)  a = t[0]  b = t[1],t是一个tuple
        n = n + 1
    return 'done'

# for循环访问,无法获取函数返回值
# for i in fib(10):            # n为希望生成的斐波那契数列数量
#     print(i)

# next()访问
g = fib(10)
while True:
    try:
        print(next(g))          # 等价于print(g.__next__())
    except StopIteration as e:
        print(e.value)          # 打印函数返回值
        break
posted @ 2018-06-12 16:29  Joe1991  阅读(178)  评论(0)    收藏  举报