def pay_change(paid, cost):
# set up the change and an empty dictionary for result
change = paid - cost
result = {}
# get the result dictionary values for each bill
n_twenty = change // 20
result['$20'] = n_twenty
rest = change % 20
n_ten = rest // 10
result['$10'] = n_ten
rest = rest % 10
n_five = rest // 5
result['$5'] = n_five
rest = rest % 5
n_two = rest // 2
result['$2'] = n_two
rest = rest % 2
n_one = rest // 1
result['$1'] = n_one
# print(result) if you want to check the result dictionary
# present the result, do not show if value is 0
for k, v in result.items():
if v != 0:
print('Need', v, 'bills of', k)
因为我也是初学者,所以我将把它作为python的练习。请参见以下代码:
逻辑是假设变化超过20,然后通过使用
//
缓慢计算,然后使用%
计算其余的。不管怎样,我们最终会得到一本字典,它给出了每一美元钞票需要多少钞票。在然后,对于那些值为0的美元钞票,我们不需要显示它们,所以我编写了一个for循环来检查字典中的值。在
好了,现在我简化了代码,以避免重复代码片段,我很满意:
^{pr2}$相关问题 更多 >
编程相关推荐