w3resource

Python: Compute the maximum value of the sum of the passing integers

Python Basic - 1: Exercise-61 with Solution

Python: Compute the maximum value of the sum of the passing integers

Arrange integers (0 to 99) as narrow hilltop, as illustrated in Figure 1. Reading such data representing huge, when starting from the top and proceeding according to the next rule to the bottom. Write a Python program that compute the maximum value of the sum of the passing integers according to the following rules.

At each step, you can go to the lower left diagonal or the lower right diagonal. For example, in the example of FIG. 1, as shown in FIG. 2, when 8,4,9,8,6,8,9,4,8 is selected and passed, the sum is 64 (8 + 4 + 9) + 8 + 6 + 8 + 9 + 4 + 8 = 64)

Input:
A series of integers separated by commas are given in diamonds. No spaces are included in each line. The input example corresponds to Figure 1. The number of lines of data is less than 100 lines.

Sample Solution:

Python Code:

import sys
print("Input the numbers (ctrl+d to exit):")
x = [list(map(int, l.split(","))) for l in sys.stdin]
dp = x[0]
 
for i in range(1, (len(x)+1)//2):
    _dp = [0]*(i+1)
    for j in range(i):
        _dp[j] = max(_dp[j], dp[j]+x[i][j])
        _dp[j+1] = max(_dp[j+1], dp[j]+x[i][j+1])
    dp = _dp
 
for i in range((len(x)+1)//2, len(x)):
    _dp = [0]*(len(dp)-1)
    for j in range(len(_dp)):
        _dp[j] = max(dp[j], dp[j+1]) + x[i][j]
    dp = _dp
print("Maximum value of the sum of integers passing according to the rule on one line.") 
print(dp[0])

Sample Output:

Input the numbers (ctrl+d to exit):
8
4, 9
9, 2, 1
3, 8, 5, 5
5, 6, 3, 7, 6
3, 8, 5, 5
9, 2, 1
4, 9
8
Maximum value of the sum of integers passing according to the rule on one line.
64

Flowchart:

Flowchart: Python - Cut out words of 3 to 6 characters length from a given sentence not more than 1024 characters

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to cut out words of 3 to 6 characters length from a given sentence not more than 1024 characters.
Next: Write a Python program to find the number of combinations that satisfy p + q + r + s = n where n is a given number <= 4000 and p, q, r, s in the range of 0 to 1000.

What is the difficulty level of this exercise?



Inviting useful, relevant, well-written and unique guest posts