Help needed, stuck on problem - given a list of numbers find the ones that add up to a target.

I am trying to solved the above stated problem while following a tutorial.

The code in the tutorial is in javascript and looks like -


const howsum = (targetSum , numbers) => {

if  (targetSum === 0) return [];
if  (targetSum < 0) return null;

for (let num of numbers){
	const remainder = targetSum - num;
	
	const remainderResult = howSum(remainder, numbers);
	
	if (remainderResult !== null){
		return [...remainderResult, num ];
	
		}
	}
};

I attempted to recreate the code in python -


def howSum(targetSum,numbers):

    print("\ntargetSum " , targetSum)
    
    if targetSum == 0: return []
    if targetSum < 0: return None

    for num in numbers:
        print("\ntargetSum " , targetSum)

        print("Number : " , num)

        remainder = targetSum - num

        print("remainder : ", remainder)

        result = howSum(remainder, numbers)

        print("result for target sum : ",targetSum," is - " ,  result)

        if result != None:

            return result.append(num)

        
    

    return False

But it is not working.

The result comes out as false from one of the operations and am not able to debug it. Would someone be able to help me figure it out?
I probably think it has something to do with how None is acting in the program.

The end goal is to memoize is but I need to write it recursively first.

For the function call - print(howSum(7,[2,3]))

I get the following result -

targetSum 7

targetSum 7
Number : 2
remainder : 5

targetSum 5

targetSum 5
Number : 2
remainder : 3

targetSum 3

targetSum 3
Number : 2
remainder : 1

targetSum 1

targetSum 1
Number : 2
remainder : -1

targetSum -1
result for target sum : 1 is - None

targetSum 1
Number : 3
remainder : -2

targetSum -2
result for target sum : 1 is - None
result for target sum : 3 is - False

I can't for the life of me find out how this False is coming.

Comments (1)