简体   繁体   English

Python中递归函数的斐波那契数列

[英]Fibonacci series by recursive function in Python

Hello I am trying to generate Fibonacci series by using a recursive function in python.您好,我正在尝试通过在 python 中使用递归函数来生成斐波那契数列。

Here is my code这是我的代码

def fibolist(n):
    list1 = [1, 1]
    if n in (1,2) :
        return list1
    else:
        fibolist(n-1).append(sum(fibolist(n-1)[n-3:]))
        return list1

but when I enter any number as an argument, the result is [1, 1] Could you please help me?!但是当我输入任何数字作为参数时,结果是[1, 1]你能帮我吗?!

You start with你开始

list1 = [1, 1]

You never change that value, and then you return it to the calling routine.您永远不会更改该值,然后将其返回到调用例程。

Each invocation of fibolist has a local variable named list1 ; fibolist每次调用都有一个名为list1的局部变量; appending to one does not change the list1 value in the calling program.追加到一个改变list1中调用程序价值。 You need to explicitly do that.你需要明确地这样做。 Try尝试

else:
    return fibolist(n-1) + [sum(fibolist(n-1)[n-3:])]

Just to fix your code:只是为了修复您的代码:

def fibolist(n):
    if n in (0,1) :
        return [1,1]
    else:
        return fibolist(n-1)+[sum(fibolist(n-1)[n-2:])]

Few notes:几点注意事项:

lists in python have starting index=0, so it's better start with it (unless you want to put start return to [0,1,1] for n in (1,2) ). python中的列表有起始索引= 0,所以最好从它开始(除非你想把 start return 到[0,1,1] for n in (1,2) )。

Also - as already mentioned you shouldn't return local variable, which you preassign in each go.另外 - 正如已经提到的,你不应该返回局部变量,你每次都预先分配。

Your code is not updating the list1 variable that it returns upon coming back from the recursion.您的代码不会更新从递归返回时返回的 list1 变量。 Doing fibolist(n-1).append(...) updates the list returned by the next level but that is a separate list so list1 is not affected.执行fibolist(n-1).append(...)更新下一级返回的列表,但这是一个单独的列表,因此list1不受影响。

You could also make your function much simpler by making it pass the last two values to itself:您还可以通过将最后两个值传递给自身来使您的函数更简单:

def fibo(n,a=1,b=1): return [a] if n==1 else [a] + fibo(n-1,b,a+b)

BTW, the modern interpretation of the fibonacci sequence starts at 0,1 not 1,1 so the above signature should be def fibo(n,a=0,b=1) .顺便说一句,斐波那契数列的现代解释从 0,1 而不是 1,1 开始,所以上面的签名应该是def fibo(n,a=0,b=1)

Output:输出:

print(fibo(5))
#[1, 1, 2, 3, 5]

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

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