斐波那契数列,并传回其斐波那契数

时间:2019-11-20 13:31:13

标签: python python-3.x

我正在尝试实现将打印一些斐波那契数字的功能。例如,如果我的输入是fibonacci([0,1,2,3],则输出将为0,1,1,2。

我不确定该如何进行。

def fibonacci(n):

    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n-2)

    while True:
        n.append(n)

print(fibonacci[5,10,11])

2 个答案:

答案 0 :(得分:1)

您可以稍微重构代码并获取:

def fibonacci(lst):
    def getTerm(n):
        if n == 0:
            return 0
        elif n == 1:
            return 1
        return getTerm(n - 1) + getTerm(n-2)
    return [getTerm(x) for x in lst]

给出输出:

>>> fibonacci([0,1,2,3])
[0, 1, 1, 2]
>>> fibonacci([5,10,11])
[5, 55, 89]

答案 1 :(得分:0)

避免重复计算:

def fibonacci(indices):
    fibs = {}
    set_of_indices = set(indices)
    f0 = fibs[0] = 0
    f1 = fibs[1] = 1
    for i in range(2,max(indices)+1):
        f2 = f0+f1
        if i in set_of_indices:
            fibs[i] = f2
        f0,f1=f1,f2
    return [fibs[i] for i in indices]