Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing all combinations of a list up to length n (Python)

Tags:

python

list

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']]
like image 445
Mariska Avatar asked Jul 26 '14 13:07

Mariska


1 Answers

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
like image 66
kkontagion Avatar answered Nov 10 '22 04:11

kkontagion