【高级特性】生成器

'''
    生成器的使用
'''


# 通过生成器实现斐波那契数列
def fbnq(max):
    a, b, n = 1, 0, 0
    while n < max:
        yield a
        c = a
        a = a + b
        b = c
        n = n + 1

# 通过map和递归实现斐波那契数列
def fbnq_rev(max):
    if max == 1 or max == 2:
        return 1
    return fbnq_rev(max-1) + fbnq_rev(max - 2)


if __name__ == '__main__':
    print([x for x in fbnq(5)])
    print(list(map(fbnq_rev, range(1, 6))))

运行结果:

[1, 1, 2, 3, 5]
[1, 1, 2, 3, 5]

猜你喜欢

转载自www.cnblogs.com/biexei/p/11674446.html