Created
September 22, 2014 10:55
-
-
Save m1el/7fb089e87dae63c7ee5c to your computer and use it in GitHub Desktop.
non-recursive implementation of Ackermann function
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 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