下面是我如何回答下面的问题。我怎样才能更好地解决这个问题?在
**
Define a procedure, stamps, which takes as its input a positive integer in pence and returns the number of 5p, 2p and 1p stamps (p is pence) required to make up that value. The return value should be a tuple of three numbers(that is, your return statement should be followed by the number of 5p, the number of 2p, and the number of 1p stamps). Your answer should use as few total stamps as possible by first using as many 5p stamps as possible, then 2 pence stamps and finally 1p stamps as needed to make up the total. (No fair for USians to just say use a "Forever" stamp and be done with it!)
**
这是我的解决方案
def stamps(i):
# Your code here
five = 0
two = 0
one = 0
while i > 0:
if i == 0:
break
if i >= 5:
five = five + 1
i = i - 5
if i == 0:
break
if i < 5 or i == 2:
two = two + 1
i = i - 2
if i == 0:
break
if i < 2 or i == 1:
one = one + 1
i = i - 1
return five,two,one
这是练习中的测试
^{pr2}$
为了使其更通用,一个接受标记类型元组的函数:
我将使用模和余数运算:
或者(甚至不知道)您可以使用内置的divmod:
^{pr2}$def stamps(x): return (x / 5, (x - x / 5 * 5) / 2, x - (x / 5 * 5 + (x - x / 5 * 5) / 2 * 2))
相关问题 更多 >
编程相关推荐