2014-03-30 175 views
-3

我想打印集合中所有可能的3個數字組合(0 ... n-1),而每個組合都是唯一的。我通過這段代碼獲取變量ñPython中一組3個數字的所有可能組合

n = raw_input("Please enter n: ") 

但我被困在未來與算法。請幫忙嗎?

+0

你嘗試過什麼嗎?在你的問題中添加你的代碼會很好。 – abhishekgarg

回答

0
combos = [] 
for x in xrange(n): 
    for y in xrange(n): 
     for z in xrange(n): 
      combos.append([x,y,z]) 
+0

效率最低的方式 – kingmakerking

1

itertools是你的朋友在這裏,特別是permutations

演示:

from itertools import permutations 

for item in permutations(range(n), 3): 
    print item 

這是假設你有Python的2.6或更高版本。

+0

我認爲你的意思是'itertools.combinations' – Duncan

+0

@Duncan我認爲OP的組合定義可能比編程更普遍,所以我決定包含它。 –

8
from itertools import combinations 
list(combinations(range(n),3)) 

這會爲你使用Python比後來的工作,只要2.6

1

如果你想所有重複的可能組合值和位置不同,你需要使用的產品是這樣的:

from itertools import product 
t = range(n) 
print set(product(set(t),repeat = 3)) 

例如,如果n = 3,輸出將是:

set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)]) 

希望這有助於

相關問題