0

我正在阅读的教程有以下程序

# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
    count = count + 1
    old_a = a    # we need to keep track of a since we change it
    print(old_a,end=" ")   # Notice the magic end=" " in the print function arguments that
                           # keeps it from creating a new line
    a = b
    b = old_a + b
print() # gets a new (empty) line

代码很完美。但是,我无法弄清楚如何计算序列。如何更改值以创建序列?

4

2 回答 2

0

如果您删除所有这些无关代码,它会更有意义:

while count < max_count:
    old_a = a
    a = b
    b = old_a + b

old_a可能会让你感到困惑。这是写这个的漫长道路:

a, b = b, a + b

ab和(同时)交换,ba + b。请注意,它编写不同:

a = b
b = a + b

因为当你重新定义b时,a已经拥有它的新值,即等于b

我还会通过在纸上写下来手动运行代码。

于 2013-03-25T09:53:08.597 回答
0

此代码工作正常:

a, b = 0, 1
for _ in range(20):
        print a
        a, b = b, a+b
于 2013-03-25T10:01:09.467 回答