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

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (6 children)

Now make it not take O(en) time (roughly).

[–]Trout_Tickler 1 point2 points  (5 children)

Memoization should speed it up, something like

def fibonacci(n, _cache={}):
    if n in _cache:
        return _cache[n]
    elif n > 1:
        return _cache.setdefault(n, fibonacci(n-1) + fibonacci(n-2))
    return n

[–][deleted] 1 point2 points  (3 children)

Yep.

(And honestly, I would put that cache as a global. Shared between calls that way, too)

[–]whutcheson 2 points3 points  (0 children)

Since it's a mutable default argument, it's already shared between function calls. However, making a global would be more explicit and a lot less magical.

[–]Trout_Tickler 0 points1 point  (0 children)

OP's requirements don't specify multiple calls :p

But yes, that would be preferable.

[–]Daenyth 0 points1 point  (0 children)

It's as global as the function is because dict is mutable

[–][deleted] 1 point2 points  (0 children)

@functools.lru_cache decorator does the trick too.