Bottom Page

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
Quote
#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
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Return all Path value from function Palerm0_24 2 45 Mar-18-2019, 03:09 PM
Last Post: ichabod801
  os.path.relpath help Kickdak 1 60 Mar-15-2019, 01:28 PM
Last Post: Larz60+
  Cannot add dot executable to system path bobsmith76 2 104 Mar-05-2019, 03:17 PM
Last Post: bobsmith76
  Directory path gahhon 3 145 Mar-03-2019, 11:39 PM
Last Post: DeaD_EyE
  [python]FileNotFoundError...System cannot find the path specified creichle 1 236 Jan-30-2019, 12:49 AM
Last Post: Larz60+
  Case sensitive path asheru93 6 201 Jan-28-2019, 01:52 PM
Last Post: asheru93
  Printing out a triangle using nested for loops MrGoat 12 380 Jan-16-2019, 07:21 PM
Last Post: ichabod801
  Problem with reading a path gkiller007 30 876 Jan-05-2019, 10:09 PM
Last Post: snippsat
  os.path.isdir(<whatever>) returns always True Fabrizio 3 277 Dec-04-2018, 04:28 PM
Last Post: nilamo
  Directory path EOF Graham 8 337 Nov-28-2018, 10:13 PM
Last Post: Graham

Forum Jump:


Users browsing this thread: 1 Guest(s)