Skip to content

Instantly share code, notes, and snippets.

@lopuhin
Created February 26, 2013 19:25
Show Gist options
  • Save lopuhin/5041302 to your computer and use it in GitHub Desktop.
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
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