假設我們有一個串列和目標:
串列:[1,2,3,4,5]
和目標:20
我們希望通過乘法找到總組合來達到這個目標,即:,,,,
我做[1,4,5]
了
這個代碼,但我似乎不知道如何洗掉那些,所以我也有它們,我的意思是我收到:
,。
但是沒有,我似乎無法得到它,我試圖以某種方式“作弊”來得到它,但我不能,因為我的代碼不適合它......[4,5]
[2,5,2]
[1,2,2,5]
[1,4,5]
[1,2,2,5]
[1]
def Coin(target, lst, temp=[], comb=[]):
if target == 1:
comb.append(temp)
return comb
if len(lst) == 0:
return []
if target >= lst[0]:
if lst[0] > 1:
take=Coin(target/lst[0],lst,temp [lst[0]],comb)
dont_take=Coin(target,lst[1:],temp,comb)
else:
take_1 = Coin(target, lst[1:], temp [1], comb)
return take_1
return take
return comb
print(Coin(20, [1,2,3,4,5], [], []))
[[1, 2, 2, 5], [1, 4, 5]]
如何添加沒有1的部分?我不需要解決方案,因為如上所述,不是家庭作業,而是考試練習。一個線索就足夠了,我想自己找到它,但我需要一個線索。
uj5u.com熱心網友回復:
也許你應該結合
if lst[0] > 1:
else:
在一起,這意味著對于 1 我們還應該決定是否接受。
uj5u.com熱心網友回復:
使用生成器比yield
使用函式更容易做到這一點return
。
不同之處在于您只能執行return
一次,而您可以yield
執行任意次數(如果沒有解決方案,則為 0)。
如果你想回傳 a list
,你仍然可以,像這樣:
def coin (target, lst):
return list(_coin(target, lst, 0)
def _coin (target, lst, i):
...
如果這無關緊要,生成器不必一次生成整個串列來節省記憶體。你只需:
def coin (target, lst, i=0):
... # Use yield as often as you want, all will be returned.
其次,您遇到了 Python 中最常見的問題。您正在使用可變物件作為默認值。如果您要繼續使用當前的方法,您需要:
def coin(target, lst, temp=None, comb=None):
if temp is None:
temp = []
if comb is None:
comb = []
...
第三,您應該養成遵循標準樣式約定的習慣。在許多方面,約定是什么并不重要。但是每個人都在同一個頁面上,確實如此。因此,您應該嘗試遵循最常見的 Python 約定。其中函式應該被命名coin
而不是Coin
.
uj5u.com熱心網友回復:
編輯:問題的規則是:
僅正整數(不允許 0)。
數字只能出現一次(在輸入時)。
不能重復串列中的數字。例如:[1,2,3,4], n=12 >> [1,12], [12,1], [3,4], [2,6], [1,3,4], [ 1,2,6]。
不是:[1,2,2,3],[2,2,3]這就是我的猜測。
def coin_change_MULTI(num, lst): if num == 1 and 1 not in lst: return [] return Coin_MULTI(num, sorted(lst), [], []) def Coin_MULTI(target, lst, temp=[], comb=[]): if target == 1: if big_than_target(1, lst): return [[1]] comb.append(temp) return comb if len(lst) == 0: return [] if target >= lst[0]: if lst[0] > 1: take=Coin_MULTI(target/lst[0],lst[1:],temp [lst[0]],comb) dont_take=Coin_MULTI(target,lst[1:],temp,comb) return comb else: take_1 = Coin_MULTI(target, lst[1:], temp [1], comb) dont_take_1 = Coin_MULTI(target, lst[1:], temp, comb) return comb return take dont_take return comb print(coin_change_MULTI(12, [2,4,6,12,7,3, 1])) print(coin_change_MULTI(1, [2,4,6,12,7,3,1])) print(coin_change_MULTI(1, [2,4,6,12,7,3])) print(coin_change_MULTI(100, [2,4,6,12,7,3,1])) print(coin_change_MULTI(576, [2,4,6,12,7,3,1])) print(coin_change_MULTI(12096, [2,4,6,12,7,3,1])) print(coin_change_MULTI(0, [2,4,6,12,7,3,1])) print((coin_change_MULTI(24, [2,4,6,12,7,3,1]))) [[1, 2, 6], [1, 3, 4], [1, 12], [2, 6], [3, 4], [12]] [[1]] [] [] [[1, 2, 4, 6, 12], [2, 4, 6, 12]] [[1, 2, 3, 4, 6, 7, 12], [2, 3, 4, 6, 7, 12]] [] [[1, 2, 3, 4], [1, 2, 12], [1, 4, 6], [2, 3, 4], [2, 12], [4, 6]]
行程以退出代碼 0 結束
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507856.html
下一篇:遞回函式內的兩個呼叫