[英]How to change this code to not printing unused coin=0?
我正在嘗試構建一個功能,在人們輸入金額后,它將顯示他們需要的最少硬幣或紙幣數量。 但這有什么方法可以讓我改變它,這樣它就不會打印未使用硬幣的名稱和數量? (作為初學者)感謝您的幫助! (可以用for循環來處理嗎?)
不是為每個演示保留一個變量,而是保留一個 dict 並根據所使用的面額更新 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%500
if amount>=100:
denominations['100'] = amount//100
amount= amount%100
if 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%10
if 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//1
for key, val in denominations.items():
print(f"{key}: {val}")
Enter an amount: 523
Total number of notes/coins=
500: 1
20: 1
2: 1
1: 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}")
使用 while 循環而不是 for 循環的 Sreerams 的類似實現:
amount = int(input("Enter an amount: "))
counter = amount
pos = 0
notes = [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 += 1
print("Total number of notes/coins=")
for r in output:
for k,v in r.items():
if v > 0:
print("{}: {}".format(k, v))
請注意,Sreerams 代碼優於我的代碼,它更易於閱讀並且在規模上的性能更高。
循環可用於遍歷筆記列表,並在循環內部,如果發現任何筆記被計數,則可以打印。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.