This is already pretty short. Making it shorter doesn't seem a good objective, and risks hurting readability.
That being said, there are a few things you could do.
You could do this in one step:
min_coin = [sys.maxint] * 20
min_coin[0] = 0
Like this:
min_coin = [0] + [sys.maxint] * 19
While at it, why are there 20 elements? Your program will find the minimum number of coins up to 19, and I have a feeling that you actually want it for 20. In which case you would need:
min_coin = [0] + [sys.maxint] * 20
And then use range(21)
in the loop. However, you shouldn't hard code this number, give it a name, like target_amount
, and use that.
Speaking of names, many of the names in your code can be better:
min_coin
is a list, so plural min_coins
would be better
min_of_i
is actually an amount
One more optimization is possible by flipping the order of the nested loops.
In the current code you need an if
statement to skip the amounts that are too small for the coin.
If you make the loop over coins to be the outer loop,
then you can set a starting value for the inner value to make the if
statement unnecessary.
def get_min_coins(coins, target_amount):
n = len(coins)
min_coins = [0] + [sys.maxint] * target_amount
for i in range(1, n + 1):
for j in range(coins[i - 1], target_amount + 1):
min_coins[j] = min(min_coins[j - coins[i - 1]] + 1, min_coins[j])
return min_coins