Created
February 26, 2013 19:25
-
-
Save lopuhin/5041302 to your computer and use it in GitHub Desktop.
stack-based emulation of recursive fibonacci function - turns out it is slower in pypy and cpython
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fib_rec(n): | |
if n <= 2: | |
return 1 | |
else: | |
return fib_rec(n - 1) + fib_rec(n - 2) | |
def fib_stack(n): | |
value_stack, op_stack = [], [n] | |
while True: | |
if not op_stack: | |
return value_stack[-1] | |
n = op_stack.pop() | |
if n is None: | |
value_stack.append(value_stack.pop() + value_stack.pop()) | |
elif n <= 2: | |
value_stack.append(1) | |
else: | |
op_stack.extend([None, n - 1, n - 2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment