Currency convertibility (greedy) - Python realization

# Greedy algorithm to solve the problem of currency exchange
There are n # currency coin denominations of v1, v2, v3 ... vn, where v1 = 1, the total value of money with the use of Exchange, how to make the number of coins required minimum, i.e., x1, x2, x3 ... xn minimum sum
# Input: nominal value of various currencies v1, v2, v3 ... vn; To redeem the total value of money
# Output: get the least amount of currency exchange
 
1  # modify Denomination 
2 V = [50,10,5,2,1 ]
 . 3  # amount of money to be modified exchange Money 
. 4 Money = 253
 . 5  # of each currency is the initial number 0 
. 6 X = [0] * len (V )
 7  # total initial quantity of money 0 
. 8 COUNT = 0
1  # starts from the maximum denomination exchange, exchange insufficient remaining large denomination, it is then convertible small denomination, until completion of exchange 
2  for I in Range (0, len (V)):
 . 3      X [I] = Money // V [I]          # rounding sign // 
. 4      Money Money% V = [I]          # modulo symbol% 
. 5  for I in Range (0, len (V)):
 . 6      COUNT = X [I] + COUNT
. 1  Print ( ' the amount of money obtained by the greedy algorithm exchange: ' , COUNT)
 2  Print ( '   which face value ' , V)
 . 3  Print ( '   the amount of money are ' , X)

operation result:

An amount of money to be redeemed is: 253
 2 monetary amount obtained by the greedy algorithm exchange: 7
 . 3    wherein denominations of [50, 10, 5, 2, 1 ]
 4    number of currencies are [5, 0, 0, 1 , 1]

Greedy method to ensure that every step is optimal, but does not guarantee the global optimum. In other words, the use of greedy law finally obtained very good results, but not optimal.

 

 

 

Guess you like

Origin www.cnblogs.com/aiyou-3344520/p/11696073.html