File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ from __future__ import division
2
+ # Learn Python together
3
+ """ Write a function that evaluetes the Ackermann funtion"""
4
+
5
+ # Solution 1 with limited input numbers
6
+ def ackermann (m , n ):
7
+ if m == 0 :
8
+ return n + 1
9
+ elif m > 0 and n == 0 :
10
+ return ackermann (m - 1 , 1 )
11
+ elif m > 0 and n > 0 :
12
+ return ackermann (m - 1 , ackermann (m , n - 1 ))
13
+ else :
14
+ return 0
15
+
16
+ print (ackermann (3 ,4 ))
17
+ # Output -> 125
18
+ print (ackermann (3 ,7 ))
19
+ # Output -> RecursionError: maximum recursion depth exceeded in comparison
20
+
21
+ # Solution 2 using memoization
22
+
23
+ cache = {} # empty dictionary for storing results
24
+
25
+ def ackermann_memo (m , n ):
26
+ if m == 0 :
27
+ return n + 1
28
+
29
+ if n == 0 :
30
+ # return recursively function with (m-1,1)
31
+ return ackermann_memo (m - 1 , 1 )
32
+ # If the result of this function call has been previously calculated
33
+ if (m , n ) in cache :
34
+ # return the stored result from the dictionary
35
+ return cache [m , n ]
36
+ else :
37
+ # otherwise return current recusive function result in the dictionary
38
+ cache [m , n ] = ackermann_memo (m - 1 , ackermann_memo (m , n - 1 ))
39
+ return cache [m , n ]
40
+
41
+ # check
42
+ print (ackermann_memo (3 , 7 ))
43
+ # output-> 1021
44
+ print (ackermann_memo (3 , 8 ))
45
+ # output-> 2045
46
+ print (ackermann_memo (4 , 8 ))
47
+ # output-> RecursionError: maximum recursion depth exceeded in comparison
48
+ # Do you know why ?
You can’t perform that action at this time.
0 commit comments