斐波那契和非斐波那契编码
我很抱歉,因为这可能是一个常见问题,但我认为我正在寻找一个在其他主题中找不到的非常具体的答案。基本上,我对添加数字的流程感到很困惑。这是两个类似的代码,它们以不同的方式计算数字。对此有什么简单的解释吗?
>>> a = 0
>>> b = 1
>>> while b <1000:
print b
a, b = b, a+b
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987
>>> a =0
>>> b=1
>>> while b<1000:
print b
a = b
b = a+b
1,2,4,8,16,32,64,128,256,512
I apologize since this might be a common question, but I think I am looking for a quite specific answer that wouldn't be found in other topics. Basically, I am quite confused about the flow of adding numbers. Here are two similar codes that compute numbers differently. Is there any simple explanation for this?
>>> a = 0
>>> b = 1
>>> while b <1000:
print b
a, b = b, a+b
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987
>>> a =0
>>> b=1
>>> while b<1000:
print b
a = b
b = a+b
1,2,4,8,16,32,64,128,256,512
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
区别在于交换时的值是什么
a, b = b, a+b
将 a 设置为 b 并将 a 设置为 a+b 但交换是相对同时完成的,因此不是按顺序,即 b 中的更改不考虑 a 首先更改。
在第二个示例中,
值已更改,第二条语句尊重第一个语句的更改
The difference lies in what the values are WHEN swapped
a, b = b, a+b
sets a to b and sets a to a+b but the swaps are done relatively at the same time so it's not in order, ie the change in b doesn't respect that a was changed first.
In the second example
the values are changed and the 2nd statement respects the change of the first
交换存在优先级差异。
在第一个示例中,您分配:
一个= 1
b = 1
在第二个示例中,您要分配:
一个= 1
b = 2
为了实现与第一个示例相同的操作顺序,您必须使用临时变量。
There is a precedence difference in the swap.
In the first example you are assigning:
a = 1
b = 1
In the second example you are assigning:
a = 1
b = 2
In order to achieve the same order of operations as the first example you'll have to use a temp var.
第一个代码示例中的分配同时发生,第二个代码示例中的分配连续发生,从而导致不同的答案。
The assignments happen at the same time in the 1st code example, and serially in the 2nd, leading to a different answer.