Doctor David Anderson
Doctor David Anderson

Reputation: 274

Python all combinations for multiple lists with variable k

I am able to produce all combinations given a particular value (k) for a single list as follows:

lst = []
p = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
c = itertools.combinations(p, k)
for i in c:
    lst.append(list(i))
print lst

Note, in this code, k requires a specific value to be inputted - it cannot be a variable.

However, I now have multiple lists in which I need all combinations for various k:

m = [1, 2, 3, 4]
t = [1, 2, 3, 4]
c = [1, 2, 3, 4, 5]
ss =[1, 2, 3]

Put simply: I require an output of all the combinations possible for all these lists. E.g. k = 1 through 4 for m and t, 1 through 5 for c, and 1 through 3 for ss.

Example of k = 2 for ss would be

    m = [1, 2, 3, 4]
    t = [1, 2, 3, 4]
    c = [1, 2, 3, 4, 5]
    ss = [1, 2]

    m = [1, 2, 3, 4]
    t = [1, 2, 3, 4]
    c = [1, 2, 3, 4, 5]
    ss = [1, 3]    

    m = [1, 2, 3, 4]
    t = [1, 2, 3, 4]
    c = [1, 2, 3, 4, 5]
    ss = [2, 3]

Follow this pattern for all values combinations of k possible in all variables.

Let me know if this is unclear and I can edit question accordingly.

Upvotes: 0

Views: 124

Answers (1)

DSM
DSM

Reputation: 353379

You can get your output via itertools.product alone or via combinations. We could cram this all into one line if we really wanted, but I think it's more comprehensible to write

from itertools import combinations, product

def all_subs(seq):
    for i in range(1, len(seq)+1):
        for c in combinations(seq, i):
            yield c

after which we have

>>> m,t,c,ss = [1,2,3,4],[1,2,3,4],[1,2,3,4,5],[1,2,3]
>>> seqs = m,t,c,ss
>>> out = list(product(*map(all_subs, seqs)))
>>> len(out)
48825

which is the right number of results:

>>> (2**4 - 1) * (2**4 - 1) * (2**5-1) * (2**3 - 1)
48825

and hits every possibility:

>>> import pprint
>>> pprint.pprint(out[:4])
[((1,), (1,), (1,), (1,)),
 ((1,), (1,), (1,), (2,)),
 ((1,), (1,), (1,), (3,)),
 ((1,), (1,), (1,), (1, 2))]
>>> pprint.pprint(out[-4:])
[((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 2)),
 ((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 3)),
 ((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (2, 3)),
 ((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 2, 3))]

Upvotes: 1

Related Questions