Skip to content

Instantly share code, notes, and snippets.

@redwrasse
Created May 19, 2020 19:36
Show Gist options
  • Save redwrasse/a27eb69b8f29f205bf34ea755f880c0b to your computer and use it in GitHub Desktop.
Save redwrasse/a27eb69b8f29f205bf34ea755f880c0b to your computer and use it in GitHub Desktop.
simple stack-based computations
# stack_computations.py
"""
Simple example stack computations
"""
"""
Stack diagram
f(n)
f(n-1)
..
..
stack computation: push f(n), push f(n-1),.., 1, ... pop f(n-1), pop f(n)
"""
def f(n):
if n == 1:
return 1
else:
return n * f(n - 1)
def stack_f(n):
stack = []
while n >= 1:
stack.append(n)
n -= 1
returnv = 1
# in this case the stack item calculation is
# to multiply the current int value times the returned value
# of the previous stack calculation
while stack:
m = stack.pop()
returnv = returnv * m
return returnv
for i in range(1, 10):
print(f'factorial of {i}: {f(i)} stack result: {stack_f(i)}')
"""
call dependency tree
main
/ \
h(3) g(4)
push main, push h(3), pop h(3), push g(4), pop g(4), pop main
"""
def main():
a = 3
b = 4
return h(a) * g(b)
def stack_main():
stack = list()
stack.append(main)
stack.append((h, 3))
func, val = stack.pop()
res1 = func(val)
stack.append((g, 4))
func2, val2 = stack.pop()
res2 = func2(val2)
res = res1 * res2
return res
def g(n):
return n**2
def h(n):
return n + 3
print(f"\nmain(): {main()} stack_main(): {stack_main()}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment