[英]All possible combination of 3 numbers in a set in Python
我想打印集合中 3 個數字的所有可能組合( 0 ... n-1 ),而這些組合中的每一個都是唯一的。 我通過以下代碼獲得變量n :
n = raw_input("Please enter n: ")
但我堅持想出算法。 請問有什么幫助嗎?
from itertools import combinations
list(combinations(range(n),3))
只要您使用的版本晚於 Python 2.6,這就會起作用
itertools
是你的朋友,特別是permutations
。
演示:
from itertools import permutations
for item in permutations(range(n), 3):
print item
這是假設您擁有 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)])
希望這可以幫助
combos = []
for x in xrange(n):
for y in xrange(n):
for z in xrange(n):
combos.append([x,y,z])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.