Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci numbers with memoization runs slow in Python?

Tags:

python

def fib(n):
    if n == 1:
        return 0
    if n == 2:
        return 1
    return fib(n-2) + fib(n-1)


def memo(f):
    cache = {}
    def memoized(n):
        if n not in cache:
            cache[n] = f(n)
        return cache[n]
    return memoized

fib1 = memo(fib)

This code runs really slow on my laptop, but if I change the name fib1 to fib, then everything works fine...anyone know the reason ? Thanks!

like image 502
Ang Avatar asked Mar 20 '26 20:03

Ang


2 Answers

fib recurses into fib, not fib1. If the memoized version has a different name it won't get used.

like image 183
Mark Ransom Avatar answered Mar 23 '26 09:03

Mark Ransom


In that code fib is the name of the non-memoized function. fib1 is the name you've given to the memoized function. But if you see your code, you'll see that it recursively calls fib the non-memoized version. Hence why you aren't getting a speed advantage.

like image 36
Winston Ewert Avatar answered Mar 23 '26 09:03

Winston Ewert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!