Udacity计算机科学入门:第7课练习2

时间:2018-08-29 15:09:55

标签: python computer-science

这是我如何回答以下问题。我该如何更好地解决这个问题?

**

  

定义一个过程,图章,将正值作为输入   便士的整数,并返回5p,2p和1p邮票的数量(p为   便士)以弥补该价值。返回值应为   三个数字的元组(即您的return语句应为   其次是5p,2p和1p   邮票)。您的答案应使用尽可能少的总印章   首先使用尽可能多的5p邮票,然后使用2便士邮票和   最后根据需要加盖1枚邮票。 (对美国人没有公平   只是说要使用“永久”印章就可以了!)

**

这是我的解决方案

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

3 个答案:

答案 0 :(得分:2)

我将使用模和余数运算:

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

答案 1 :(得分:0)

为使这一点更加通用,该函数采用一组图章类型:

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)

答案 2 :(得分:0)

def stamps(x): return (x / 5, (x - x / 5 * 5) / 2, x - (x / 5 * 5 + (x - x / 5 * 5) / 2 * 2))