计算机科学导论:第7课练习2

2024-06-17 18:47:02 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我如何回答下面的问题。我怎样才能更好地解决这个问题?在

**

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}$

Tags: andofthetonumberreturnifas
3条回答

为了使其更通用,一个接受标记类型元组的函数:

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)

我将使用模和余数运算:

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:

^{pr2}$

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

相关问题 更多 >