如何更改此代码以不打印未使用的硬币=0?

我正在尝试构建一个功能,当人们输入金额后,它会显示他们需要的最小硬币或纸币数量。但这有什么方法可以让我改变它,这样它就不会打印未使用的硬币的名称和数量吗?(作为初学者)感谢您的帮助!(可以用for循环来处理吗?)



一只名叫tom的猫
浏览 87回答 3
3回答

慕的地10843

循环可用于遍历笔记列表,并且在循环内,如果发现有任何笔记被计数,则可以打印该笔记。notes=[1000,500,100,50,20,10,5,2,1]amount=int(input('Enter an amount: '))print('Total number of notes/coins=')for notesAmount in notes:    if amount>=notesAmount:       notesCount=amount//notesAmount       amount%=notesAmount       if notesCount>0:          print(notesAmount, ":", notesCount)

慕少森

不要为每个面额保留一个变量,而是保留一个字典并根据所使用的面额更新 key: val 。查看代码amount=int(input('Enter an amount: '))denominations = dict()print('Total number of notes/coins=')if amount>=1000:    denominations['1000'] = amount//1000    amount%=1000    if amount>=500:    denominations['500'] = amount//500    amount= amount%500if amount>=100:    denominations['100'] = amount//100    amount= amount%100if amount>=50:    denominations['50'] = amount//50    amount= amount%50    if amount>=20:    denominations['20'] = amount//20    amount= amount%20    if amount>=10:    denominations['10'] = amount//10    amount= amount%10if amount>=5:    denominations['5'] = amount//5    amount= amount%5   if amount>=2:    denominations['2'] = amount//2    amount= amount%2    if amount>=1:    denominations['1'] = amount//1for key, val in denominations.items():    print(f"{key}: {val}")Enter an amount: 523Total number of notes/coins=500: 120: 12: 11: 1如果使用如下所示的简单逻辑,则可以减少代码行数,def find_denominations():        amount=int(input('Enter an amount: '))        denominations = dict()        DENOMINATIONS = [1000, 500, 100, 50, 20, 10, 5, 2, 1]           print('Total number of notes/coins=')        for d in DENOMINATIONS:        if amount >= d:            denominations[d] = amount // d            amount %= d    for key, val in denominations.items():        print(f"{key}: {val}") 

倚天杖

Sreerams 的类似实现使用 while 循环而不是 for 循环:amount = int(input("Enter an amount: "))counter = amountpos = 0notes = [1000, 500, 100, 50, 20, 10, 5, 2, 1]output = []while counter > 0:    remainder = counter % notes[pos]    sub = counter - remainder    num = int(sub / notes[pos])    counter -= sub    output.append({notes[pos]: num})    pos += 1print("Total number of notes/coins=")for r in output:    for k,v in r.items():        if v > 0:            print("{}: {}".format(k, v))请注意,Sreerams 代码优于我的代码,它更易于阅读,并且在规模上性能更高。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python