0

I wrote a code which on given a sum and a list of coins will return a set of coins that add up to that sum

eg. input: sum = 7 coins = [2,3]

 output:
 [3,2,2]

but when it was returning none when I debugged the code I found that the result variable was computed correctly but when it appends c it turns into none

def coinSum(sum,coin):
    if sum == 0:
        return []
    if sum < 0:
        return None

    for c in coin:
        reminder = sum - c
        result = coinSum(reminder,coin)
        if result is not None:
            returnValue = result.append(c)
            return returnValue

    return None

After that, I wrote this code which gave the correct output

def coinSum(sum,coin):
    if sum == 0:
        return []
    if sum < 0:
        return None

    for c in coin:
        reminder = sum - c
        result = coinSum(reminder,coin)
        if result is not None:
            returnValue = result + [c]
            return returnValue

    return None

what is the difference here? when I check it with a simple list, the append function works properly

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119

1 Answers1

0

Your trying to assign append to a variable or something like that. Here is an example.

x = []
y = x.append(2)
print(y)

output

None

So in your case here is an example of using your first code.

def coinSum(sum,coin):
    if sum == 0:
        return []
    if sum < 0:
        return None

    for c in coin:
        reminder = sum - c
        result = coinSum(reminder,coin)
        if result is not None:
            result.append(c)
            return result

    return None
print(coinSum(9,[2,1]))

Notice I don't assign result.append(c) to a new variable.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44