[英]Python to C++: Algorithm that list all combinations of Knapsack using recursion
[英]python recursion list combinations without using generator
我正在學習python3。 要想更多地考慮遞歸,我想實現一個函數comb(n,k),該函數返回一個列表,其中包含集合{1,2,…,n}中kk元素的所有組合。
我認為使用循環是不明智的,因為嵌套循環的數量取決於k。 所以我考慮遞歸。 當我找不到正確的答案時,我嘗試編寫受此問題啟發的函數。
def combinations(sub, data_set, index, still_needed):
if still_needed == 0:
return sub
for i in range(index, len(data_set)):
sub.append(data_set[i])
still_needed = still_needed - 1
return combinations(sub, data_set, index+1, still_needed)
def comb(n, k):
data_set = list(range(1, n+1))
print (combinations([], data_set, 0, k))
如果我測試Comb(6,3),我只會得到[1,2,3]。 我想獲得所有組合。 我的代碼有什么問題? 還是錯過了重要的事情? 我只想學習python的遞歸,這不是一項家庭作業,謝謝。
預期結果如下:
[[1, 5, 6],
[2, 5, 6],
[3, 5, 6],
[4, 5, 6],
[1, 4, 6],
[2, 4, 6],
[3, 4, 6],
[1, 3, 6],
[2, 3, 6],
[1, 2, 6],
[1, 4, 5],
[2, 4, 5],
[3, 4, 5],
[1, 3, 5],
[2, 3, 5],
[1, 2, 5],
[1, 3, 4],
[2, 3, 4],
[1, 2, 4],
[1, 2, 3]]
雖然順序並不重要。 我將不勝感激,如果有任何pythonic方法可以解決此問題,例如。 嵌套[expression for item in iterable]
(因為我嘗試過但失敗了)。
再次感謝。
函數中的問題是在for
循環中有一個return
語句:它在第一次迭代期間停止執行該函數。
這是您可以用於遞歸的基本結構:
def combinations(n, k, min_n=0, accumulator=None):
if accumulator is None:
accumulator = []
if k == 0:
return [accumulator]
else:
return [l for x in range(min_n, n)
for l in combinations(n, k - 1, x + 1, accumulator + [x + 1])]
print(combinations(6, 3))
# [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 3, 4], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [1, 5, 6], [2, 3, 4], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6], [2, 5, 6], [3, 4, 5], [3, 4, 6], [3, 5, 6], [4, 5, 6]]
要檢查結果是否正確,可以針對itertools
進行測試:
import itertools
print(list(itertools.combinations(range(1,7),3)))
# [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 4), (1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (1, 5, 6), (2, 3, 4), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6), (3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]
print(
list(itertools.combinations(range(1, 7), 3))
==
[tuple(comb) for comb in combinations(6, 3)]
)
# True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.