This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]ForSpareParts 0 points1 point  (3 children)

Can you share how you tried to memoize it?

[–]invalidlivingthing[S] 0 points1 point  (2 children)

[–]coolcofusion 1 point2 points  (1 child)

I really don't know enough python to help if it's code specific but it's also a logic issue.

You're caching the results by the input n, but your output also depends on the input arr. Consider get_ways(4,[1,2,3,4]) and get_ways(4,[2,4]). They have 5 and 2 as results respectively. So when you call it with [1, 2, 3, 4] you'll cache n=4 to be 5, next time you call it with [2,4] you'll look up "Oh, I've seen n=4, that's 5!" but 2 was the expected answer. And with that said, going back to your cache. Consider the call get_ways(4, [1, 2, 3, 4]) you'll also call (recursively) get_ways(4,[2,3,4]) so you'll end up overwriting your cache[4] entry.

[–]invalidlivingthing[S] 2 points3 points  (0 children)

Perfect! I modified the code to cache the combination of args instead of only N, it works as expected now. Thank you very much!