What would be an efficient algorithm to do the following: given a list, we have to output all combinations of elements up to a length n. Let's say x = ['a','b','c','d','e'] and n = 2. The output should be:
[['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']]
Since you're looking for an algorithm and not a tool... this gives all possible unique combinations.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With