如何编写一个高效的算法,用于以下操作:给定一个列表,我们需要输出长度不超过n的所有元素组合。假设x=['a','b','c','d','e'],n=2。输出应为:
[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e']]
如何编写一个高效的算法,用于以下操作:给定一个列表,我们需要输出长度不超过n的所有元素组合。假设x=['a','b','c','d','e'],n=2。输出应为:
[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e']]
itertools.combinations
并迭代不断增加的长度:from itertools import combinations
x = ['a','b','c','d','e']
c = []
n = 2
for i in range(n):
c.extend(combinations(x, i + 1))
print(c)
或者,使用列表推导:
from itertools import combinations
x = ['a','b','c','d','e']
n = 2
c = [comb for i in range(n) for comb in combinations(x, i + 1)]
print(c)
x = ['a', 'b', 'c', 'd', 'e']
result = []
for length in range(1,3):
result.extend(itertools.combinations(x, length))
print result
[('a',), ('b',), ('c',), ('d',), ('e',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e')]
>>> x = ['a','b','c','d','e']
>>> n = 2
>>> import itertools
>>> [list(comb) for i in range(1, n+1) for comb in itertools.combinations(x, i)]
[['a'], ['b'], ['c'], ['d'], ['e'],
['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'],
['b', 'c'], ['b', 'd'], ['b', 'e'],
['c', 'd'], ['c', 'e'], ['d', 'e']]
由于您正在寻找算法而不是工具...这将给出所有可能的唯一组合。
x = ['a','b','c','d','e']
n = 2
outList = []
for i in range(0,len(x)):
outEleList = []
outEleList.append(x[i])
outList.append(outEleList)
for c in range(i,len(x)):
out = []
out.append(x[i])
out.append(x[c])
outList.append(out)
print outList