Sourasekhar Banerjee - 9 months ago 47

Python Question

I have the following list:

`list1 = ['g1','g2','g3','g4']`

I want to find

`2^n-2`

`n`

`n = 4`

`2^4 -2 = 14`

The combinations are:

`[[['g1'],['g2','g3','g4']],[['g2'],['g1','g3','g4']], [['g3'],['g1','g2','g4']],['g4'],['g1','g2','g3']],[['g1','g2'],['g3','g4']],[['g1','g3'],['g2','g4']],[['g1','g4'],['g3','g4']],[['g2','g3'],['g1','g4']],`

[['g2','g4'],['g1','g3']],[['g3','g4'],['g1','g2']],[['g1','g2','g3'],['g4']],[['g2','g3','g4'],['g1']],[['g3','g4','g1'],['g2']],[['g4','g1','g2'],['g3']]]

I know one approach:

in first iteration take single element and put it into a list and other elements in second list:

`['g1'],['g2','g3','g4']`

in second iteration take 2 elements in a list and other elements in second list.

`['g1','g2'],['g1','g4']`

Is there any other approach ??

I'm writing this program in python.

My approach is costly. Is there any library method to do this quickly.

Answer Source

Here's a functional approach using `itertools`

```
import itertools as iter
list1 = ['g1', 'g2', 'g3', 'g4']
combinations = [iter.combinations(list1, n) for n in range(1, len(list1))]
flat_combinations = iter.chain.from_iterable(combinations)
result = map(lambda x: [list(x), list(set(list1) - set(x))], flat_combinations)
# [[['g1'], ['g4', 'g3', 'g2']], [['g2'], ['g4', 'g3', 'g1']], [['g3'], ['g4', 'g2', 'g1']],...
len(result)
# 14
```