我尝试在python中生成斐波那契,但我注意到,如果我通过交换来实现,那么它给我的价值将与我通过简单赋值来实现的价值不同
def fib_num(max):
a = 0
b = 1
for i in range(max):
# a,b = b+a,a this way it is right
# but if I will implement it like below with simple assigment,
# I am not going to get the same result Why???
a = b+a
b = a
yield a
答案 0 :(得分:2)
多次分配正在为您隐式创建一个临时变量。您的代码为a
分配了一个新值,当您再次使用它时,它将具有 new 值,而不是旧值:
a = b + a
b = a
正确的等效解决方案是:
temp = a
a = b + a
b = temp