首页 > 代码库 > Euler_problem_18 for python
Euler_problem_18 for python
如下所示 给出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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。