Using a Python Dictionary to Cache Results of a Recursive Function

 I used recursive functions to calculate factorials. I created my own dictionary to cache the results of successive calculations. 


#with caching, using my own dictionary

cache={}

def factorial(n):

    if n<=1:       #this is the base case

        return 1

    else:

        cache[n-1]=factorial(n-1)

        cache[n]=cache[n-1]*n     #we don't get to this line until previous line has got to n=1

        return cache[n]

# ask user to input a number the factorial of which the user wishes to find

num= int(input("What number? "))

print(num,'! = ',factorial(num))     # the recursive factorial function is called here


print("Now I will print the dictionary's contents.")

#print out the dictionary

for key, value in cache.items():

    print(f'key:{key}, value:{value}')


Click on this image to increase its size and see the results of running the code twice.


Comments