Python Recursion Error: RecursionError: maximum recursion depth exceeded while calling a Python object

Night Balasingham :

I'm trying to build a function that will take in a number and then use recursion to print out a Fibonacci sequence and end the sequence on the number. So if I have a sequence that starts on 0 and 1 if the users input is 4 it will return 0,1,1,2,3. I am getting this RecursionError:

RecursionError: maximum recursion depth exceeded while calling a Python object

This is my code:

num = input("Give me a number.")
def fib(n):
  n = int(n)
  if n == 0:
    return 1
  return fib(n - 1) + fib(n - 2)
print(fib(num))
ePi272314 :

Two problems

There are two problems with your code:

  • There is an infinite loop, which generates the RecursionError exception
  • It is impossible to retrieve all terms of the sequence (you said you want to print all the sequence, not only the last term)

The infinite loop

Try the code below. I just added n==1 as another stop condition.

def fib(n):
    n = int(n)
    if n == 0 or n == 1:  # Changed here
        return 1
    return fib(n - 1) + fib(n - 2)

num = input("Give me a number: ")

print(fib(num))

The case f(1)=1 is required by definition (see here).
Or just debugging your code, you will realize that the loop will never end for fib(1) because it returns:
f(1-1) + f(1-2) >>> f(0) + f(-1) >>> 1 + infinite loop.

Printing all terms

You could try to use lists in your recursive code, which is tricky to do or perhaps change to a version with loops.

With loops:

# A version using a while loop
# This code returns the list of terms
def fib(n):

    n=int(n)
    terms = []

    i=0
    while i<=n:
        if i==0 or i==1:
            terms.append(1)
        else:
            terms.append(terms[-2]+terms[-1])
        i+=1

    return terms

Recursive:

Working on it

Try all these examples here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297772&siteId=1