Python greedy algorithm solves cashier's change problem

scene description

        When checking out at the supermarket, assuming there are only coins of 1 cent, 5 cents, 1 cent, 3 cents, 5 cents, and 1 yuan, if you need to change, give the number of coins you need to change, so that the cashier will give the customer the least amount of coins , run the program as shown in the figure:

knowledge supplement

        The greedy algorithm means that in solving the current problem, always make the best current choice, that is, the local optimal solution! Using the greedy strategy must ensure that there is no aftereffect, that is, the process after a certain state will not affect the state before, and at the same time, the local optimal strategy can produce a global optimal solution.

The general solution steps of the greedy algorithm are:

        1. Establish a mathematical model to describe the problem;
        2. Divide the problem to be solved into several sub-problems;
        3. Solve each sub-problem to obtain the local optimal solution of the sub-problem;
        4. Combine the local optimal solutions of the sub-problems into the original a solution to the problem.

define function function

Initialize the number of coins the cashier has

        Get the amount of each type of change through input, define the total amount of change that the cashier has, prevent the change from being impossible, and determine the number of coins of each denomination.

"""
    通过输入获取总零钱
"""
def new_coin():
    print("=====收银员总零钱统计=====")
    coin = [0.01, 0.05, 0.1, 0.5, 1.0]
    coin_num = []
    sum = 0
    for index, i in enumerate(coin):
        num = int(input('收银员{}面值硬币有几个?'.format(i)))
        coin_num.append(num)
        sum += i * num
    print("收银员总零钱数:{0}".format(sum))
    return sum, coin, coin_num

write change

        Starting from the largest coin denomination, calculate how much money can be changed for this type of denomination. The amount of change for each type of denomination coin is a sub-problem, and at the same time, it is aggregated to achieve the goal of minimizing the total number of coins.

""" 
    计算找零 
"""
def change(sum, coin, coin_num):
    print('==========找零==========')
    s = float(input("请输入要找零金额:"))
    # 找零比收银员总零钱数大
    if s > sum:
        print("收银员零钱不够!")
    else:
        # 贪心算法要总硬币数最少,从最大面值开始找零
        i = len(coin) - 1
        while i >= 0:
            if s >= coin[i]:
                n = int(s / coin[i])
                if n > coin_num[i]:
                    n = coin_num[i]
                #贪心算法 动态改变找零总值
                s -= n * coin[i]
                print("用了{0}面值的硬币{1}个".format(coin[i], n))
            i -= 1
        print("找零结束!")

Complete code implementation


"""
    通过输入获取总零钱
"""
def new_coin():
    print("=====收银员总零钱统计=====")
    coin = [0.01, 0.05, 0.1, 0.5, 1.0]
    coin_num = []
    sum = 0
    for index, i in enumerate(coin):
        num = int(input('收银员{}面值硬币有几个?'.format(i)))
        coin_num.append(num)
        sum += i * num
    print("收银员总零钱数:{0}".format(sum))
    return sum, coin, coin_num


""" 计算找零 """
def change(sum, coin, coin_num):
    print('==========找零==========')
    s = float(input("请输入要找零金额:"))
    # 找零比收银员总零钱数大
    if s > sum:
        print("收银员零钱不够!")
    else:
        # 贪心算法要总硬币数最少,从最大面值开始找零
        i = len(coin) - 1
        while i >= 0:
            if s >= coin[i]:
                n = int(s / coin[i])
                if n > coin_num[i]:
                    n = coin_num[i]
                #贪心算法 动态改变找零总值
                s -= n * coin[i]
                print("用了{0}面值的硬币{1}个".format(coin[i], n))
            i -= 1
        print("找零结束!")


if __name__ == '__main__':
    print("============收银员找零================")
    sum, coin, coin_num = new_coin()
    change(sum, coin, coin_num)

PS: Due to personal reasons, it has been discontinued for a long time, and today I will slowly pick up the previous update.

Welcome to like, collect, and comment in the comment area, and reprint to indicate the source.

Guess you like

Origin blog.csdn.net/qq_52213943/article/details/127733687