如下所示 给出2个解法
def euler_problem_18_1():
"""this problem spend my half-day but noting to finished ,so bad
"""
rows = ‘‘‘
3
7 4
2 4 6
100 5 9 3
‘‘‘
rows = reversed([map(int, row.split())
for row in rows.strip().split(‘\n‘)])
# first deal with string
totals = None
for row in rows:
totals = [
value + (max(totals[i], totals[i + 1]) if totals else 0)
for i, value in enumerate(row)
]
print totals
# assert totals[0] == 1074
print totals
def euler_problem_18_2():
"""
using recursion
"""
rows = []
with open(‘a.txt‘) as f:
for line in f:
rows.append([int(i) for i in line.rstrip(‘\n‘).split(‘ ‘)])
result = rec_sum_row(rows, len(rows) - 2)
print result
def rec_sum_row(row_data, row_num):
# iterate over the given row
for i in range(len(row_num)):
# add the largest of values below-left or below-right
row_data[row_num][i] += max([row_data[row_num + 1][i], row_data[row_num + 1][i + 1]])
# base case
if len(row_data[row_num]) == 1:
return row_data[row_num][0]
else:
return rec_sum_row(row_data, row_num - 1)