 Collected 179 code examples. Learn by example while getting your job done as quickly as possible.

Edit example

How do I create recursive ackermann function in Python?

Viewed 189 times.

• Example

def ackermann(m, n):
if m == 0:
return n + 1
if n == 0:
return ackermann(m - 1, 1)
return ackermann(m - 1, ackermann(m, n - 1))

for i in range(0, 6):
for j in range(0, 6):
print(f'ackermann({i}, {j}) = {ackermann(i, j)}')

Copy code to clipboard

Output

ackermann(0, 0) = 1
ackermann(0, 1) = 2
ackermann(0, 2) = 3
ackermann(0, 3) = 4
ackermann(0, 4) = 5
ackermann(0, 5) = 6
ackermann(1, 0) = 2
ackermann(1, 1) = 3
ackermann(1, 2) = 4
ackermann(1, 3) = 5
ackermann(1, 4) = 6
ackermann(1, 5) = 7
ackermann(2, 0) = 3
ackermann(2, 1) = 5
ackermann(2, 2) = 7
ackermann(2, 3) = 9
ackermann(2, 4) = 11
ackermann(2, 5) = 13
ackermann(3, 0) = 5
ackermann(3, 1) = 13
ackermann(3, 2) = 29
ackermann(3, 3) = 61
ackermann(3, 4) = 125
ackermann(3, 5) = 253
ackermann(4, 0) = 13
RecursionError: maximum recursion depth exceeded in comparison