-2

I am fairly new to python, stumbled upon a dynamic programming course on youtube that I thought would help me better understand the concept @ here.

Now, I have been struggling to understand it... Would anyone have the time to explain the way this code works?

The function takes a target sum and an array of numbers as arguments. The function should return an array containing any combination of numbers that add up exactly to the target number.

def howSum(targetSum, numbers, memo = {}):

if targetSum in memo : return memo[targetSum]
if targetSum == 0 : return []
if targetSum < 0 : return None

for num in numbers:
    remainder = targetSum - num
    
    remainderResult = howSum(remainder, numbers, memo)
        
    if remainderResult != None:
        memo[targetSum] = [*remainderResult, num]
        return memo[targetSum]
    
memo[targetSum] = None
return None
    

The original code was written for JS, I translated it to Python but I am struggling with a couple of things: namely:

  • return statements at the end of the definition

  • and this line specificaly:

    memo[targetSum] = [*remainderResult, num]

Is there a concept I am missing?

2 Answers2

0

I tried to explain by comments:

def howSum(targetSum, numbers, memo = {}):

    # if the result is calculated 
    # already (in the past) then 
    # use it
    if targetSum in memo : return memo[targetSum]

    # return pre-defined values 
    # to out-of-bound parameters
    if targetSum == 0 : return []
    if targetSum < 0 : return None

    # otherwise make the calculation
    for num in numbers:
        remainder = targetSum - num
        
        remainderResult = howSum(remainder, numbers, memo)
            
        if remainderResult != None:
            # if there is a result (which is not 
            # None) then store it for later
            # (to memoize it)
            memo[targetSum] = [*remainderResult, num]
            return memo[targetSum]
    
    memo[targetSum] = None
    return None

For a more pythonic memoization see this answer.

mccandar
  • 580
  • 4
  • 12
0

It is better to mention in short the function your code supposed to evaluate to save others' time.

  1. return statements at the end of the definition:

note that if you arrive this line while executing the code, then you didn't find an answer, so return None, which means no answer is found.

  1. memo[targetSum] = [*remainderResult, num]

Your function tries to find a way to write targetSum as the sum of a subset of elements in numbers, and store these elements in memo[targetSum]. This is exactly what happens in this line of code.