CODE:
def down(pos):
return [pos[0],pos[1]+1]
def right(pos):
return [pos[0]+1,pos[1]]
def gT(m,n,pos=[0,0],memo=dict()):
print(pos,"-->",memo)
goal = [m-1,n-1]
key=str(pos)
# keyr=str(pos.reverse())
if(key in memo):
return memo[key]
if pos == goal:
res = 1
elif pos[1] == goal[1]:
res = gT(m,n,right(pos),memo)
elif pos[0] == goal[0]:
res = gT(m,n,down(pos),memo)
else:
res = gT(m,n,down(pos),memo)+gT(m,n,right(pos),memo)
memo[key]=res
# memo[keyr]=res
return res
OUTPUT:
>>> gT(3,3)
[0, 0] --> {}
[0, 1] --> {}
[0, 2] --> {}
[1, 2] --> {}
[2, 2] --> {}
[1, 1] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1}
[1, 2] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1}
[2, 1] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1}
[2, 2] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1}
[1, 0] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1, '[2, 1]': 1, '[1, 1]': 2, '[0, 1]': 3}
[1, 1] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1, '[2, 1]': 1, '[1, 1]': 2, '[0, 1]': 3}
[2, 0] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1, '[2, 1]': 1, '[1, 1]': 2, '[0, 1]': 3}
[2, 1] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1, '[2, 1]': 1, '[1, 1]': 2, '[0, 1]': 3}
6
>>> gT(4,4)
[0, 0] --> {'[2, 2]': 1, '[1, 2]': 1, '[0, 2]': 1, '[2, 1]': 1, '[1, 1]': 2, '[0, 1]': 3, '[2, 0]': 1, '[1, 0]': 3, '[0, 0]': 6}
6
for some reason it keeps memo saved between function calls when it should be initializing a new one .. I don't understand why this is occurring.
The code itself works .. but only for the first function call after which it preserves memo and starts giving wrong answers
Edit: for people looking at this in the future https://stackoverflow.com/a/13518071/7162067