我想打印集合中所有可能的3個數字組合(0 ... n-1),而每個組合都是唯一的。我通過這段代碼獲取變量ñ:Python中一組3個數字的所有可能組合
n = raw_input("Please enter n: ")
但我被困在未來與算法。請幫忙嗎?
我想打印集合中所有可能的3個數字組合(0 ... n-1),而每個組合都是唯一的。我通過這段代碼獲取變量ñ:Python中一組3個數字的所有可能組合
n = raw_input("Please enter n: ")
但我被困在未來與算法。請幫忙嗎?
combos = []
for x in xrange(n):
for y in xrange(n):
for z in xrange(n):
combos.append([x,y,z])
效率最低的方式 – kingmakerking
itertools
是你的朋友在這裏,特別是permutations
。
演示:
from itertools import permutations
for item in permutations(range(n), 3):
print item
這是假設你有Python的2.6或更高版本。
我認爲你的意思是'itertools.combinations' – Duncan
@Duncan我認爲OP的組合定義可能比編程更普遍,所以我決定包含它。 –
from itertools import combinations
list(combinations(range(n),3))
這會爲你使用Python比後來的工作,只要2.6
如果你想所有重複的可能組合值和位置不同,你需要使用的產品是這樣的:
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)])
希望這有助於
你嘗試過什麼嗎?在你的問題中添加你的代碼會很好。 – abhishekgarg