1

I am on python version 3.4.1 and when I run the code:

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.

2
  • How big is the number you input ? Commented Oct 23, 2014 at 18:13
  • Tried small cases like 3 4 5. Same error Commented Oct 23, 2014 at 18:14

3 Answers 3

3

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. Inside fibo, 0 fails the n == 1 or n ==2 condition, so fibo(n-1) is executed. Now the number is -1 because 0 - 1 == -1. This number also fails the n == 1 or n ==2 condition and fibo(n-1) is executed again. Now the number is -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.

Sign up to request clarification or add additional context in comments.

Comments

0

You start by trying to calculate fibo(0) which results in infinite recursion - do 'range(1,n)'

1 Comment

or just set the if-statement to if n <= 2:
0

Fibonacci recursion increases geometrically. 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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.