Optimization of decisions for change of decisions

I wrote here a Python solution that solves the following problem: how can I make a given amount of money nwith the least amount of coins taking into account the names d?

def min_coin_change(n, d):
    mini = float("inf")
    for den in d:
        diff = n - den
        if diff == 0:
            ans = 1
        elif diff < 0:
            ans = float("inf")
        else:
            ans = 1 + min_coin_change(n - den, d)
        mini = min(mini, ans)
    return mini

While my solution works, it takes a lot of time when it is ngreater than 50 or when the length is dgreater than 5. How can I speed up my code so that it works on significantly larger inputs? Am I missing a trick or something that will dramatically speed up my code?

+3
source share
4 answers

, , , , .

, den

def changecoin(d, denval)
  count = 0
  while d > denval:
    d -= denval
    count += 1
  return count, d

denval d .

newcount = 0
for denval in den:
    count, d = changecoin(d, denval)
    newcount += count

, , changecoin ​​ while,

count = 0
for denval in den
  count += d//denval
  d = d % denval

count , d. d , 0, d . for , d 0, ,

  if d < 1:
    break
+2
+2

,

memoization Python? ( 2 )

"memoization" , (, 10 ), .

Mwmoize , "" ,


class Memoize:
    def __init__(self, f):
        self.f = f
        self.memo = {}
    def __call__(self, *args):
        if not args in self.memo:
            self.memo[args] = self.f(*args)
        return self.memo[args]

@Memoize
def min_coin_change(n,d)......

min_coin_change(30,(25,10,5,1))
+1

. :

  • : ( , 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]

+1
source

All Articles