Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the following recursive function not use the values in the cache to return the values?

I have created a python function to calculate the n-th fibonacci term. To increase the efficiency, I have used a cache_mem dict to store the variable. When I debugged the function, it is going through all function calls instead of using the stored variables of the cache. Why s this happening ?

cache_mem = {}

def fib(n):
    if n <= 1:
        return n
    else:
        cache_mem[n-1] = cache_mem.get(n-1, fib(n-1))
        cache_mem[n-2] = cache_mem.get(n-2, fib(n-2))

        return cache_mem[n-1] + cache_mem[n-2]

I expect the cache_mem dict to store the values of the results, and use them instead of calling the function. Based on my understanding, the line

cache_mem[n-1] = cache_mem.get(n-1, fib(n-1))

will check for the value for n-1 in the dict. If it exists, it will return the value, else it will calculate the values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The arguments to a function are all evaluated before calling the function. So when you write

cache_mem.get(n-1, fib(n-1))

it first has to execute fib(n-1) before calling cache_mem.get(). So the cache never prevents making the call.

Replace that with an explicit condition:

if n-1 not in cache_mem:
    cache_mem[n-1] = fib(n-1)

BTW, Python has a functools.cache decorator to add automatic caching to a function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading