Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #This is where you would paste an array of the numbers
- pyramid = [...]
- #Runs a "sum factorial" function (like a regular factorial but adding instead of multiplying) as part of finding the position in the array
- #The basic idea is that the position of the first number in a row is equal to the sum factorial of that row number minus 1
- def sum_factorial(x):
- total = 0
- for i in range(x, 0, -1):
- total += i
- return total
- #Finds positin in the array of numbers corresponding to the inputs row and iteration within that row
- #The position is found by running the sum factorial function on the row number, adding the iteration within the row
- #and subtracting 1 as arrays start counting from 0
- def position(row, iteration):
- return sum_factorial(row - 1) + iteration - 1
- #Iterates for the number of rows in the triangle minus 1, starting from the bottom to the top
- for row in range(99, 0, -1):
- #The amount of iterations in a row is equal to the row number, but you must add 1 because range() does not include the second value
- for iteration in range(1, row + 1):
- #Checks to see if the number to the bottom left of the current number it is checking (it checks all numbers in each row) is greater than the number to the right
- if pyramid[position(row, iteration) + row] > pyramid[position(row, iteration) + row + 1]:
- #If it is greater, the current number is now equal to itself + the number to the bottom left of it
- pyramid[position(row, iteration)] += pyramid[position(row, iteration) + row]
- else:
- #Otherwise, it is now equal to itself + the number to the right of it
- pyramid[position(row, iteration)] += pyramid[position(row, iteration) + row + 1]
- #The top number should now be equal to the sum of the route with largest route
- print(pyramid[0])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement