Python Forum
Thread Rating:
  • 3 Vote(s) - 2.67 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Triangle: max path sum
#1
In my task I have to find the maximum path sum in a triangle of numbers - .txt file (maximum total from top to bottom).
For example in a triangle:
4
34
126 maxpathsum is 10

This is my program:
def maxSum(triangle, l, n): 
	for i in range(l-1, -1, -1): 
		for j in range(i+1): 

			if (triangle[i+1][j] > triangle[i+1][j+1]): 
				triangle[i][j] += triangle[i+1][j] 
			else: 
				triangle[i][j] += triangle[i+1][j+1] 

	return triangle[0][0]
with open("triangle.txt") as fp:
    total = 0
    for count, line in enumerate(fp):
        triangle = [int(num) for num in line.split()]
        
        tri1 = open('triangle.txt', 'r')

        tri2 = tri1.read()
        
        
        x= len(tri2.splitlines())
        y=x-1
        
        #print(triangle)
       
        print(maxSum(triangle, y, y)) 
I don't know how to fix this error:

Error:
Traceback (most recent call last): File "C:\Users\Mateo\Desktop\course-0\Task1.py", line 27, in <module> print(maxSum(triangle, y, y)) File "C:\Users\Mateo\Desktop\course-0\Task1.py", line 6, in maxSum if (triangle[i+1][j] > triangle[i+1][j+1]): IndexError: list index out of range
Reply
#2
The inherent issue is with maxSum(). To fix it, I recommend structuring the variable triangle differently. Right now, the code is opening the file twice to get different metadata about the data. It looks like triangle would be a list of individual numbers as it currently is.

As I understand the max sum problem, you need to find the greatest value on each line of the triangle and sum those values. Now, Python has a built-in function called max() that can help so you don't have to do the indexing. To make that happen, pass in a list of lists that represents the triangle:

Quote:5
2 3
1 2 1

becomes
triangle = [[5], [2,3], [1,2,1]]

The code is fairly close to what is needed to make that possible. It only requires a little refactoring and a more complex list comprehension:

triangle = [
    [
        int(num) for num in line.split()
    ] for line in fp.read().splitlines()
]
Then, in maxSum() you can iterate over triangle list to get the max values of each one. Then, add them all together and you're done.

If you are required to do the indexing or are not permitted to use max(), the indexing should be done differently. With the list structure above, you can simply iterate over each item. To ensure that the indices don't exceed the length of the lists, you will have to check the index of the current item against the length:

for each in tri:
    if len(each) == 1:
        break

    for num in each:
        if each.index(name) + 1 < len(each):
            # compare current index value to next index value
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Sad triangle numbers Woody_MC_2022 5 1,144 Sep-24-2022, 08:14 PM
Last Post: deanhystad
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,149 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  Fill a value in triangle shape in Matrix lynx 0 1,848 Dec-07-2019, 06:32 AM
Last Post: lynx
  Hollow triangle-drawing characters param error. phob0s 4 2,568 Jul-31-2019, 08:18 AM
Last Post: phob0s
  Printing out a triangle using nested for loops MrGoat 12 6,448 Jan-16-2019, 07:21 PM
Last Post: ichabod801
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,669 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908
  Area of a triangle OmarSinno 8 5,648 Sep-25-2017, 08:10 PM
Last Post: OmarSinno

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020