Python遞迴 找零錢

2022-06-01 21:00:13 字數 2518 閱讀 6347

#無法解決某些情況,例如存在21元的零錢

def fun(n):

count = 0

while n > 25:

n = n - 25

count = count + 1

while n > 10:

n = n - 10

count = count + 1

while n > 5:

n = n - 10

count = count + 1

while n > 0:

n = n - 1

count = count + 1

return count

print(fun(63))

def fun(n):  # 分好類

if n <= 0:

return 0

elif n >= 25:

return 1 + fun(n-25)

elif n >= 10:

return 1 + fun(n-10)

elif n >= 5:

return 1 + fun(n-5)

elif n >= 1:

return 1 + fun(n-1)

print(fun(25))

import time

def recmd(valuelist, change, knowlist):

minnum = change

if change in valuelist: # 可以作為結束條件

knowlist[change] = 1

return 1

elif knowlist[change] > 0: # 回憶

return knowlist[change]

else:

for i in [c for c in valuelist if c <= change]: # 常用

num = 1 + recmd(valuelist, change - i, knowlist)

if num < minnum:

minnum = num

knowlist[change] = minnum

return minnum # 最後記得要返回

print(time.process_time()) # time.clock()被拋棄

print(recmd([1, 5, 10, 25], 77, [0]*79)) # 建立全為0的表

print(time.process_time())

import time

from pythonds.basic.stack import stack

def dp(valuelist, change, minnum, coinused): # minnum初始化為0,之後需要利用到這些資料

for cents in range(1, change+1): # 從小到大遞推

coincount = cents # 初始化乙個無害的最小值

newcoin = 1

for j in [c for c in valuelist if c <= cents]: # 常用技巧

if 1 + minnum[cents-j] < coincount:

coincount = 1 + minnum[cents - j]

newcoin = j

minnum[cents] = coincount

coinused[cents] = newcoin # 每乙個change的最優解都是由兩部分組成,這裡是記錄其中一部分

return minnum[change]

def printselection(change, coinused):

coin = change

s = stack()

while coin > 0:

thiscoin = coinused[coin]

s.push(thiscoin)

coin = coin - thiscoin

while not s.isempty():

print(s.pop())

vallist = [1, 5, 10, 25]

amnt = 63

minn = [0]*64

coinused = [0]*64

print(dp(vallist, amnt, minn, coinused)) # 建立表的方式get

print(coinused[1:]) # 列印全部

printselection(amnt, coinused) # 列印組成部分

動態規劃解法的必要條件:問題的最有解包含了更小規模的最優解,即每一步都要依靠前面某步的最優解

talk is cheap. show me the code. 將演算法思路轉化成具體**需要不斷實踐,積累經驗

python找零錢程式 Python 找零問題

coding utf 8 def change money money print 總金額 str money 元 loop true tmp 面值列表 單位 元 type 100,50,20,10,5,1,0.5,0.1 sy int money 10 將傳入的金額 10,轉換為 角 單位 whi...

找零錢問題

問題描述 我們知道人民幣有1 2 5 10 20 50 100這幾種面值。現在給你n 1 n 250 元,讓你計算換成用上面這些面額表示且總數不超過100張,共有幾種。比如4元,能用4張1元 2張1元和1張2元 2張2元,三種表示方法。輸入有多組,每組一行,為乙個整合n。輸入以0結束。輸出該面額有幾...

找零錢 貪心

現 在有1,2,5,10,20,50,100面值的人名幣若干。你的任務就是用最少的張數來找錢。如需要找23元,我們用一張20,一張2元,一張1元即可。所以3張就是最少的張數。description 輸入多組資料,第一行n n 100 表示有多少組錢需要找,第2 n 1行,輸入要找的錢m m 0 in...