Python中一个集合中3个数字的所有可能组合
我想打印集合0中3个数字的所有可能组合。。。n-1,而这些组合中的每一个都是唯一的。我通过以下代码获得变量n:Python中一个集合中3个数字的所有可能组合,python,algorithm,combinatorics,Python,Algorithm,Combinatorics,我想打印集合0中3个数字的所有可能组合。。。n-1,而这些组合中的每一个都是唯一的。我通过以下代码获得变量n: n = raw_input("Please enter n: ") 但我一直在想算法。有什么帮助吗?itertools是您的朋友,特别是置换 combos = [] for x in xrange(n): for y in xrange(n): for z in xrange(n): combos.append([x,y,z]) 演
n = raw_input("Please enter n: ")
但我一直在想算法。有什么帮助吗?itertools是您的朋友,特别是置换
combos = []
for x in xrange(n):
for y in xrange(n):
for z in xrange(n):
combos.append([x,y,z])
演示:
这是假设您有Python2.6或更新版本
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)])
希望这有帮助你尝试过什么吗??在你的问题中添加你的代码会很好。我想你指的是itertools。combinations@Duncan我认为OP对组合的定义可能比编程的定义更一般,所以我决定将其包括在内。
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)])