0

I am learning dynamic programming from freecodecamp youtube. I am a python programmer and the tutorial is following Javascript. When I translated the code from JS to python, I am finding that I get different output(wrong).

This is the code from that tutorial video - Javascript:

This is the link for the video https://youtu.be/oBt53YbR9Kk?t=5290

const canSum = (targetSum, numbers, memo={}) => {
  if (targetSum in memo) return memo[targetSum];
  if (targetSum ===0) return true;
  if (targetSum < 0) return false;

  for (let num of numbers){
    const remainder = targetSum - num;
    if (canSum(remainder, numbers, memo) === true){
      memo[targetSum] = true;
      return true;
    }
  }
  memo[targetSum] = false;
  return false;
}

console.log(canSum(7,[2,3]))
console.log(canSum(7,[5,3,4,7]))
console.log(canSum(7,[2,4]))
console.log(canSum(8,[2,3,5]))
console.log(canSum(30,[7,14]))

The output is

true 
true
false
true
false

The code I made for the same in python is :

def canSum(targetSum, numbers, memo={}):
    if targetSum in memo: return memo[targetSum]
    if targetSum == 0: return True
    if targetSum <0: return False
    for num in numbers:
        remainder = targetSum - num
        if canSum(remainder,numbers,memo) == True:
            memo[targetSum] = True
            return True
    memo[targetSum]=False
    return False


print(canSum(7,[2,3]))
print(canSum(7,[5,3,4,7]))
print(canSum(7,[2,4]))
print(canSum(8,[2,3,5]))
print(canSum(30,[7,14]))

The output is

True
True
True
True
True

As you see the output for the different language is different, why is it so?, or have I made any mistake? Can anyone help please

  • Your use of the `{}` as the default argument is causing state to be transferred from one call of the function to another. Don't use default argument for `memo` just pass a fresh dictionary to each invocation of the function. – rdas Apr 12 '21 at 05:11
  • @rdas Then why code of JavaScript works? – magnificence Apr 12 '21 at 06:59
  • I'm guessing it's because javascript doesn't treat mutable default arguments in the same way that python does. – rdas Apr 12 '21 at 07:04

0 Answers0