您能告诉我代码有什么问题吗?

时间:2019-07-14 07:18:58

标签: python python-3.x recursion fibonacci

当我调用fib函数时,它不返回任何内容。你能告诉我我做错了什么吗?

def fib(n, List = []):
    if n > 0:
        if len(List) == 0 or len(List) == 1:
            List.append(1)
        else:
            List.append(List[len(List) - 2] + List[len(List) - 1])
        fib(n - 1, List)
    else:
        return List

l = fib(5)
print(l)  # >> None

1 个答案:

答案 0 :(得分:1)

fib(n - 1, List)更改为return fib(n - 1, List)

def fib(n, List = []):
    if n > 0:
        if len(List) == 0 or len(List) == 1:
            List.append(1)
        else:
            List.append(List[len(List) - 2] + List[len(List) - 1])
        return fib(n - 1, List)
    else:
        return List