I wrote a function called change
which takes in an int
and a list of coins.
It recursively checks what the least amount of coins are needed to create that amount and returns this number. Now I am trying to modify this function to take the same input but instead return a list with the number of coins and a list of coins used.
def change(amount, coins):
if amount == 0:
return 0
if coins == []:
return float("inf")
if coins[0] > amount:
return change(amount, coins[1:])
use_it = 1+change(amount-coins[0], coins)
lose_it = change(amount, coins[1:])
return min(use_it, lose_it)
I began modifying this code but I'm not sure how to manipulate the return value given that it's a list:
def giveChange(amount, coins):
if amount == 0:
return [0, []]
if coins == []:
return [float("inf"), []]
if coins[0] > amount:
return giveChange(amount, coins[1:])
use_it = 1 + giveChange(amount-coins[0], coins)
lose_it = giveChange(amount, coins[1:])
listOfCoins =
return [min(use_it, lose_it), listOfCoins]
I have this so far but my use_it line is wrong because the function now returns a list. Could I simply do this:
use_it = 1 + giveChange(amount-coins[0], coins)[0]
I am not sure how to build up the list of coins so that I can return it with the amount of coins at the end.