3 回答
TA贡献1785条经验 获得超8个赞
循环可用于遍历笔记列表,并且在循环内,如果发现有任何笔记被计数,则可以打印该笔记。
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)
TA贡献2019条经验 获得超9个赞
不要为每个面额保留一个变量,而是保留一个字典并根据所使用的面额更新 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}")
TA贡献1828条经验 获得超3个赞
Sreerams 的类似实现使用 while 循环而不是 for 循环:
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 代码优于我的代码,它更易于阅读,并且在规模上性能更高。
添加回答
举报