2014-05-25 28 views
1

我試圖寫一個函數,使得NCK從列表中蟒功能NCK選擇ķ從n個的列表中的元素在python

例如,從列表中對:

['a', 'b', 'c'] 

輸出應該是:

[['a','b'],['a','c'],['b','c']] 

但是我沒有得到任何輸出

,這裏是我的嘗試:

def chose(elements, k): 
    output = [] 
    for i in range(len(elements)): 
     if k == 1: 
      output.append(elements[i]) 
     for c in chose(elements[i+1:], k-1): 
      output.append(elements[i]) 
      output.append(c) 
    return output 
print chose(['a', 'b', 'c'],2) 

能不能請你告訴什麼是錯的功能

+0

http://meta.stackoverflow.com/questions/254094/question-that-使用鹼性調試可待解決,。建議閱讀http://ericlippert.com/2014/03/05/how-to-debug-small-programs/。 –

+0

另請參考:https://docs.python.org/2/library/itertools.html –

回答

1

使用itertools.combinations,如果你想找到的所有組合:

from itertools import combinations 

a = ['a', 'b', 'c'] 
result = [list(i) for i in combinations(a,2)] 

的文件和實施combinations()功能都可以在here ...找到

更新 這個函數應該做你想要什麼:

def chose(elements, k): 
    output = [] 
    if k == 1: 
     return [[i] for i in elements] 
    else: 
     for i in range(len(elements)): 
      head = elements[i] 
      tails = chose(elements[i+1:], k-1) 
      output += [[head] + tail for tail in tails] 
     return output 

print chose(['a','b','c'], 2) 
+0

不幸的是,我們不允許使用libs:| – MotherLand

+1

在我發佈的鏈接上查找'iterfunction.combination()'的實現。如果你不允許使用庫,你可以複製它。 – miindlek

1

您可以使用冪不使用任何進口:

def power_set(items,k): 
    n = len(items) 
    for i in xrange(2**n): 
     combo = [] 
     for j in xrange(n): 
      if (i >> j) % 2 == 1: 
       combo.append(items[j]) 
     if len(combo) == k: 
      yield combo 

print(list(power_set(['a', 'b', 'c'],2))) 

[['a', 'b'], ['a', 'c'], ['b', 'c']] 
相關問題