我必须编写一个函数来计算并返回最大收益 我们可以实现从一个知识库,这是存储在一个列表列表每一级。你知道吗
要测试此功能,主要有:
if __name__ == "__main__":
l0 = [[7], [3,8], [8,1,0], [2,7,4,4], [4,5,2,6,5]]
l1 = [[11], [7,32], [14,14,14], [0,1,2,3], [5,99,1,2,7],
[0,25,9,45, 54,1], [99,88,77,66,55,44,33]]
>>>30
>>>270
我试着从下到上,有没有别的解决办法?你知道吗
你可以想象列表就像一棵树
[7]
[3,8]
[8,1,0]
[2,7,4,4]
等等。。。 我想到达有最大效益的步行,选择的权重由列表中的数字给出,我必须使我的路径最大化
我写了这个解决方案
def maxpath(listN):
liv = len(listN) -1
return calcl(listN,liv)
def calcl(listN,liv):
if liv == 0:
return listN[0]
listN[liv-1] = [(listN[liv-1][i]+listN[liv][i+1],listN[liv-1][i]+listN[liv][i]) \
[ listN[liv][i] > listN[liv][i+1] ] for i in range(0,liv)]
return calcl(listN,liv-1)
print(maxpath(l0))
print(maxpath(l1))
#output
[30]
[270]
通过树的可能路由数是
2**rows
。到给定节点的可能路由数由二项式展开式给出。你可以很简单地从树的头开始增加可能的路由,每个节点只有两个可能的下一个移动,它们在列表中的索引要么与当前位置相同,要么更多。你知道吗解决这个问题的一个简单方法是为给定数量的行生成所有可能的路径。
create_paths()
这样做,返回树中所有可能的路由。函数max_cost()
使用此函数根据成本树评估所有路由,返回最昂贵路由的值。我把它留给你,让你得到实际的路线(不是很难……)相关问题 更多 >
编程相关推荐