1 Star 0 Fork 0

阿坚/projecteuler

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
p067.py 1.85 KB
一键复制 编辑 原始数据 按行查看 历史
阿坚 提交于 2022-05-22 10:42 . little
"""
Problem 67: https://projecteuler.net/problem=67
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right click and
'Save Link/Target As...'), a 15K text file containing a triangle with
one-hundred rows.
"""
# _*_ conding:UTF-8 _*_
'''
@author = Kuperain
@email = kuperain@aliyun.com
@IDE = VSCODE Python3.8.3
@creat_time = 2022/5/22
'''
def inputTriangle(filename: str = 'p067_triangle.txt') -> list:
import re
triangle = []
with open(filename, 'r') as tf:
for line in tf:
row = line.strip().lstrip('0')
if not row: # blank line
continue
row = re.compile(r'\s+[0]*').sub(',', row) # replace '___000'
row = eval('[' + row + ']')
if triangle and len(row) - len(triangle[-1]) != 1:
raise ValueError(
f'{line} must one more data than the last row.')
else:
triangle.append(row)
return triangle
def maxTotal(triangle: list = inputTriangle()) -> int:
'''
>>> print(maxTotal([[3],[7,4],[2,4,6],[8,5,9,3]]))
23
'''
high = len(triangle)
if high == 0:
raise ValueError('triangle is empty.')
for i in range(0, high):
if len(triangle[i]) != i+1:
raise ValueError('triangle is illegal.')
if high == 1:
return triangle[0][0]
import copy
res = copy.deepcopy(triangle)
for row in range(high-2, -1, -1):
for col in range(len(res[row])):
res[row][col] += max(res[row+1][col], res[row+1][col+1])
return res[0][0]
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=False)
print(maxTotal())
# 7273
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/kuperain/projecteuler.git
git@gitee.com:kuperain/projecteuler.git
kuperain
projecteuler
projecteuler
master

搜索帮助