#python
#python
Вопрос:
Я пытаюсь создать функцию, которая после ввода людьми суммы денег покажет минимальное количество монет или банкнот, которые им нужны. Но у меня есть какие-либо способы изменить его так, чтобы он не печатал имя и номер неиспользуемой монеты? (как новичок) Спасибо за помощь! (Можно ли будет справиться с этим с помощью цикла for ?)
Ответ №1:
Вместо того, чтобы сохранять переменную для каждого подтверждения, сохраняйте 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}")
Комментарии:
1. деноминации — это dict, и код повторяет dict, выбирает ключ и значение из dict и распечатывает их.
Ответ №2:
Аналогичная реализация для 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 превосходит мой, его легче читать и он будет более производительным в масштабе.
Ответ №3:
Цикл можно использовать для перебора списка заметок и внутри цикла, если обнаруживается, что какая-либо заметка подсчитана, ее можно распечатать.
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)