[英]Path with maximum sum in a triangle
I made a program for finding the max sum among all possible paths in a triangle 我编写了一个程序,用于查找三角形中所有可能路径之间的最大和
EXAMPLE: 例:
1
2 1
1 2 3
Then the max value among all possible paths is 1+2+3=6 那么所有可能路径中的最大值为1 + 2 + 3 = 6
My code: 我的代码:
def maxSum(tri, n):
if n > 1:
tri[1][1] = tri[1][1]+tri[0][0]
tri[1][0] = tri[1][0]+tri[0][0]
for i in range(2, n):
tri[i][0] = tri[i][0] + tri[i-1][0]
tri[i][i] = tri[i][i] + tri[i-1][i-1]
for j in range(1, i):
if tri[i][j]+tri[i-1][j-1] >= tri[i][j]+tri[i-1][j]:
tri[i][j] = tri[i][j] + tri[i-1][j-1]
else:
tri[i][j] = tri[i][j]+tri[i-1][j]
print max(tri[n-1])
#my list containing the triangle
tri = [[1], [2,1], [1,2,3]]
maxSum(tri, 3)
But my code is printing the output as 5.Anyone please help me to correct my code ? 但是我的代码将输出打印为5.有人可以帮助我更正我的代码吗?
If I am not wrong ,here is your requirement 如果我没看错,这是您的要求
For a triangle of 3 , you will have 6 elements and you want to get max path (means select all possible 3 elements combinations and get the combination of 3 numbers where you will give maximum sum. This can be achieved with a simple code 对于3的三角形,您将有6个元素,并且想要获得最大路径(表示选择所有可能的3个元素组合,并获得3个数字的组合,以得到最大和。这可以通过简单的代码实现
Code 码
`# declaring list
tri=[[1], [2, 1], [1, 2, 3]]`
#getting all possible 3 elements combinations out of available 6 elements. The below two lines will give list of tuples
import itertools
temptri=list(itertools.product(*tri))
#Converting tuple to list
ftri=[]
for i in temptri:
ftri.append(list(i))
#getting max sum of the avilable 3 elements combinations
print sum(max(ftri, key=sum))
Example input/output 输入/输出示例
input
tri=[[1], [2, 5], [1, 2, 3]]
output
6
input
[[1], [2, 5], [1, 2, 3]]
output
9
input
[[1], [2, 5], [1, 2, 3],[1,2,3,7]]
output
16
You haven't specified what a valid path is and so just like Sandeep Lade, i too have made an assumption: To get the sum of maximum numbers in the triangle: 您尚未指定有效路径是什么,因此就像Sandeep Lade一样,我也做出了一个假设:要获得三角形中最大数量的总和:
def maximum(x):
return max(x)
triangle= [[1], [2, 1], [1, 2, 3],[2,3,4,5]]
#the above can be represented as:
# 1
# 2 1
# 1 2 3
# 2 3 4 5
max_numbers = list(map(maximum,triangle))
print(max_numbers,'====>',sum(max_numbers))
gives you the sum of maximum numbers in the triangle and its scalable for any size of the triangle 为您提供三角形中最大数量的总和,以及该三角形可扩展为任意大小
You can make code even more concise using lambda functions: 您可以使用lambda函数使代码更加简洁:
print(sum(list(map(lambda x:max(x),triangle))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.