我的任务是
“编写一个功能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)

我是编程新手,因此在运行此代码时,它只是输入
当我键入292而不是它应输出的内容时,为“1 0 0 0 0 0 0 0 0”。

最佳答案

由于您不熟悉编码,因此应该开始编写在纸上执行的过程,然后找出可用于自动化该过程的工具。



算法

我要做的是:

  • 假设我有一些装有硬币的垃圾箱,每个垃圾箱都标有硬币面额。
    纸箱从最大面额到最小面额进行分类,在移到下一个纸箱之前,我总是从最大面额的筐中挑选尽可能多的硬币。
  • 用纸写我需要计算每个面额硬币数量的值。
  • 从第一个垃圾箱(拥有最高面额的垃圾箱)开始。
  • 从那种垃圾箱中挑选我需要的硬币,这样我就不会“超调”写在纸上的数量(请注意,这个数字可以为零)。
    这可以用整数除法来完成。例如,如果您的值是700,而bin的面额是200,则可以计算整数除法700 ÷ 200 = 3 (plus a remainder of 100)
  • 计算我选择的硬币总数。
  • 删除在第5步中计算出的值,并将其余值写为"new"值。
    由于您已经在步骤4中计算了整数除法,因此可以计算余数。您还可以考虑在大多数编程语言中都有一个“模数”运算符,它将立即为您提供整数除法的余数。使用上面的示例,700 mod 200 = 100读取“700模200为100”,或“整数除法700÷200的余数为100”。
  • 前进到下一个硬币箱。
  • 从第4步开始重复,直到我使用了所有垃圾箱或该值为零为止。

  • 例子

    假设我从292的值开始,并且我有以下面额的容器(已经从最高面额到最低面额排序):

    |  200 |  100 |   50 |   20 |   10 |    5 |    2 |    1 |
    +------+------+------+------+------+------+------+------+
    |   I  |   II |  III |   IV |    V |   VI |  VII | VIII |
    

    因此,让我们看看如果应用上述算法会发生什么:

    Write the value:   292
    Start with the first bin (denomination: 200)
    Pick 1 coin from the bin
        The total amount picked from the bin is 200
        The remainder is 92
    Strike the previous value
        The new value is 92
    Move to the next bin (denomination: 100)
    Pick 0 coins from the bin
        The total amount picked from the bin is 0
        The remainder is 92
    Strike the previous value
        The new value is 92
    Move to the next bin (denomination: 50)
    Pick 1 coin from the bin
        The total amount picked from the bin is 50
        The remainder is 42
    Move to the next bin (denomination: 20)
        Pick 2 coins from the bin
        The total amount picked from the bin is 20
        The remainder is 2
    Move to the next bin (denomination: 10)
        Pick 0 coins from the bin
        The total amount picked from the bin is 0
        The remainder is 2
    Move to the next bin (denomination: 10)
        Pick 0 coin from the bin
        The total amount picked from the bin is 0
        The remainder is 2
    Move to the next bin (denomination: 5)
        Pick 0 coin from the bin
        The total amount picked from the bin is 0
        The remainder is 2
    Move to the next bin (denomination: 2)
        Pick 1 coin from the bin
        The total amount picked from the bin is 2
        The remainder is 0
    Done
    

    用Python实现

    Python是一种非常清晰的语言,可简化此类任务。因此,让我们尝试将我们的算法转换为Python。

    工具箱

    假设您使用的是Python 3.x,则需要了解一些运算符:
  • 整数除法运算符(//):如果仅用一个斜杠进行除法,则将得到“实数除法”(例如3 / 2 == 1.5),但是如果使用双斜杠,则将得到“整数除法” (例如3 // 2 = 1)
  • 模运算符(%):如上所述,该运算符返回除法的余数(例如7 % 4 == 3)

  • 这些运算符一起使用,将为您提供每一步所需的信息:
    292 // 200 == 2
    292 % 200 == 92
    
    92 // 100 == 0
    92 % 100 == 92
    
    ...
    

    Python的一个有用特性是您可以执行“多重分配”:您可以在一个步骤中将多个值分配给多个变量:
    # Initialize the value:
    value = 292
    # Initialize the denomination:
    denomination = 200
    # Calculate the amount of coins needed for the specified denomination
    # and get the remainder (overwriting the value), in one single step:
    coins, value = value // denomination, value % denomination
    #              ^^^^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^
    #              |                      The remainder
    #              The number of coins
    #              (using integer division)
    

    有了这些知识,我们可以编写解决方案:

    更正您的代码

    请记住:在阅读以下解决方案之前,请阅读以上所有内容。

    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')) # Example: 292
        # Calculate the number of coins needed and the remainder
        # The remainder will "overwrite" the value previously held in the "money" variable
        a, money = money // twopound, money % twopound # a = 1, money = 92
        b, money = money // onepound, money % onepound # b = 0, money = 92
        c, money = money // fiftyp,   money % fiftyp   # c = 1, money = 42
        d, money = money // twentyp,  money % twentyp  # d = 2, money = 2
        e, money = money // tenp,     money % tenp     # e = 0, money = 2
        f, money = money // fivep,    money % fivep    # f = 0, money = 2
        g, money = money // twop,     money % twop     # g = 1, money = 0
        e, money = money // onep,     money % onep     # e = 0, money = 0
        print(a,b,c,d,e,f,g,h)
    

    该解决方案使用整数除法和余数来执行计算。

    让我们以正确的方式来做:循环

    让我们面对现实:上面的代码是冗长的。一定有更好的方法……而且有!使用循环。

    考虑一下算法:重复执行从一个容器到下一个容器的步骤,并获取所需的硬币数量和剩余的硬币数量。这可以写成一个循环。

    因此,让我们在工具箱中添加一个list:
    denominations = [200, 100, 50, 20, 10, 5, 2, 1]

    然后将每个步骤的结果存储在第二个列表中:
    coins = [] # We'll use the '.append()' method to add elements to this list

    因此,从第一个“bin”开始:
    n, money = money // denominations[0] , money % denominations[0]
        coins.append(n)

    让我们将其循环:
    def select_coins_v2():
            denominations = [200, 100, 50, 20, 10, 5, 2, 1]
            coins = []
            money = int(input('Enter how much money you have in pence'))
            for i in range(len(denominations)):
                n, money = money // denominations[i], money % denominations[i]
                coins.append(n)
            print(coins)

    就是这样!

    另一个改进:只获得一次面额两次使用

    请注意,上面的代码仍然有一个问题:您阅读了denominations两次。如果面额值只能读取一次,那就太好了。

    当然,有一种方法:
    def select_coins_v3():
            denominations = [200, 100, 50, 20, 10, 5, 2, 1]
            coins = []
            money = int(input('Enter how much money you have in pence'))
            for d in denominations:  # 'd' will hold the value of the denomination
                n, money = money // d, money % d
                coins.append(n)
            print(coins)

    正如我的一个 friend 所说:“快速,准确,简洁;不要慢,漫不经心和困惑”

    TL; DR
  • 在Python 3.x中,“整数除法”运算符为//,余数(模)运算符为%
  • 您可以在一行代码中执行多个分配: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


  • 奖励:使用字典

    如果我想同时打印面额和使用的每种面额的硬币数量怎么办?您可以使用循环遍历两个列表,但是也可以使用字典来简化它:
    def select_coins_v4():
            denominations = [200, 100, 50, 20, 10, 5, 2, 1]
            coins = []
            money = int(input('Enter how much money you have in pence'))
            for d in denominations:  # 'd' will hold the value of the denomination
                n, money = money // d, money % d
                coins.append(n)
            number_of_coins = dict(zip(denominations, coins))
            print(number_of_coins)

    Python提供了很大的灵活性。随意尝试各种获取所需内容的方法...,然后选择更简单的方法。

    希望这可以帮助。

    关于python - 如何将钱(便士)变成其单个硬币?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52706139/

    10-12 16:57