022.【Greedy Algorithm】

1. Greedy algorithm

Greedy algorithm is also called greedy algorithm. A greedy algorithm means that when solving a problem, one can always make the choice that is considered to be the best at this moment. That is to say, without considering the overall optimality, only a local optimal solution in a certain sense is made. It is similar to the dynamic programming algorithm in that most of the optimal solution problems can be split into sub-problems one by one. The difference between the greedy algorithm and the dynamic programming algorithm is that the dynamic programming algorithm is to obtain the optimal solution of the whole problem, and each result will affect the future results. However, the results of the greedy algorithm each time will not affect the future results, but only consider the immediate problems. The greedy algorithm is short-sighted in the problem-solving strategy, making choices only based on the information currently available, and once a choice is made, no matter what the future results are, the choice will not change. For example, to catch fish after draining the water is to catch fish after draining the water. This is a greedy behavior that ignores long-term interests and only cares about the immediate future. In a sense, greedy algorithm is a special case of dynamic programming algorithm.

2. Use a greedy algorithm

It is normal to find change in supermarkets. Usually they have change in various denominations. Coins have denominations of 10 cents, 50 cents, 1 yuan, 5 yuan, 10 yuan, 20 yuan, 50 yuan and 100 yuan. When it is necessary to find customer change, there are many combinations of change. In this problem, the solution with the least number of coins should be selected. Therefore, the problem to be solved in this section is to find the solution with the least number of coins when the user enters the amount of change that needs to be changed.

insert image description here
Analysis: Choose coins with larger face value as much as possible. For example, divide the total change amount of 80 by the face value of 100. The integer after taking the quotient is 0, which means that 100 is greater than 80. You cannot find coins with a face value of 100 yuan. analogy.

The specific code to realize the change problem is as follows:

def change():
  d = [0.01,0.02,0.05,0.1,0.2,0.5,1.0]                  	# 存储每种硬币的面值
  d_num = []                               					# 存储每种硬币的数量
  s = 0

  # 拥有的零钱总和
  temp = input('请输入每种零钱的数量:')
  d_num0 = temp.split(" ")                      			# 用空格将每种零钱数量分割
  for i in range(0, len(d_num0)):                    		# 遍历每个空格
      d_num.append(int(d_num0[i]))             				# 给存储硬币数量列表补充空格
      s += d[i] * d_num[i]                     				# 计算出收银员拥有多少钱
  
  sum = float(input("请输入需要找的零钱:"))
  if sum > s:
  # 当输入的总金额比收银员的总金额多时,无法进行找零
      print("数据有错")
      return 0

  s = s - sum                              					# 收银员的总金额减去输入的总金额
  # 要想用的钱币数量最少,那么需要利用所有面值大的钱币,因此从数组的面值大的元素开始遍历,贪心算法开始
  i = 6                                     				# 列表最大坐标
  while i >= 0:                                				# 循环找零
    if sum >= d[i]:                                         # 输入的总金额大于或等于每个零钱面值数,才进行找零
       # 用输入的总金额从列表的最后一个元素开始整除取商,计算的是找每种面值的个数
        n = int(sum / d[i])
        if n >= d_num[i]:                     				# 如果计算n大于或等于每个面值个数
          n = d_num[i]                     					# 更新n
        sum -= n * d[i]                        				# 贪心的关键步骤,令sum动态的改变
        print("找了%d个%.2f元硬币"%(n, d[i]))   				# 输出需要找每种面值的情况
    i -= 1                                  				# 改变i的值用来结束循环

change()                                    				# 直接调用函数

Guess you like

Origin blog.csdn.net/qq_42226855/article/details/131258993