草庐IT

python - 如何将钱(以便士计)转换为单独的硬币?

coder 2023-08-27 原文

我的任务是
'编写一个函数 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 而不是它应该输出的内容时。

最佳答案

由于您是编码新手,您应该开始在纸上编写您要遵循的过程,然后找出可以使用哪些工具来自动化此过程。

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).



算法

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

  • 例子

    假设我从 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; 博士
  • 在 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/

    有关python - 如何将钱(以便士计)转换为单独的硬币?的更多相关文章

    1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

      我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

    2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

      总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

    3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

      我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

    4. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

      关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

    5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

      给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

    6. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

      我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

    7. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

      我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

    8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

      我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

    9. ruby - 如何指定 Rack 处理程序 - 2

      Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

    10. ruby - 将数组的内容转换为 int - 2

      我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

    随机推荐