Python: Recursion only one output

Question:

I wanted to write a recursive function to fit curves. For some reasons my results didn’t looked good so I boiled down the problem to one easy example:

Number = 6
Successor = 0

def Fuction(Number, Successor):
    if (Number - Successor)+1>0:
       Successor += 1
       Fuction(Number, Successor)
    else:
        return(Fuction(Number, Successor))


A = Fuction(Number, Successor) 
print(f'The Successor of {Number} is {A}')

When I do this the Kernel dies. How can I fix it? (I followed the awnser : Why does my recursive function return none)

Asked By: Phicalc

||

Answers:

Maybe something like this?

Number = 6
Successor = 0

def Fuction(Number, Successor):
    if (Number - Successor) + 1 == 0: # base case for interrupting recursion
        return Successor
    Successor += 1
    return Fuction(Number, Successor)

A = Fuction(Number, Successor) # will be 7
print(f'The Successor of {Number} is {A}')

You can also do it like this which is more similar to your code example:

def Fuction(Number, Successor):
    if (Number - Successor) + 1 > 0:
        Successor += 1
        return Fuction(Number, Successor)
    return Successor
Answered By: Milos Stojanovic

The problem here is that the recursion does not terminate. The issue occurs when Number=6 and Successor=7, Fuction(6,7) just calls Fuction(6,7) again and again until the interpreter crashes due its recursion limit being exceeded. I believe this is when your kernel dies.

The solution here is to find the right base case for the recursion where it can return without making another recursive call.

Here’s a nice video explaining how to implement recursion.

Answered By: Abhilash
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.