gpt4 book ai didi

Python(斐波纳奇数列): trying to understand what is the difference between a, b = b, a + b OR a = b & a = a + b

转载 作者:太空狗 更新时间:2023-10-30 01:50:03 28 4
gpt4 key购买 nike

我不确定这个问题的标题是什么,这也可能是一个重复的问题。所以请相应地指导。

我是 python 编程的新手。我有这个简单的代码来生成斐波那契数列。

1: def fibo(n):
2: a = 0
3: b = 1
4: for x in range(n):
5: print (a, end=' ')
6: #a, b = b, a+b
7: a = b
8: b = a+b
9: print()
10: num = int(input("enter n value: "))
11: print(fibo(num))

如果我按原样执行上面的代码,得到的结果如下

enter n value: 10
0 1 2 4 8 16 32 64 128 256

如果取消注释 #6 和注释行 #7 和 #8,我得到的结果是实际的 fibo 系列。

enter n value: 10
0 1 1 2 3 5 8 13 21 34

我想知道有什么区别

a, b = b, a + b 

a = b
b = a + b

使用的编程IDE:PyCharm Community 2017.3

最佳答案

a = b
b = a + b

实际上是:

a = b
b = b + b

你想要的是:

a = b
b = old_value_of_a + b

当你这样做时a, b = b, a + b它确实在做:

tmp_a = b
tmp_b = a + b
a = tmp_a
b = tmp_b

这是你想要的

关于Python(斐波纳奇数列): trying to understand what is the difference between a, b = b, a + b OR a = b & a = a + b,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48072131/

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