简体   繁体   中英

Fibonacci series by recursive function in Python

Hello I am trying to generate Fibonacci series by using a recursive function in 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?!

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 ; appending to one does not change the list1 value in the calling program. 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) ).

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. Doing fibolist(n-1).append(...) updates the list returned by the next level but that is a separate list so list1 is not affected.

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) .

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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