Python function: Find Change from purchase amount

前端 未结 6 779
旧时难觅i
旧时难觅i 2021-01-29 13:56

I\'m looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, a

6条回答
  •  孤城傲影
    2021-01-29 14:18

    The above soloution working.

    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)
    

    Alternatively a solution can reached by using the floor and mod functions.

    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 )
    

    Or another solution

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

提交回复
热议问题