简体   繁体   English

斐波那契数列乘法

[英]Fibonacci sequence multiplying

I tried to make the fibonacci sequence with the following code: 我试图用以下代码制作斐波那契数列:

def fibonacci(n): # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a = 0
    b = 1
    the_list = []
    while n > len(the_list):
        the_list.append(a)
    #By saying a = b and b = a+b we define the
    #fibonacci sequence, since this is how the
    #fibonacci sequence works.
        a = b
        b = a+b
    print the_list
# Now call the function we just defined:
fibonacci(10)

As far as I know this code should do it but instead of giving me the fibonacci sequence its giving the following output: 据我所知,该代码应该执行此操作,但与其给我斐波那契序列,不如给出以下输出:

[0, 1, 2, 4, 8, 16, 32, 64, 128, 256]

So my fibonacci sequence is multiplying instead of working correcly. 所以我的斐波那契数列是乘法而不是正确地工作。 I have no idea why because i thought 我不知道为什么,因为我想

a = b
b = a+b

should do the trick, if i look at my while loop the statements for this loop are also correct, so I just dont get it why i dont get the right output. 应该可以解决问题,如果我看看我的while循环,这个循环的语句也是正确的,所以我只是不明白为什么我没有得到正确的输出。

So if someone could explain me why this code is not working it would be highly appriciated 因此,如果有人可以向我解释为什么此代码无法正常工作,那么它会受到高度重视。

Your code is creating an exponential sequence because of a logic flaw. 由于逻辑缺陷,您的代码正在创建指数序列。 Based on your code: 根据您的代码:

Start:
a = 0
b = 1

1st iteration:
a = b = 1
b = a + 1 = 1 + 1 = 2

2nd iteration:
a = b = 2
b = a + 2 = 2 + 2 = 4

As you can see the fact that you set a before performing the b calculation causes your issue. 如您所见,在执行b计算之前设置a会导致问题。

Instead you need would something like (to prove the point): 相反,您需要以下内容(证明这一点):

tmp = a
a = b
b = tmp + a

A little extra math would eliminate the need for the extra variable: 进行一些额外的数学运算将消除对额外变量的需要:

b += a
a = b - a

But the easiest (and most pythonic) way would be: 但是最简单(也是最pythonic)的方式是:

a, b = b, a + b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM