I can't seem to figure out what broke my code.
I wrote a code that takes a pyramid:
[[1],
[2,3],
[4,5,6],
[7,8,9,10]]
Starting from the head (pyramid[0][0]) calculates the maximum sum possible to achieve by moving to either the item below, or to the item below and to the right recursively
In this example the output should be 20.
This is the code without memoization, which works fine:
def max_trail(pyramid,row=0,col=0):
if row == (len(pyramid)-1):
return pyramid[row][col]
else:
return pyramid[row][col] + max(max_trail(pyramid ,row+1 ,col),
max_trail(pyramid ,row+1, col+1))
But when I try to apply memoization, something along the way breaks. What am I missing?
This is the broken code:
def max_trail_mem(pyramid,row=0,col=0,mem=None):
if mem==None:
mem={}
key = ((row),(col))
if row == (len(pyramid)-1):
if key not in mem:
value = pyramid[row][col]
mem[key]=value
return mem[key]
return mem[key]
else:
key = (row+1),(col)
if key not in mem:
mem[(row+1),(col)] = max_trail_mem(pyramid ,row+1 ,col,mem)
key = (row+1),(col+1)
if key not in mem:
mem[(row+1),(col+1)]=max_trail_mem(pyramid ,row+1, col+1,mem)
return max(mem[(row+1),(col)],mem[(row+1),(col+1)])
This has taken hours off my poor studential life. Any help will be greatly appreciated!
You forgot
pyramid[row][col] +
beforemax(...
at your last return. Adding it gives20
for your example (see last line of code):