以下是我如何回答这个问题。我怎样才能更好地解决这个问题?
**
定义一个过程,stamps,它以正整数为输入,以便士为单位,并返回组成该值所需的5p、2p和1p邮票(p为便士)的数目。返回值应该是三个数字的元组(也就是说,您的返回语句后面应该是5p、2p和1p邮票的编号)。你的答案应该使用尽可能少的总邮票,首先使用尽可能多的5便士邮票,然后是2便士邮票,最后是1便士邮票,以构成总数。(对于USians来说,仅仅说使用“永久”邮票并完成它是不公平的!)
**
这里是我的解决方案
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下面是练习中的测试
print stamps(8)
#>>> (1, 1, 1) # one 5p stamp, one 2p stamp and one 1p stamp
print stamps(5)
#>>> (1, 0, 0) # one 5p stamp, no 2p stamps and no 1p stamps
print stamps(29)
#>>> (5, 2, 0) # five 5p stamps, two 2p stamps and no 1p stamps
print stamps(0)
#>>> (0, 0, 0) # no 5p stamps, no 2p stamps and no 1p stamps发布于 2018-08-29 15:16:13
我将使用模块操作和剩余操作:
def modulo_and_remainder(a, b):
return a//b, a %b
def stamps(a):
five, rem = modulo_and_remainder(a, 5)
two, one = modulo_and_remainder(rem, 2)
return five, two, one或者(甚至不知道这一点)您可以使用内置的divmod:
def stamps(a):
five, rem = divmod(a, 5)
two, one = divmod(rem, 2)
return five, two, one发布于 2018-08-29 15:47:17
为了使它更加通用,一个函数需要一个邮票类型的元组:
def stamps(postage_cost,stamps):
stamps_required = []
for stamp in stamps:
(num_stamps,remainder) = divmod(postage_cost,stamp)
stamps_required.append(num_stamps)
postage_cost = remainder
return tuple(stamps_required)
stamp_types = (5,2,1)
required = stamps(8,stamp_types)
print(required)发布于 2019-04-05 18:20:29
def stamps(x): return (x / 5, (x - x / 5 * 5) / 2, x - (x / 5 * 5 + (x - x / 5 * 5) / 2 * 2))
https://stackoverflow.com/questions/52080837
复制相似问题