我写这篇文章来计算改变所需的最小票据和硬币数量。这可以使用循环完成吗?
def user_change(balance):
twen = int(balance/20)
balance=balance%20
ten = int(balance/10)
balance=balance%10
five = int(balance/5)
balance = balance%5
ones = int(balance/1)
balance = balance%1
quart = int( balance/0.25)
balance = balance%0.25
dime = int(balance/0.10)
balance = balance%0.10
nickel = int(balance/0.05)
balance = balance%0.05
pennies = int(balance/0.05)
print twen
print ten
print five
print ones
print quart
print dime
print nickel
print pennies
user_change(34.36)
答案 0 :(得分:7)
这是一个美好的时光(好吧,总是是个好时光)让自己更轻松,首先考虑数据结构。您有一个货币(密钥)列表,对于每个密钥,您希望为(值)找到一个唯一的金额。 k:v配对意味着dict
,所以填补一个代替只打印值;你可以随时打印......
def make_change(bal):
currency = [20,10,5,1,.25,.1,.05,.01]
change = {}
for unit in currency:
change[unit] = int(bal // unit)
bal %= unit
return change
(无论何时使用%=
运营商,都应该感觉很酷)
答案 1 :(得分:1)
是的,它可以。看看
的重复x=int(balance/N)
balance=balance%N
将你的N放在一个列表中,然后循环将它们收集到另一个列表中
如需高级信用,请map
。
答案 2 :(得分:1)
当然,我们只需列出一些值并映射它。
def user_change(balance):
values = [20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01]
for value in values:
print(int(balance/value))
balance = balance % value
答案 3 :(得分:1)
编辑:每个roippi更新答案@建议:
from collections import OrderedDict
_currency_values = [
('twenties',20),
('tens',10),
('fives',5),
('ones',1),
('quarters',0.25),
('dimes',0.10),
('nickels',0.05),
('pennies',0.01),
]
currency_values = OrderedDict(_currency_values)
def user_change(balance):
user_change_results = []
for currency in currency_values.keys():
#print balance
if balance == 0:
break
currency_amount = currency_values[currency]
currency_change_amount = balance//currency_amount
user_change_results.append((currency,currency_change_amount))
balance-=(currency_change_amount*currency_amount)
return user_change_results
if __name__ == '__main__':
print user_change(34.36)
原始回复:
这是我的方法。与roippi @类似,但每种货币金额都有描述符:
currency_values = {
'twenties' : 20,
'tens' : 10,
'fives' : 5,
'ones' : 1,
'quarters' : 0.25,
'dimes' : 0.10,
'nickels' : 0.05,
'pennies' : 0.01,
}
currency_order = ['twenties','tens','fives','ones','quarters','dimes','nickels','pennies']
def user_change(balance):
user_change_results = []
for currency in currency_order:
#print balance
if balance == 0:
break
currency_amount = currency_values[currency]
currency_change_amount = balance//currency_amount
user_change_results.append((currency,currency_change_amount))
balance-=(currency_change_amount*currency_amount)
return user_change_results
if __name__ == '__main__':
print user_change(34.36)