有关python 生成器 yield 的小实例----生成斐波那契数列

使用生成器主要目的是为了不在程序开始运行之时占用大量系统内存, 防止系统杀死进程.或者出现MemoryError (32bit的Python使用内存超过2G之后,就报这个错误)
接下来会用常规方法和生成器2种方式生成斐波那切数列, 废话不多说,直接上代码:
一般方法:

f_n = [0,1]

def f_num(n_len):
    for i in range(n_len-2):
        a = f_n[i]
        b = f_n[i+1]
        a, b = b ,a+b   
        f_n.append(b)
        i += 1

f_num(10)

print(f_n)

================== RESTART: C:\Users\yzh\Desktop\斐波那契数列.py ==================
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

生成器:

f_n = [0,1]

def make_fn(n_len):
    while len(f_n) < n_len:
        a = f_n[-2]
        b = f_n[-1]
        a, b = b, a+b
        yield b

new_num = make_fn(10)

for i in range(8):
    f_n.append(next(new_num))

print(f_n)

==================== RESTART: C:\Users\yzh\Desktop\fb.py ====================
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

猜你喜欢

转载自blog.csdn.net/weixin_40624269/article/details/82284091