I have to write a function that computes and returns the maximum benefit
we can achieve from a base of knowledge which is stored per levels in a list of lists.
To test this function the main is:
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
I tried to start from the bottom to the top, is there any other solution?
You can imagine the list like a tree
[7]
[3,8]
[8,1,0]
[2,7,4,4]
and so on…
I want to reach the walk that have the max benefit, the weight of the choices is given by the number in the list, I have to maximize my path
I have wrote this solution
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]
The number of possible routes through a tree is
2**rows. The number of possible routes to a given node is given by the binomial expansion. You can grow the possible routes from the head of the tree quite simply, at each node there are only two possible next moves, their indexes in the list are either the same as the current position or one more.A simple way to solve the problem is to generate all possible paths for a given number of rows.
create_paths()does this, returning all possible routes through the tree. Functionmax_cost()uses this to evaluate all routes against the cost tree, returning the value of the most expensive route. I leave it to you to get the actual route out (not very hard..) 🙂