Skip to content

Commit f6bc32e

Browse files
committed
Added the Python function to evaluate the Ackermann function to the session02 directory of my student directory
1 parent 15615e6 commit f6bc32e

File tree

1 file changed

+78
-0
lines changed
  • Students/imdavis/session02

1 file changed

+78
-0
lines changed

Students/imdavis/session02/ack.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#!/usr/bin/env python2.7
2+
# -*- coding: utf-8 -*-
3+
4+
"""Example of a recursive function with a good docstring.
5+
6+
For best results to view the docstring, after importing do:
7+
8+
>>> print ack.__doc__
9+
10+
Its value grows rapidly, even for small inputs. For example A(4,2) is an
11+
integer of 19,729 decimal digits. May hit maximum recursion limit. See:
12+
13+
sys.getrecursionlimit()
14+
sys.setrecursionlimit()
15+
16+
"""
17+
18+
def ack(m, n):
19+
"""Evaluation of the Ackermann Function.
20+
21+
The Ackermann Function is defined as:
22+
A(m, n) =
23+
n+1 if m = 0
24+
A(m−1, 1) if m > 0 and n = 0
25+
A(m−1, A(m, n−1)) if m > 0 and n > 0
26+
27+
Args:
28+
m (int): must be >= 0
29+
n (int): must be >= 0.
30+
31+
Yields:
32+
Evaluation of Ackermann function for A(m, n)
33+
34+
"""
35+
36+
if (m < 0 or n < 0):
37+
print "Arguments for the Ackermann function must be >= 0."
38+
return None
39+
elif (m == 0):
40+
return n + 1
41+
elif (n == 0):
42+
return ack(m - 1, 1)
43+
else:
44+
return ack(m - 1, ack(m, n - 1))
45+
46+
if __name__ == '__main__':
47+
TestsPass = True
48+
49+
try:
50+
assert ack(0, 0) == 1
51+
assert ack(0, 1) == 2
52+
assert ack(0, 2) == 3
53+
assert ack(0, 3) == 4
54+
assert ack(0, 4) == 5
55+
assert ack(1, 0) == 2
56+
assert ack(1, 1) == 3
57+
assert ack(1, 2) == 4
58+
assert ack(1, 3) == 5
59+
assert ack(1, 4) == 6
60+
assert ack(2, 0) == 3
61+
assert ack(2, 1) == 5
62+
assert ack(2, 2) == 7
63+
assert ack(2, 3) == 9
64+
assert ack(2, 4) == 11
65+
assert ack(3, 0) == 5
66+
assert ack(3, 1) == 13
67+
assert ack(3, 2) == 29
68+
assert ack(3, 3) == 61
69+
assert ack(3, 4) == 125
70+
assert ack(4, 0) == 13
71+
72+
except AssertionError:
73+
TestsPass = False
74+
print "All Tests Did Not Pass!"
75+
76+
if (TestsPass):
77+
print "All Tests Pass!"
78+

0 commit comments

Comments
 (0)