Python数组硬币排序

2024-06-01 11:39:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python中的数组执行硬币排序python程序,想知道最有效的方法是什么。。。 这就是我目前所拥有的,任何帮助都将不胜感激


values = [50,20,10,5,1]    #values of coins
amount = int(input("how much change"))
remaining = amount
i = 0
fifty = 0
twenty = 0
ten = 0
five = 0
one = 0
print(remaining)
print("##########")
# while unsorted values remain:
# while len(values) >0:
while remaining >0:
  print(remaining)
  if remaining >= values[0]:
    remaining = remaining - values[0]
    fifty += 1
    # remaining = remaining - 50  
  
  if remaining >= 20 and remaining <50:
    remaining = remaining - values[1]
    twenty += 1
      # remaining = remaining - 20 
  if remaining >= 10 and remaining <20:
    remaining = remaining - values[2]
    ten += 1
  #  remaining = remaining - 10 
  if remaining >= 5 and remaining <10:
    remaining = remaining - values[3]
    five += 1 
  #  remaining = remaining - 5  
  if remaining >= 1 and remaining <5:
    remaining = remaining - values[4]
    one += 1 
      # remaining = remaining - 1 
  if remaining ==0:
    print("end loop")
    break
    
print("#########")
print("number of 50 coins = " + str(fifty))
print("number of 20 coins = " + str(twenty))
print("number of 10 coins = " + str(ten))
print("number of 5 coins = " + str(five))
print("number of 1p coins = " + str(one))
   
print("end")
  #i=i+1


我想有一个有效的方法来做到这一点,我教计算机科学。 谢谢


Tags: andofnumberifonevaluesprintfive
1条回答
网友
1楼 · 发布于 2024-06-01 11:39:24

您可以使用//%为每个硬币值建立计数列表,整数除法给出使用的硬币数,然后余数(remaining % v)是新的剩余计数。然后循环打印。(如果要显示零,请删除if count条件。)

values = [50,20,10,5,1]    #values of coins
amount = int(input("how much change "))
remaining = amount

counts = []
for v in values:
    counts.append(remaining // v)
    remaining %= v

for count, value in zip(counts, values):
    if count:
        print(f"number of {value} coins = {count}")
print("end")

或者,如果您不想存储输出,而只想打印输出,则无需构建列表:

values = [50,20,10,5,1]    #values of coins
amount = int(input("how much change "))
remaining = amount

for value in values:
    print(f"number of {value} coins = {remaining // value}")
    remaining %= value
print("end")

相关问题 更多 >