Milan
Milan

Reputation: 1750

Generating all possibles combinations of values from a list of single values

Basically, I want to generate truth table list of values using Python. For instance, if I have the following values: [0, 1], I want the following list to be generated:

[(0, 0), (0, 1), (1, 0), (1, 1)]

If I want my table to have three inputs, then the following list should be generated:

[(0, 0, 1), (0, 1, 0), (0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 0), (1, 0, 1), (1, 1, 1)]

So:

Right now my solution is the following but I find it heavy:

from itertools import permutations

number_of_inputs = 3
set_of_values = [0, 1]
list_of_permutations = list(dict.fromkeys(list(permutations(set_of_values  * number_of_inputs, number_of_inputs))))

Do you have a better solution ? Such as a one-liner function call

Upvotes: 0

Views: 47

Answers (2)

j1-lee
j1-lee

Reputation: 13939

It seems like product is enough:

number_of_inputs = 3
set_of_values = [0, 1]
list_of_permutations = itertools.product(set_of_values, repeat=3)
print(*list_of_permutations)
# (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1)

Upvotes: 3

Jamie Marshall
Jamie Marshall

Reputation: 2304

does this work?

from itertools import permutations

number_of_inputs = 3
set_of_values = [0, 1]
result = set(permutations(set_of_values  * number_of_inputs, number_of_inputs)

Upvotes: 0

Related Questions