简体   繁体   English

Fibonacci错误:相比之下超出了最大递归深度

[英]Fibonacci error: maximum recursion depth exceeded in comparison

I am on python version 3.4.1 and when I run the code: 我在python版本3.4.1和运行代码时:

def fibo(n):
    if n == 1 or n ==2:
        return 1
    else:
        return fibo(n-1)+fibo(n-2)

print("input number for fibonacci seq list")
num = int(input())
for i in range(0,num):
    print(str(fibo(i)))

I would want the code to give me a list of the fibonacci numbers that the user input but I get the error mentioned in the title. 我希望代码给我一个用户输入的斐波那契数字列表,但我得到标题中提到的错误。 I am not sure why. 我不知道为什么。

I am not sure why. 我不知道为什么。

Let me explain what is going on. 让我解释一下发生了什么。

At this part: 在这一部分:

for i in range(0,num):
    print(str(fibo(i)))

the first number i passed to fibo is 0 because range(0,num) starts at 0 . 所述第一数目i传递给fibo0 ,因为range(0,num)开始于0 Inside fibo , 0 fails the n == 1 or n ==2 condition, so fibo(n-1) is executed. fibo内部, 0n == 1 or n ==2条件下失败,因此执行fibo(n-1) Now the number is -1 because 0 - 1 == -1 . 现在数字是-1因为0 - 1 == -1 This number also fails the n == 1 or n ==2 condition and fibo(n-1) is executed again. 该数字也未通过n == 1 or n ==2条件,并再次执行fibo(n-1) Now the number is -2 . 现在数字是-2

Hopefully, you see where this is going. 希望你能看到它的发展方向。 The number is decreased indefinitely until fibo reaches Python's maximum recursion depth and thereby raises an error. 数量无限减少,直到fibo达到Python的最大递归深度,从而引发错误。

首先尝试计算fibo(0),这会产生无限递归 - 做'范围(1,n)'

Fibonacci recursion increases geometrically. Fibonacci递归在几何上增加。 It is better to use iteration or a generator. 最好使用迭代或生成器。

Here's a generator: 这是一个发电机:

>>> def fibgen():
...   a,b=1,1
...   while True:
...     yield a
...     a,b=b,a+b
...
>>> i = fibgen()
>>> next(i)
1
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
5
>>> i=fibgen()
>>> [next(i) for _ in range(10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

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

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