贪心算法找零问题

找零问题:假设商店老板需要找零n元钱,钱币的面额有:100元、50元、20元、5元、1元,如何找零使得所需钱币的数量最少?复制代码

# greedy algorithm

money = [100,50,20,5,1]

def change_money(x):
    change = [0,0,0,0,0]
    for i,m in enumerate(money):
        change[i] = x // money[i]
        x = x % money[i]
    if x > 0:
        print("还剩%s" % x)
    return change

print(change_money(356.2))

上述算法解法不够精确,下面算法更加精确:
import math
import decimal

money = [100, 50, 20, 5, 1]


def change_money(x):
change = [0, 0, 0, 0, 0]
x = decimal.Decimal(str(x))
print("x精准值为{}".format(x))
# math_x00 = int(x)
math_x01 = math.trunc(x)
for i, m in enumerate(money):
change[i] = math_x01 // money[i]
print("chang[i]是{}".format(change[i]))
math_x01 = math_x01 % money[i]
print("math_x01是{}".format(math_x01))

result = sum([i * j for i, j in zip(change, money)])
print("result是{}".format(result))
math_x02 = x - result
# if math_x02 > 0 or math_x02 == 0:
print("还剩{}".format(math_x02))
return change


print(change_money(6249.2))


 

 

posted @ 2020-12-12 00:21  ABDM  阅读(229)  评论(2编辑  收藏  举报