From 11a15cc5842bb44a81bc8ee56af8f25d92a74287 Mon Sep 17 00:00:00 2001 From: Naveen Namani Date: Thu, 28 Oct 2021 22:57:14 +0530 Subject: [PATCH] Add solution for Project Euler problem 67 (#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 * 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 * Update project_euler/problem_067/sol2.py Co-authored-by: Christian Clauss * Fixed extra line Co-authored-by: Christian Clauss --- DIRECTORY.md | 1 + project_euler/problem_067/sol2.py | 39 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 project_euler/problem_067/sol2.py diff --git a/DIRECTORY.md b/DIRECTORY.md index 2acfff69d..a8986f195 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -771,6 +771,7 @@ * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py) + * [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol2.py) * Problem 069 * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py) * Problem 070 diff --git a/project_euler/problem_067/sol2.py b/project_euler/problem_067/sol2.py new file mode 100644 index 000000000..2e88a5717 --- /dev/null +++ b/project_euler/problem_067/sol2.py @@ -0,0 +1,39 @@ +""" +Problem Statement: +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. +""" +import os + + +def solution() -> int: + """ + Finds the maximum total in a triangle as described by the problem statement + above. + >>> solution() + 7273 + """ + script_dir = os.path.dirname(os.path.realpath(__file__)) + triangle_path = os.path.join(script_dir, "triangle.txt") + + with open(triangle_path) as in_file: + triangle = [[int(i) for i in line.split()] for line in in_file] + + while len(triangle) != 1: + last_row = triangle.pop() + curr_row = triangle[-1] + for j in range(len(last_row) - 1): + curr_row[j] += max(last_row[j], last_row[j + 1]) + return triangle[0][0] + + +if __name__ == "__main__": + print(solution())