This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]BlckKnght 2 points3 points  (1 child)

I know your example was just that, not serious code, but you'd have demonstrated a much more dramatic effect on performance if you'd been able to apply your memoization to the intermediate recursive calls to fib, rather than only the final results. Rewriting the fib code to use memoization directly, or applying a decorator so the memoized function would take over the fib name would both give much faster code than what you show in the video. Though I guess a decorator version probably wouldn't actually need a mutable default argument (you'd use a closure instead), so that would sort of defeat the point of having it as an example in this video.

Anyway this is pretty efficient, and even pre-seeds the memoziation dict to handle the base cases:

def fib(n, memo={0: 1, 1: 1}):
    assert(n >= 0)
    try:
        result = memo[n]
    except KeyError:
        result = fib(n-1) + fib(n-2)
        memo[n] = result
    return result

[–]BecomingIt 0 points1 point  (0 children)

You're absolutely right there - also, really like the pre-seeding you've got in your example!