File tree 2 files changed +79
-0
lines changed
2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ By starting at the top of the triangle below and moving to adjacent numbers on
3
+ the row below, the maximum total from top to bottom is 23.
4
+
5
+ 3
6
+ 7 4
7
+ 2 4 6
8
+ 8 5 9 3
9
+
10
+ That is, 3 + 7 + 4 + 9 = 23.
11
+
12
+ Find the maximum total from top to bottom of the triangle below:
13
+
14
+ 75
15
+ 95 64
16
+ 17 47 82
17
+ 18 35 87 10
18
+ 20 04 82 47 65
19
+ 19 01 23 75 03 34
20
+ 88 02 77 73 07 63 67
21
+ 99 65 04 28 06 16 70 92
22
+ 41 41 26 56 83 40 80 70 33
23
+ 41 48 72 33 47 32 37 16 94 29
24
+ 53 71 44 65 25 43 91 52 97 51 14
25
+ 70 11 33 28 77 73 17 78 39 68 17 57
26
+ 91 71 52 38 17 14 91 43 58 50 27 29 48
27
+ 63 66 04 68 89 53 67 30 73 16 69 87 40 31
28
+ 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
29
+ """
30
+ import os
31
+
32
+
33
+ def solution ():
34
+ """
35
+ Finds the maximum total in a triangle as described by the problem statement
36
+ above.
37
+
38
+ >>> solution()
39
+ 1074
40
+ """
41
+ script_dir = os .path .dirname (os .path .realpath (__file__ ))
42
+ triangle = os .path .join (script_dir , 'triangle.txt' )
43
+
44
+ with open (triangle , 'r' ) as f :
45
+ triangle = f .readlines ()
46
+
47
+ a = [[int (y ) for y in x .rstrip ('\r \n ' ).split (' ' )] for x in triangle ]
48
+
49
+ for i in range (1 , len (a )):
50
+ for j in range (len (a [i ])):
51
+ if j != len (a [i - 1 ]):
52
+ number1 = a [i - 1 ][j ]
53
+ else :
54
+ number1 = 0
55
+ if j > 0 :
56
+ number2 = a [i - 1 ][j - 1 ]
57
+ else :
58
+ number2 = 0
59
+ a [i ][j ] += max (number1 , number2 )
60
+ return max (a [- 1 ])
61
+
62
+
63
+ if __name__ == "__main__" :
64
+ print (solution ())
Original file line number Diff line number Diff line change
1
+ 75
2
+ 95 64
3
+ 17 47 82
4
+ 18 35 87 10
5
+ 20 04 82 47 65
6
+ 19 01 23 75 03 34
7
+ 88 02 77 73 07 63 67
8
+ 99 65 04 28 06 16 70 92
9
+ 41 41 26 56 83 40 80 70 33
10
+ 41 48 72 33 47 32 37 16 94 29
11
+ 53 71 44 65 25 43 91 52 97 51 14
12
+ 70 11 33 28 77 73 17 78 39 68 17 57
13
+ 91 71 52 38 17 14 91 43 58 50 27 29 48
14
+ 63 66 04 68 89 53 67 30 73 16 69 87 40 31
15
+ 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
You can’t perform that action at this time.
0 commit comments