Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273
()
| 16 | |
| 17 | |
| 18 | def solution(): |
| 19 | """ |
| 20 | Finds the maximum total in a triangle as described by the problem statement |
| 21 | above. |
| 22 | |
| 23 | >>> solution() |
| 24 | 7273 |
| 25 | """ |
| 26 | script_dir = os.path.dirname(os.path.realpath(__file__)) |
| 27 | triangle = os.path.join(script_dir, "triangle.txt") |
| 28 | |
| 29 | with open(triangle) as f: |
| 30 | triangle = f.readlines() |
| 31 | |
| 32 | a = [] |
| 33 | for line in triangle: |
| 34 | numbers_from_line = [] |
| 35 | for number in line.strip().split(" "): |
| 36 | numbers_from_line.append(int(number)) |
| 37 | a.append(numbers_from_line) |
| 38 | |
| 39 | for i in range(1, len(a)): |
| 40 | for j in range(len(a[i])): |
| 41 | number1 = a[i - 1][j] if j != len(a[i - 1]) else 0 |
| 42 | number2 = a[i - 1][j - 1] if j > 0 else 0 |
| 43 | a[i][j] += max(number1, number2) |
| 44 | return max(a[-1]) |
| 45 | |
| 46 | |
| 47 | if __name__ == "__main__": |