Search code examples
pythonarrayssumtarget

Sum of elements (can be repeated) of subarrays equal to a target value in Python


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

I have tried this code and getting the answer [[[[[], 2], 2], 2], 2] instead of [2, 2, 2, 2]. I am quite new to programming and stack exchange. Please help me out here. Thanks in advance


Solution

  • Use sequence unpacking.

    Instead of:

                return [remainderResult, num]
    

    Use:

                return [*remainderResult, num]
    

    Full code:

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

    Output:

    [2, 2, 2, 2]