我的任务是 '编写一个函数selectCoins,要求用户输入金额 (便士)然后输出每种面额的硬币数量(从2英镑以下) 到1p)应该用来精确地弥补这个数额(使用尽可能少的) 硬币数量)。例如,如果输入为292,则函数应报告: 1×2,0×1,1×50p,2×20p,0×10p,0×5p,1×2p,0×1p(提示:使用整数) 除法和余数)
def selectCoins():
twopound = 200
onepound = 100
fiftyp = 50
twentyp = 20
tenp = 10
fivep = 5
twop = 2
onep = 1
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
money = int(input('Enter how much money you have in pence'))
while True:
if money >= twopound:
money = money - twopound
a = a + 1
elif money >= onepound:
money = money - onepound
b = b + 1
elif money >= fiftyp:
money = money - fiftyp
c = c + 1
elif money >= twentyp:
money = money - twentyp
d = d + 1
elif money >= tenp:
money = money - tenp
e = e + 1
elif money >= fivep:
money = money - fivep
f = f + 1
elif money >= twop:
money = money - twop
g = g + 1
elif money >= onep:
money = money - onep
h = h + 1
else:
money = 0
break
print(a,b,c,d,e,f,g,h)
我是新编程,所以当我运行这个代码时,它只是输入 “1 0 0 0 0 0 0 0”当我键入292而不是它应该输出的值时。在
使用真实面额最酷的事情是贪婪的解决方案总是能找到最优的解决方案。。。这不再适用于奇怪的面额。。。如果你把这些问题分解成最容易的部分
一旦你有了这个,你只需要反复调用它并调整你的结果,直到你没有变化到期
^{pr2}$现在您只需使用用户输入调用您的
get_change
方法因为你是个新手,你应该开始把你要遵循的过程写在纸上,然后找出你可以使用哪些工具来自动化这个过程。在
算法
我要做的是:
这些箱子是从大面额到低面额的,我总是在移动到下一个箱子之前,从最高面额的箱子里挑选出我需要的硬币。在
这可以用整数除法来实现;例如,如果您的值为700,并且bin的面额为200,则计算整数除法
700 ÷ 200 = 3 (plus a remainder of 100)
因为您已经在步骤4中计算了整数除法,所以可以计算余数。你也可以考虑在大多数编程语言中都有一个“模”运算符,它可以立即给你一个整数除法的余数。使用上面的例子,
700 mod 200 = 100
,它读作“700模200是100”,或者“整数除法700÷200的余数是100”。在示例
假设我从一个值
292
开始,我有以下面额的箱子(已经从最高面额到最低面额排序):那么,让我们看看如果我应用上面的算法会发生什么:
^{pr2}$在Python中实现这一点
Python是一种非常清晰的语言,它使这类任务变得简单。让我们试着把我们的算法翻译成Python。在
工具箱
假设您使用的是Python 3.x,那么您需要了解一些运算符:
//
):如果你只用一个斜杠除法,你会得到“实数除法”(例如3 / 2 == 1.5
),但是如果你用双斜杠,你会得到“整型除法(例如3 // 2 = 1
)%
):如上所述,此运算符返回除法的余数(例如7 % 4 == 3
)结合使用,这些运算符将为您提供每个步骤所需的信息:
Python的一个有用特性是可以执行“多重赋值”:可以在一个步骤中将多个值赋给多个变量:
有了这些知识,我们可以写出解决方案:
正在更正代码
记住:在给出下面的解决方案之前,请阅读以上所有内容。在
让我们用正确的方法来做:用一个循环
另一个改进是:只获得面额一次,然后使用两次
TL;DR
//
,余数(模)运算符是%
。在a, b = 1, 2
denominations = [200, 100, 50, 20, 10, 5, 2, 1]
n, money = money // denominations[0], money % denominations[0]
for d in denominations: n, money = money // d, money % d
奖励:使用字典
Python提供了很大的灵活性。请随意尝试不同的方法来获得你所需要的。。。选择比较容易的。在
希望这有帮助。在
相关问题 更多 >
编程相关推荐