Skip to main content

Euler 0019

The Problem:

MovingHow throughmany aSundays trianglefell of number (every number chosen yields 2 more numbers to choose), what ison the highest sum path in the triangle?

Considerations and Approach:

We will populate a tree data structure with the data from the triangle, and then work from the bottom up to find the best path.

Starting at the bottomfirst of the treemonth takebetween theJan value1 1901 and Dec 31 2000?

Considerations:

There is for sure a number theory mathematical way of thehandling nodesthis... themself,but...

Approach:

What if we just imported a python calendar module and counted how many Sundays were between then when moving up the tree, take the best value from the left and right children and add it to the sum.

This results in the top node having the best sum.now?

The Code:

triangle_fileimport calendar

year = open("triangle",1901
"r")

class Node:
    def __init__(self, value):
        self.l_nodeend_year = None2000

self.r_nodesunday_first_days = None

        self.value = value
        self.l_sum = -1
        self.r_sum = -1
        self.best = -1

#not necessarily the prettiest way to construct a tree... but oh well.
#there is a lot by reference here.
top_triangle = int(triangle_file.readline())
triangle_tree = Node(top_triangle)
past_line = [triangle_tree]
for line in triangle_file:
    current_line = [Node(int(x)) for x in line.split()]0
for i in range(len(past_line))year, end_year + 1):
    past_line[i].l_nodethis_year = current_line[i]calendar.Calendar().yeardayscalendar(i,12)
    past_line[i].r_nodefor =year current_line[i+1]in past_linethis_year:
        =for current_linemonth #makein ayear:
            functionfor toweek populatein the sums
def pop_sums(node : Node):month:
                if node.l_node is None:
        node.l_sum = node.value
        node.r_sum = node.value
        node.best = node.value
    else:
        #make sure both below are populated
        if node.l_node.bestweek[6] == -1:
                    pop_sums(node.l_node)sunday_first_days if node.r_node.best =+= -1:
            pop_sums(node.r_node)
        
        node.l_sum = node.l_node.best + node.value
        node.r_sum = node.r_node.best + node.value
        node.best = node.l_sum if node.l_sum > node.r_sum else node.r_sum

pop_sums(triangle_tree)1

print(triangle_tree.best)sunday_first_days)