Ipse Lium
Ipse Lium

Reputation: 1080

Combinations of list of tuples with alternative values

I defined a dictionary which gives a list of alternative choices for tuples as :

d = {(2, 1): [(2, 1)],
     (1, 2): [(1, 2)],
     (2, 0.5): [(2, 1), (2, 0.5)],
     (0.5, 2): [(0.5, 2), (1, 2)],
     (0.5, 0.5): [(0.5, 0.5), (1, 1), (0.5, 1), (1, 0.5)],
     (1, 1): [(1, 1), (0.5, 0.5)]}

For instance :

I also have a list of tuples (each tuple of this list is always a key of the dictionary d). For instance :

lst = [(2, 1), (1, 1), (1, 1)]

I want to list all alternatives to this list using the alternative values provided by the dictionary d. For instance, alternatives to lst will be :

[(2, 1), (1, 1), (1, 1)]
[(2, 1), (0.5, 0.5), (0.5, 0.5)]
[(2, 1), (0.5, 0.5), (1, 1)]
[(2, 1), (1, 1), (0.5, 0.5)]

I'm sure I can do this with itertools and lambdas, but did not find any solution for now.

Upvotes: 0

Views: 115

Answers (1)

Paritosh Singh
Paritosh Singh

Reputation: 6246

You can use itertools product to get the desired output.

d = {(2, 1): [(2, 1)],
     (1, 2): [(1, 2)],
     (2, 0.5): [(2, 1), (2, 0.5)],
     (0.5, 2): [(0.5, 2), (1, 2)],
     (0.5, 0.5): [(0.5, 0.5), (1, 1), (0.5, 1), (1, 0.5)],
     (1, 1): [(1, 1), (0.5, 0.5)]}

lst = [(2, 1), (1, 1), (1, 1)]

from itertools import product
result = list(product(*(d[k] for k in lst)))

This produces a list of tuples. If you wish to have all values as lists instead, you can just iterate and access them in that way.

for val in result:
    print(list(val))

#Output:
[(2, 1), (1, 1), (1, 1)]
[(2, 1), (1, 1), (0.5, 0.5)]
[(2, 1), (0.5, 0.5), (1, 1)]
[(2, 1), (0.5, 0.5), (0.5, 0.5)]

Upvotes: 3

Related Questions