one-file-projects/ackermann.py

21 lines
487 B
Python

cache = {}
def ack(m,n):
if (m,n) in cache:
return cache[(m,n)]
elif m == 0:
ans = n+1
elif n == 0:
ans = ack(m-1,1)
else:
ans = ack(m-1, ack(m, n-1))
cache[(m,n)] = ans
return ans
if __name__ == "__main__":
for i in range(6):
for j in range(6):
try:
print("ack(%d,%d) = %d" % (i,j, ack(i,j)))
except RuntimeError:
print("ack(%d,%d) = <StackOverflow>" % (i,j))