gpt4 book ai didi

python - python 文档中的这段斐波那契代码与我的重新实现相比有什么问题?

转载 作者:行者123 更新时间:2023-11-28 16:35:06 25 4
gpt4 key购买 nike

Python 文档:

>>> def fib(n):
a,b=0,1
while a<n:
print a,
a,b=b,a+b

>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

我的重新实现:

>>> def fib2(n):
a=0
b=1
while a<n:
print a
a=b
b=a+b

>>> fib2(2000)
0
1
2
4
8
16
32
64
128
256
512
1024

最佳答案

两者的区别

a,b=b,a+b

a=b
b=a+b

是在第二个中,a被赋值为b,然后b被赋值为a的和b,表示它是原始值的两倍。

考虑:

a = 1
b = 2
a,b = b,a+b

这给出了

a==2 (old value of b)
b==3 (sum of 1 and 2)

反之:

a = 1
b = 2
a = b
b = a + b

给出:

a==2 (old value of b)
b==a+b==2+2==4 (twice the old value of b)

关于python - python 文档中的这段斐波那契代码与我的重新实现相比有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27345831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com