Home > front end >  Return Parameters from a Recursive function in python
Return Parameters from a Recursive function in python

Time:10-27

sorry if this is a noob question, I wasn't able to find a solution online (maybe I just don't know what to search for).

How do I return the "found" dictionary from this recursive function (I am only able to return the nth number)

Note: simply returning found at the end does not work for multiple reasons

# Nth Fibonacci number generator
def nth_Rfib(n, found = {0:1, 1:1}):
    if n in found:
        return found[n]
    else:
        found[n] =  nth_Rfib(n-1, found)   nth_Rfib(n-2, found)
    #print(found)
    return found[n] # return found ** Doesn't Work **

print(nth_Rfib(5))  # 8
# instead, it should return: {0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}

Thank you.

CodePudding user response:

In both cases, you need to return found. But as your function returns dictionary, you need to access a needed value when you call it recursevly:

def nth_Rfib(n, found = {0:1, 1:1}):
    if n in found:
        return found
    else:
        found[n] =  nth_Rfib(n-1, found)[n-1]   nth_Rfib(n-2, found)[n-2]
    return found

print(nth_Rfib(5))

this returns:

{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}

Note a possible issue with default mutable arguments like your found = {0:1, 1:1}, for example:

>>> print(nth_Rfib(3))
{0: 1, 1: 1, 2: 2, 3: 3}
>>> print(nth_Rfib(5))
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}
>>> print(nth_Rfib(3))
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}

nth_Rfib(3) after nth_Rfib(5) returns the same dictionary, because you never reset it to the default {0:1, 1:1}.

CodePudding user response:

You need a function that returns a number, so that the recursive expression

found[n] = fib(n-1)   fib(n-2)

can make sense; and you also need a function that returns a dictionary, since that's what you want to return, ultimately.

Hence it makes sense to define two distinct functions, one that returns a number, and one that returns a dict.

def nth_Rfib(n):
    found = {0: 0, 1: 1}
    def fib(n):
        if n not in found:
            found[n] = fib(n-1)   fib(n-2)
        return found[n]
    fib(n)
    return found

This makes found a variable which is local to nth_Rfib, but acts like a global variable during the recursive calls of fib.

It also completely eliminates any oddities of mutable default arguments.

>>> nth_Rfib(10)
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21, 9: 34, 10: 55}
>>> nth_Rfib(3)
{0: 0, 1: 1, 2: 1, 3: 2}
  • Related