如何把钱(便士)兑换成单独的硬币?

2024-10-01 22:30:01 发布

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

我的任务是 '编写一个函数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)

我是新编程,所以当我运行这个代码时,它只是输入 “1 0 0 0 0 0 0 0”当我键入292而不是它应该输出的值时。在


Tags: 函数用户数量硬币elifmoneyonepoundfivep
2条回答

使用真实面额最酷的事情是贪婪的解决方案总是能找到最优的解决方案。。。这不再适用于奇怪的面额。。。如果你把这些问题分解成最容易的部分

def get_one_change(amt_due):
    # find how many of the largest denomination that you can use is
    # ie for 60 = 1x50p is the count and number of largest
    # for 4 = 4x1p ; 21 = 2x10p ; etc
    return pence,count # ie 50,1 would be 1 50p coin

一旦你有了这个,你只需要反复调用它并调整你的结果,直到你没有变化到期

^{pr2}$

现在您只需使用用户输入调用您的get_change方法

因为你是个新手,你应该开始把你要遵循的过程写在纸上,然后找出你可以使用哪些工具来自动化这个过程。在

Important

Read the full answer in order!
Don't fall for the temptation of reading the code right away.

The solutions I provide are hidden, but you can read them hovering your mouse over them or clicking on them (if you're using StackExchange mobile app, touch the "spoiler" link in each block).

算法

我要做的是:

  1. 假设我有一个装有硬币的箱子,每个箱子都标有硬币的面额。
    这些箱子是从大面额到低面额的,我总是在移动到下一个箱子之前,从最高面额的箱子里挑选出我需要的硬币。在
  2. 在一张纸上写下我需要计算每种面额硬币数量的价值。在
  3. 从第一个箱子开始(持有最高面额的那个)。在
  4. 从那个箱子里挑选我需要的硬币,这样我就不会“超过”写在纸上的金额(注意这个数字可以是零)。
    这可以用整数除法来实现;例如,如果您的值为700,并且bin的面额为200,则计算整数除法700 ÷ 200 = 3 (plus a remainder of 100)
  5. 计算一下我选的硬币总数。在
  6. 删除步骤5中计算的值,并将余数写为“新”值。
    因为您已经在步骤4中计算了整数除法,所以可以计算余数。你也可以考虑在大多数编程语言中都有一个“模”运算符,它可以立即给你一个整数除法的余数。使用上面的例子,700 mod 200 = 100,它读作“700模200是100”,或者“整数除法700÷200的余数是100”。在
  7. 继续下一个硬币箱。在
  8. 从第4步开始重复,直到我使用所有的箱子或值为零。在

示例

假设我从一个值292开始,我有以下面额的箱子(已经从最高面额到最低面额排序):

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

那么,让我们看看如果我应用上面的算法会发生什么:

^{pr2}$

在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)
This solution uses both integer division and remainder to perform the calculations.

让我们用正确的方法来做:用一个循环

Let's face it: the above code is verbose. There must be a better way... and there is! Use a loop. Consider the algorithm: you repeat the steps jumping from one bin to the next and getting the number of coins you need and the remainder. This can be written in a loop. So, let's add a list to our toolbox:

denominations = [200, 100, 50, 20, 10, 5, 2, 1]
And let's store the results of each step in a second list:
coins = [] # We'll use the '.append()' method to add elements to this list
So, starting in the first "bin":
n, money = money // denominations[0] , money % denominations[0]
    coins.append(n)
Let's put this in a loop:
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)
And that's it!

另一个改进是:只获得面额一次,然后使用两次

Notice that the code above still has an issue: you read denominations twice. It would be nice if the denomination value could be read only once. Of course, there is a way:

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)
As a friend of mine says: "Fast, precise and concise; not slow, difuse and confusing"

TL;DR

  • 在python3.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

奖励:使用字典

What if I want to print both the denominations and the number of coins of each denomination I used? You can traverse both lists with a loop, but you can also keep it simple by using a dictionary:

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提供了很大的灵活性。请随意尝试不同的方法来获得你所需要的。。。选择比较容易的。在

希望这有帮助。在

相关问题 更多 >

    热门问题