1. 程式人生 > >練習五十四:函式的練習

練習五十四:函式的練習

取一個任意小於1美元的金額,然後計算可一換成最少多少沒硬幣。
硬幣有1美分,5美分,10美分,25美分四種。
1美元等於100美分
例如:0.76美元可以換成3枚25美分和1枚1美分,類似76枚1美分,2枚25美分+2枚10美分+1枚5美分+1枚1美分都是不符合條件的

方法一:笨辦法

def least_num(num):
    if num < 5:
        least = num
        return least,'{}個1美分'.format(least)
    if num == 5:
        least = num//5
        return least,'{}個5美分'.format(least)
    if num <
10: least = num//5 +num%5 return least,'{}個5美分,{}個1美分'.format(num//5,num%5) if num == 10: least = nun//10 return least,'{}個10美分'.format(least) if num <25: least = num//10 + num%10 return least,'{}個10美分,{}個1美分'.format(num//10,num%10) if num == 25: least = nun//25 return least,'{}個25美分'.format(least) if num >
25 and num<100: least = num//25 + num%25//10 + num%25%10//5 +num%25%10%5 return least,'{}個25美分,{}個10美分,{}個5美分,{}個1美分'.format(num//25,num%25//10,num%25%10//5,num%25%10%5) num = int(input('輸入一個小於1美元的金額(為了簡單我們輸入小於100美分):')) print(least_num(num))

執行結果:

輸入一個小於1美元的金額(為了簡單我們輸入小於100美分):76
(4, '3個25美分,0個10美分,0個5美分,1個1美分')

方法二:簡單的抽出來

def least_num(num):
    coin = [25,10,5,1]
    coinN = []
    for item in coin:
        coinN.append(num//item)
        num = num%item
    return coinN
if __name__ == "__main__":
    num = int(input('輸入一個小於1美元的金額:'))
    coinN = least_num(num)
    print('{}個25美分,{}個10美分,{}個5美分,{}個1美分'.format(coinN[0],coinN[1],coinN[2],coinN[3]))

執行結果:

輸入一個小於1美元的金額:76
3個25美分,0個10美分,0個5美分,1個1美分