Skip to content

Commit 11a15cc

Browse files
Add solution for Project Euler problem 67 (TheAlgorithms#5519)
* New solution for Euler problem 67 A faster and memory efficient solution based on the template of sol1.py. Modified the solution to be more memory efficient while reading and generating the array and during the solution finding. No conditions and straightforward logic. * added return type hint * Update project_euler/problem_067/sol2.py Preferring comprehensions over map Co-authored-by: Christian Clauss <[email protected]> * Update sol2.py Self explanatory variable names * Updated sol2 to problem 067 in directory * Update project_euler/problem_067/sol2.py Co-authored-by: Christian Clauss <[email protected]> * Update project_euler/problem_067/sol2.py Co-authored-by: Christian Clauss <[email protected]> * Fixed extra line Co-authored-by: Christian Clauss <[email protected]>
1 parent 477cc3f commit 11a15cc

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,7 @@
771771
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py)
772772
* Problem 067
773773
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py)
774+
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol2.py)
774775
* Problem 069
775776
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py)
776777
* Problem 070

project_euler/problem_067/sol2.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Statement:
3+
By starting at the top of the triangle below and moving to adjacent numbers on
4+
the row below, the maximum total from top to bottom is 23.
5+
3
6+
7 4
7+
2 4 6
8+
8 5 9 3
9+
That is, 3 + 7 + 4 + 9 = 23.
10+
Find the maximum total from top to bottom in triangle.txt (right click and
11+
'Save Link/Target As...'), a 15K text file containing a triangle with
12+
one-hundred rows.
13+
"""
14+
import os
15+
16+
17+
def solution() -> int:
18+
"""
19+
Finds the maximum total in a triangle as described by the problem statement
20+
above.
21+
>>> solution()
22+
7273
23+
"""
24+
script_dir = os.path.dirname(os.path.realpath(__file__))
25+
triangle_path = os.path.join(script_dir, "triangle.txt")
26+
27+
with open(triangle_path) as in_file:
28+
triangle = [[int(i) for i in line.split()] for line in in_file]
29+
30+
while len(triangle) != 1:
31+
last_row = triangle.pop()
32+
curr_row = triangle[-1]
33+
for j in range(len(last_row) - 1):
34+
curr_row[j] += max(last_row[j], last_row[j + 1])
35+
return triangle[0][0]
36+
37+
38+
if __name__ == "__main__":
39+
print(solution())

0 commit comments

Comments
 (0)