Skip to content

Instantly share code, notes, and snippets.

@Khunpisit
Created April 23, 2020 14:15
Show Gist options
  • Save Khunpisit/c6e8a4acebbf364499e81f6ca36b01e5 to your computer and use it in GitHub Desktop.
Save Khunpisit/c6e8a4acebbf364499e81f6ca36b01e5 to your computer and use it in GitHub Desktop.
class CoinUtil:
def __init__(self, coins = [], amount = 0):
self._coins = coins
self._amonth = amount
def coins_return(self):
print('--- get money for :', self._amonth)
coins = self._coins
amount = self._amonth
result = {}
for coin in sorted(coins, key=int, reverse=True): # alway descending sorted before calculate
if(amount >= coin):
number_coin, amount = divmod(amount, coin) #to find coin and remaining amount
result['coin({})'.format(coin)] = number_coin #prepare result
return result
## Running example is below (use python 3)
# define number of coins parameter first e.g. coins=[1,2,5,10]
# and init amount e.g. amount=1024
# to calculate just run coins_return()
result = CoinUtil(coins=[1,2,5,10], amount=1024).coins_return()
print('## result = {}'.format(result))
@Khunpisit
Copy link
Author

example result:
--- get money for : 1024

result = {'coin(10)': 102, 'coin(2)': 2}

@Khunpisit
Copy link
Author

--- get money for : 97

result = {'coin(10)': 9, 'coin(5)': 1, 'coin(2)': 1}

--- get money for : 98

result = {'coin(10)': 9, 'coin(5)': 1, 'coin(2)': 1, 'coin(1)': 1}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment