Created
November 10, 2020 08:26
-
-
Save jeremy-rifkin/0685d9f421952f7424131768ba290ad5 to your computer and use it in GitHub Desktop.
To show a friend (who confused recursion and primative recursion) that the ackermann function can be computed without recursion.
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
# definition recursive ackermann | |
def A(m, n): | |
if m == 0: | |
return n + 1 | |
elif n == 0: | |
return A(m - 1, 1) | |
else: | |
return A(m - 1, A(m, n - 1)) | |
# non-recursive ackermann | |
# Explanation: Think rpn. Each iteration computes the result of A(m, n). | |
# Arguments are put onto the stack, each iteration pops two arguments pushes | |
# new arguments for recursion. Results are also placed onto the stack. | |
def B(m, n): | |
stack = [m, n] | |
while len(stack) > 1: | |
n, m = stack.pop(), stack.pop() | |
# compute ackermann | |
if m == 0: | |
#return n + 1 | |
stack.append(n + 1) | |
elif n == 0: | |
#return A(m - 1, 1) | |
stack.append(m - 1) | |
stack.append(1) | |
else: | |
#return A(m - 1, A(m, n - 1)) | |
stack.append(m - 1) | |
stack.append(m) | |
stack.append(n - 1) | |
return stack.pop() | |
for m in range(4): | |
for n in range(6): | |
print("{:10}".format(A(m, n)), end="") | |
print() | |
print() | |
for m in range(4): | |
for n in range(6): | |
print("{:10}".format(B(m, n)), end="") | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment