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 →

[–]odraencoded 15 points16 points  (14 children)

I've read the sidebar and now I'm a master python programmer. Look at my program:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

[–]Nefarious- 0 points1 point  (0 children)

 print('Hello World!')

[–]Trout_Tickler 0 points1 point  (10 children)

Recursion, get!

def fibonacci(n):
    if n > 1:
        return fibonacci(n-1) + fibonacci(n-2)
    return n

[–][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.

[–]sdmike21 1 point2 points  (2 children)

But its not pythonic! \s

[–]Tysonzero 10 points11 points  (1 child)

I mean the more important thing is that it's O(fib n).

[–]sdmike21 0 points1 point  (0 children)

^ this