'How can I put text efficient in sub lists inside a list? (Python)

I wrote some code to calculate the maximum path sum of a triangle. This is the triangle:

    75
   95 64
  17 47 82
 18 35 87 10
20 04 82 47 65

So the maximum path sum of this triangle is: 75+95+82+87+82 = 418

This is my code to calculate it:

lst = [[72], 
    [95,64], 
    [17,47,82], 
    [18,35,87,10],
    [20,4,82,47,65]]
something = 1
i = 0
mid = 0
while something != 0:
    for x in lst:
        new = max(lst[i])
        print(new)
        i += 1
        mid += new
    something = 0
print(mid)

As you can see I put every item of the triangle down in lists and put the lists in a (head) list. This are not a lot numbers, but what if I have a bigger triangle? To do it manually is a lot of work. So my question is: How can I put the numbers from the triangle efficient in sub lists inside a head list?



Solution 1:[1]

If you have input starting with a line containing the number of rows in the triangle, followed by all the numbers on that many rows, read the first number to get the limit in a range(). Then use a list comprehension to create the list of sublists.

rows = int(input())
lst = [list(map(int, input().split())) for _ in range(rows)]

For instance, to read your sample triangle, the input would be:

5
    75
   95 64
  17 47 82
 18 35 87 10
20 04 82 47 65

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar