jef
jef

Reputation: 4083

Calculate all possible combinations from differnt array in Python

I have some group data like below a, b, c and so on. What I want to do is to calculate all possible combinations from the data. It's ok if the count of input data is always same. But in my case, I want to assume that the count of input data is from 0 to N, I mean a, b, c, d, e ...

I think I have to use recurrent loop. But I'm not sure to use recurrent loop to resolve this problem.

Input

a = ["x", "y"]
b = ["q", "w", "c"]
c = ["i", "o", "p"]
...

Ouput

The expected output is all combinations with each value's all combinations.

[{a:[], b:["q"], c:["i", "o"]}, {a:["x"], b:[], c:["o"]}, ...]

Upvotes: 1

Views: 101

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226486

If I am understanding what you're looking for, you can use itertools.product() over the powersets of the inputs (there is a recipe for powerset() in the docs). The map() function can be used to apply powerset to each of the inputs.

from itertools import product, combinations, chain
from pprint import pprint

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

names = ['a', 'b', 'c']
a = ["x", "y"]
b = ["q", "w", "c"]
c = ["i", "o", "p"]

result = []
for values in product(*map(powerset, [a, b, c])):
    result.append(dict(zip(names, values)))
pprint(result)

Here is how it works:

First, it builds the powersets:

>>> list(powerset(["x", "y"]))
[(), ('x',), ('y',), ('x', 'y')]
>>> 
>>> list(powerset(["x", "y"]))
[(), ('x',), ('y',), ('x', 'y')]
>>> list(powerset(["q", "w", "c"]))
[(), ('q',), ('w',), ('c',), ('q', 'w'), ('q', 'c'),
 ('w', 'c'), ('q', 'w', 'c')]
>>> list(powerset(["i", "o", "p"]))
[(), ('i',), ('o',), ('p',), ('i', 'o'), ('i', 'p'), 
 ('o', 'p'), ('i', 'o', 'p')]

Next product() pulls one element from each powerset:

>>> for values in product(*map(powerset, [a, b, c])):
        print(values)

((), (), ())
((), (), ('i',))
((), (), ('o',))
((), (), ('p',))
((), (), ('i', 'o'))
((), (), ('i', 'p'))
((), (), ('o', 'p'))
((), (), ('i', 'o', 'p'))
((), ('q',), ())
((), ('q',), ('i',))
((), ('q',), ('o',))
((), ('q',), ('p',))
((), ('q',), ('i', 'o'))
((), ('q',), ('i', 'p'))
((), ('q',), ('o', 'p'))
((), ('q',), ('i', 'o', 'p'))

Lastly, we zip() together the above results with the variable names to make a dict():

# What zip does
>>> list(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p'))))
[('a', ()), ('b', ('q',)), ('c', ('i', 'o', 'p'))]

# What dict does with the zip:
>>> dict(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p'))))
{'b': ('q',), 'c': ('i', 'o', 'p'), 'a': ()}

Upvotes: 5

Related Questions