如何将Fibonacci序列保存到列表中?

时间:2018-05-08 11:52:00

标签: python python-3.x list recursion

def fibonacci(n): 
    lst = []
    if n == 0:   
        return 0  
    elif n == 1:  
        return 1  
    else :  
        f = fibonacci(n - 1) + fibonacci(n - 2)
        return f

h = fibonacci(4)

但我想得到一个这样的列表:[0, 1, 1, 2, 3, ......] 怎么弄明白?

3 个答案:

答案 0 :(得分:1)

这是一个非常低效的解决方案,但根据您当前的逻辑,您只需将maplist一起使用:

h = list(map(fibonacci, range(10)))

print(h)

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

答案 1 :(得分:0)

def fibonacci(n):
    lst = [0, 1]
    if n == 0:
        return [0]
    for i in range(2, n+1):
        lst.append(lst[i - 1] + lst[i - 2])
    return lst

print(fibonacci(0))  # ->[0]
print(fibonacci(1))  # ->[0,1]
print(fibonacci(2))  # ->[0,1,1]
print(fibonacci(3))  # ->[0,1,1,2]
print(fibonacci(4))  # ->[0,1,1,2,3]
print(fibonacci(10)) # ->[0,1,1,2,3,5,8,13,21,34,55]

OR

如果您希望fibonacci(0)返回[]

def fibonacci(n):
    lst = [0, 1]
    if n == 0:
        return []
    if n == 1:
        return [0]
    for i in range(2, n):
        lst.append(lst[i - 1] + lst[i - 2])
    return lst


print(fibonacci(0))  # ->[]
print(fibonacci(1))  # ->[0]
print(fibonacci(2))  # ->[0,1]
print(fibonacci(3))  # ->[0,1,1]
print(fibonacci(4))  # ->[0,1,1,2]
print(fibonacci(10)) # ->[0,1,1,2,3,5,8,13,21,34]

答案 2 :(得分:0)

也是一种可能性(不适用于n<2,但这是一个简单的修复......):

def fib(n, lst=None):
    if lst is None:
        lst = [0, 1]
    while len(lst) < n:
        lst.append(lst[-2] + lst[-1])
    return lst