Skip to content
Advertisement

Why does this solution work in Javascript but not in Python? (Dynamic programming)

I’m following this tutorial about dynamic programming and I’m struggling to implement memoization in the following problem:

*Write a function called canSum(targetSum, numbers) that returns True only if the numbers in the array can sum to the target sum. All the numbers in the array are positive integers and you can use them more than once for the solution.

Example:

canSum(7, [2, 4]) -> False because you can’t form 7 by adding 2 and 4. *

My brute force solution was the following one:

JavaScript

Works well, but it’d be faster if we memoized the solutions of the remainders (this is explained at minute 1:28:03 in the video). I did the following with Python, which is exactly what the instructor is doing, but it only returns True and I can’t figure out why…

JavaScript

Advertisement

Answer

Thanks to the article shared by @Jared Smith I was able to figure it out.

The problem is caused by how python handles default arguments. From the article:

In Python, when passing a mutable value as a default argument in a function, the default argument is mutated anytime that value is mutated.

My memo dictionary was being mutated every call. So I simply changed memo=None and added a check to see if it was the first call of the function:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement