首页 文章

Python功能:从购买金额中查找更改

提问于
浏览
-2

我正在寻找最有效的方法来计算购买金额的变化金额(季度,硬币,镍币和硬币) . 购买金额必须低于1美元,更改金额为1美元 . 我需要知道有多少人,硬币,镍币和便士才会回来 .

设置字典是最好的吗?

5 回答

  • 7

    这可能非常快 - 每个面额只有几个操作:

    def change(amount):
        money = ()
        for coin in [25,10,5,1]
            num = amount/coin
            money += (coin,) * num
            amount -= coin * num
    
        return money
    
  • 4

    您最好的选择是可能有一个硬币大小的排序字典,然后循环检查您的更改是否大于该值,添加该硬币并减去该值,否则移动到字典中的下一行 .

    例如

    Coins = [50, 25, 10, 5, 2, 1]
    ChangeDue = 87
    CoinsReturned = []
    For I in coins:
       While I >= ChangeDue:
            CoinsReturned.add(I)
            ChangeDue = ChangeDue - I
    

    请原谅我糟糕的python语法 . 希望这足以继续下去 .

  • 0

    哎呀,你的意思是这不是每个编程课程中的问题2b了吗?呃,可能不是,他们似乎也不会教人们如何改变 . (或许他们这样做:这是一项家庭作业吗?)

    如果你找到一个超过50岁的人并让他们为你做出改变,那就像这样 . 假设您有一张3.52美元的支票,并且您将收银员交给了二十美元 . 他们会通过说“三五二”来改变

    • 算上三便士,说"three, four, five"(3.55)

    • 倒数2个镍币,(3.60,3.65)

    • 倒数一角钱(3.75)

    • 四分之一(4美元)

    • 一美元钞票(五美元)

    • 一张5美元的钞票(十美元)

    • 一张10美元的钞票(二十美元)

    这是一个递归过程的核心:你倒数当前面额,直到当前金额加上下一个面额甚至出现 . 然后上升到下一个面额 .

    当然,您可以如上所述迭代地执行此操作 .

  • 0

    使用数论的整数分区可以很容易地解决这个问题 . 我写了一个递归函数,它接受一个数字和一个分区列表,并返回组成给定数字的可能组合的数量 .

    http://sandboxrichard.blogspot.com/2009/03/integer-partitions-and-wiki-smarts.html

    这不完全是你想要的,但它可以很容易地修改,以获得你的结果 .

  • 0

    以上解决方案工作 .

    amount=int(input("Please enter amount in pence"))
    coins = [50, 25, 10, 5, 2, 1]
    coinsReturned = []
    for i in coins:
      while amount >=i:
            coinsReturned.append(i)
            amount = amount - i
    print(coinsReturned)
    

    或者,可以通过使用floor和mod函数来达到解决方案 .

    amount = int(input( "Please enter amount in pence" ))
    # math floor of 50
    fifty = amount // 50
    # mod of 50 and floor of 20
    twenty = amount % 50 // 20
    # mod of 50 and 20 and floor of 10
    ten = amount % 50 % 20 // 10
    # mod of 50 , 20 and 10 and floor of 5
    five = amount % 50 % 20 % 10 // 5
    # mod of 50 , 20 , 10 and 5 and floor of 2
    two = amount % 50 % 20 % 10 % 5 // 2
    # mod of 50 , 20 , 10 , 5 and 2 and floor of 1
    one = amount % 50 % 20 % 10 % 5 % 2 //1
    
    print("50p>>> " , fifty , " 20p>>> " , twenty , " 10p>>> " , ten , " 5p>>> " , five , " 2p>>> " , two , " 1p>>> " , one )
    

    或另一种解决方案

    amount=int(input("Please enter the change to be given"))
    endAmount=amount
    
    coins=[50,25,10,5,2,1]
    listOfCoins=["fifty" ,"twenty five", "ten", "five", "two" , "one"]
    change = []
    
    for coin in coins:
        holdingAmount=amount
        amount=amount//coin
        change.append(amount)
        amount=holdingAmount%coin
    
    print("The minimum coinage to return from " ,endAmount, "p is as follows")
    for i in range(len(coins)):
      print("There's " , change[i] ,"....",  listOfCoins[i] , "pence pieces in your change" )
    

相关问题