My apologies in advance. I'm aware that this question has been asked before with answers that have not produced the results I want/need. I am making an attempt to write a function that does the following in Python3:
I need a recursive function that returns all the number of ways (coin combinations) that produce a specified amount. This function can only contain two arguments, amount and coins. I've had a difficult time wrapping my mind around recursion, so explanations would also be greatly appreciated. Thanks.
Here's what I currently have:
COINS = dict(
USA=[100, 50, 25, 10, 5, 1],
AUSTRALIA=[200, 100, 50, 20, 10, 5],
UK=[500, 200, 100, 50, 20, 10, 5, 2, 1]
)
def change(amount, coins):
"""
>>> change(100, COINS['USA'])
293
"""
if amount < 0:
return 0
elif amount == 0:
return 1
else:
biggestcoin, *rest = coins[0], coins[1:]
return change(amount-biggestcoin, coins) + change(amount, rest)
print
to determine what variables hold at various points, to confirm that it's what you expect), and when you're asking about something that doesn't work, you should describe how it failed (e.g. include exception tracebacks). – Marseillaiseprint
s. As @KarlKnechtel noted, you have the right idea for the algorithm. There is one case that you are missing that might help you out here (I'm going to leave it slightly cryptic because I suspect this is homework):change(amount-biggestcoin, coins)
. Also, I'm not sure if you are open to other types of recursion, like recursive descent – Pareira