How to get all combinations of "sub"lists from a list
Wow
So if I start with:
x = [a, b, c]
y = [[a], [b], [c], [a,b], [b,c]]
How can I get all combinations x
of elements from it y
? It's just like:
y = [ [[a, b], c], [[b,c], a], [a, b, c]
I've looked into itertools and list comprehensions but still struggling. All elements in the original list must appear in each item of the resulting list.
Wow
Now, this assumes you have a list of valid combinations that you can use. Using a recursive function, I am able to get the desired output.
Note: I have done 0 optimizations
import numpy
def build_combo(current_set, all_combos):
global count, req_options
for each in all_combos:
if all(len(numpy.intersect1d(each, x)) == 0 for x in current_set):
inner_set = current_set.copy()
inner_set.append(each)
flat = []
for x in inner_set:
flat.extend(x)
if all(x in flat for x in req_options):
built_combos.append(inner_set)
else:
build_combo(inner_set, all_combos)
req_options = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
all_combos = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'],
['a', 'b'], ['c', 'd'], ['a', 'f'], ['f', 'g'],
['a', 'c', 'd'], ['g', 'f', 'e', 'b']]
built_combos = []
build_combo([], all_combos)
option_sets = set()
for combo in built_combos:
newset = set()
for element in combo:
newset.add(frozenset(element))
option_sets.add(frozenset(newset))
for option_set in option_sets:
combo_str = ''
for option in option_set:
combo_str += '[{}]'.format('+'.join(option))
print(combo_str)
Output ("+" sign added to printout for easier reading):
[e][g][c+d][b][f+a]
[a][c][d][f+e+g+b]
[f+g][e][c][d][a+b]
[f+g][e][c+d][a][b]
[f][e][c][g][a][b][d]
[c+a+d][f][e][g][b]
[b][e][f+g][c+a+d]
[f][e][g][c+d][a+b]
[f+g][e][a+b][c+d]
[f][e][g][c+d][a][b]
[e][c][g][b][f+a][d]
[f+g][e][c][a][b][d]
[f][e][c][g][d][a+b]
[a][f+e+g+b][c+d]
[c+a+d][f+e+g+b]