Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 1074
()
| 32 | |
| 33 | |
| 34 | def solution(): |
| 35 | """ |
| 36 | Finds the maximum total in a triangle as described by the problem statement |
| 37 | above. |
| 38 | |
| 39 | >>> solution() |
| 40 | 1074 |
| 41 | """ |
| 42 | script_dir = os.path.dirname(os.path.realpath(__file__)) |
| 43 | triangle = os.path.join(script_dir, "triangle.txt") |
| 44 | |
| 45 | with open(triangle) as f: |
| 46 | triangle = f.readlines() |
| 47 | |
| 48 | a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle] |
| 49 | |
| 50 | for i in range(1, len(a)): |
| 51 | for j in range(len(a[i])): |
| 52 | number1 = a[i - 1][j] if j != len(a[i - 1]) else 0 |
| 53 | number2 = a[i - 1][j - 1] if j > 0 else 0 |
| 54 | a[i][j] += max(number1, number2) |
| 55 | return max(a[-1]) |
| 56 | |
| 57 | |
| 58 | if __name__ == "__main__": |