Sourasekhar Banerjee Sourasekhar Banerjee - 21 days ago 7
Python Question

find 2^n -2 combinations of elements in a list

I have the following list:

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


I want to find
2^n-2
combinations where
n
is the total number of items in the list. For
n = 4
the result should be
2^4 -2 = 14
, i.e. 14 combinations.

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

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