Skip to content

Instantly share code, notes, and snippets.

@m1el
Created September 22, 2014 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1el/7fb089e87dae63c7ee5c to your computer and use it in GitHub Desktop.
Save m1el/7fb089e87dae63c7ee5c to your computer and use it in GitHub Desktop.
non-recursive implementation of Ackermann function
def ack_rec(m, n):
print(m, n)
if m == 0:
return n + 1
elif n == 0:
return ack_rec(m-1, 1)
else:
return ack_rec(m-1, ack_rec(m, n-1))
def ack_norec(m, n):
stack = [(m, n, 0)]
res = 0
while len(stack) > 0:
(m, n, r) = stack.pop()
if r == 1:
n = res
if m == 0:
res = n + 1
elif n == 0:
stack.append((m-1, 1, 0))
else:
stack.append((m-1, 0, 1))
stack.append((m, n-1, 0))
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment