斐波那契和非斐波那契编码

发布于 2024-12-26 05:22:22 字数 426 浏览 1 评论 0原文

我很抱歉,因为这可能是一个常见问题,但我认为我正在寻找一个在其他主题中找不到的非常具体的答案。基本上,我对添加数字的流程感到很困惑。这是两个类似的代码,它们以不同的方式计算数字。对此有什么简单的解释吗?

>>> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

狼性发作 2025-01-02 05:22:22

区别在于交换时的值是什么

a, b = b, a+b

将 a 设置为 b 并将 a 设置为 a+b 但交换是相对同时完成的,因此不是按顺序,即 b 中的更改不考虑 a 首先更改。

在第二个示例中,

a = b

b = a+b

值已更改,第二条语句尊重第一个语句的更改

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

a = b

b = a+b

the values are changed and the 2nd statement respects the change of the first

夏尔 2025-01-02 05:22:22

交换存在优先级差异。
在第一个示例中,您分配:
一个= 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.

↙厌世 2025-01-02 05:22:22

第一个代码示例中的分配同时发生,第二个代码示例中的分配连续发生,从而导致不同的答案。

The assignments happen at the same time in the 1st code example, and serially in the 2nd, leading to a different answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文