. :
: ( , for while). , .
: , , . , , ( ). ( ) .
def min_coin_change2(n, d):
current_amount = 0
used_coins = []
for coin_value in sorted(d, reverse=True):
while n - current_amount >= coin_value:
current_amount += coin_value
used_coins.append(coin_value)
excuse = '' if current_amount == n else ', but that is not what you asked for'
return 'I can get to %d using %s%s' % (current_amount, used_coins, excuse)
Try:
print min_coin_change2(101, [50, 20, 10, 1])
Out[25]: 'I can get to 101 using [50, 50, 1]'
and again when it is not possible to get the desired amount
print min_coin_change2(101, [50, 20, 10])
Out[26]: 'I can get to 100 using [50, 50], but that is not what you asked for'
and again when the greedy algorithm finds a suboptimal solution
print min_coin_change2(180, [100, 90, 20])
Out[2]: 'I can get to 180 using [100, 20, 20, 20, 20]'
but the best solution would be [90, 90]
source
share