Skip to content

Instantly share code, notes, and snippets.

@Noble-Mushtak
Last active December 2, 2019 14:28
Show Gist options
  • Save Noble-Mushtak/a633ec35cc649f86939dbee882af46dc to your computer and use it in GitHub Desktop.
Save Noble-Mushtak/a633ec35cc649f86939dbee882af46dc to your computer and use it in GitHub Desktop.
Iterative Implementation of Ackermann Function
import unittest
UNKNOWN = None
def ackermann(m, n):
last_answer = None
stack = []
stack.append((m, n))
while len(stack) > 0:
cur_m, cur_n = stack.pop()
if cur_n == UNKNOWN:
stack.append((cur_m, last_answer))
elif cur_m == 0:
last_answer = cur_n+1
elif cur_n == 0:
stack.append((cur_m-1, 1))
else:
stack.append((cur_m-1, UNKNOWN))
stack.append((cur_m, cur_n-1))
return last_answer
class AckermannTest(unittest.TestCase):
def test_ackermann(self):
for n in range(10):
self.assertEqual(ackermann(0, n), n+1)
for n in range(10):
self.assertEqual(ackermann(1, n), 2+(n+3)-3)
for n in range(10):
self.assertEqual(ackermann(2, n), 2*(n+3)-3)
for n in range(9):
self.assertEqual(ackermann(3, n), 2**(n+3)-3)
self.assertEqual(ackermann(4, 0), 13)
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment