1 回答
TA贡献1893条经验 获得超10个赞
如果可能,您希望尽量减少列表索引的使用,并迭代列表本身。这是一个有效的代码:
# Pre-process denomination list before function, sorting in decreasing order
denomination_list = [1,15,10]
denomination_list.sort(reverse = True)
# Ensure ones are available for change (or infinite loop may result)
if denomination_list[-1] != 1:
denomination_list.append(1)
def make_change(denomination_list, amount):
change = []
# Iterate through coins
for coin in denomination_list:
# Add current coin as long as not exceeding ampoiunt
while amount:
if coin <= amount:
change.append(coin)
amount -= coin
else:
break
return change
amount= 43
print(make_change(denomination_list, amount))
这将适用于 的非整数值,amount并将列出向下舍入金额的变化。
添加回答
举报