File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ # -*- coding: utf-8 -*-
2+ """
3+ Created on Fri Apr 13 17:06:21 2018
4+
5+ @author: terry.mai
6+ """
7+ import datetime as dt
8+
9+ def row (n ):
10+ list = []
11+ if n == 1 :
12+ #base case
13+ return [1 ]
14+ else :
15+ for i in range (1 ,len (row (n - 1 ))):
16+ #rolling sum all the values with 2 windows from the previous row
17+ #but we cannot include two boudary numbers 1 in this list
18+ temp = row (n - 1 )[i ]+ row (n - 1 )[i - 1 ]
19+ list .append (temp )
20+ #append 1 for both front and rear of the list
21+ list .insert (0 ,1 )
22+ list .append (1 )
23+
24+ return list
25+
26+ def printit (n ):
27+ for j in range (1 ,n + 1 ):
28+ print (row (j ))
29+ return
30+
31+ #---------------------
32+
33+ #introduce a global dictionary
34+ #the function is basically the same as the previous one
35+ #except we add one more if function
36+ #to see if we can find pas[n] in dictionary
37+ #if so, we return the output
38+ #if not, we append it to dictionary for future use
39+ global dict
40+ dict = {1 :[1 ]}
41+ def pas (n ):
42+ if n in dict :
43+ return dict [n ]
44+ else :
45+ list = []
46+ if n == 1 :
47+ #base case
48+ return dict [1 ]
49+ else :
50+ for i in range (1 ,len (row (n - 1 ))):
51+ #rolling sum all the values with 2 windows from the previous row
52+ #but we cannot include two boudary numbers 1 in this list
53+ temp = pas (n - 1 )[i ]+ pas (n - 1 )[i - 1 ]
54+ list .append (temp )
55+ #append 1 for both front and rear of the list
56+ list .insert (0 ,1 )
57+ list .append (1 )
58+ dict [n ]= list
59+
60+ return dict [n ]
61+
62+ def printit2 (n ):
63+ for j in range (1 ,n + 1 ):
64+ print (pas (j ))
65+ return
66+
67+
68+ #-----------------
69+ #comparison between recursion with memory and without memory
70+ #use datetime now to capture the time and take the difference
71+ def compare (n ):
72+ t1 = dt .datetime .now ()
73+ printit (n )
74+ t2 = dt .datetime .now ()
75+
76+
77+ t3 = dt .datetime .now ()
78+ printit2 (n )
79+ t4 = dt .datetime .now ()
80+
81+ print ('without memory:' ,t2 - t1 ,'\n with memory' ,t4 - t3 )
82+ return
83+
84+ compare (12 )
You can’t perform that action at this time.
0 commit comments