-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheuler18.py
More file actions
executable file
·30 lines (23 loc) · 831 Bytes
/
euler18.py
File metadata and controls
executable file
·30 lines (23 loc) · 831 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python
import time
# define a recursive function to create partial sums by row
def recSumAtRow(rowData, rowNum):
# iterate over the given row
for i in range(len(rowData[rowNum])):
# add the largest of the values below-left or below-right
rowData[rowNum][i] += max([rowData[rowNum+1][i],rowData[rowNum+1][i+1]])
# base case
if len(rowData[rowNum])==1:
return rowData[rowNum][0]
# recursive case
else:
return recSumAtRow(rowData, rowNum-1)
# read in the data
rows = []
with open('triangle') as f:
for line in f:
rows.append([int(i) for i in line.rstrip('\n').split(" ")])
start = time.time()
result = recSumAtRow(rows, len(rows)-2) # start at second to last row
elapsed = time.time() - start
print "%s found in %s seconds" % (result ,elapsed)