Change generator
Apr. 28th, 2008 05:35 pmFor no terribly compelling reason, here is a small change giver:
coins = [ 100, 50, 20, 10, 5, 2, 1 ]
def change(value, bin=0):
div, mod = divmod(value, coins[bin])
if not mod:
return [ ( div, coins[bin] ) ]
else:
return change(mod, bin+1) + \
[ ( div, coins[bin] ) ]
When supplied with a small sum of money, it breaks the number down and returns a list composed of tuples which indicate how many coins of each denomination are required:
>>> change(138)
[(1, 1), (1, 2), (1, 5), (1, 10),
(1, 20), (0, 50), (1, 100)]
>>>
For my next lame science project, I plan to build a software model of a vending machine. Or possibly a machine that automatically lays traffic cones every 5 metres. I haven't quite decided...