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:
- All permutations should be generated
- No duplicate permutation in the list
Right now my solution is the following but I find it heavy:
JavaScript
x
6
1
from itertools import permutations
2
3
number_of_inputs = 3
4
set_of_values = [0, 1]
5
list_of_permutations = list(dict.fromkeys(list(permutations(set_of_values * number_of_inputs, number_of_inputs))))
6
Do you have a better solution ? Such as a one-liner function call
Advertisement
Answer
It seems like product
is enough:
JavaScript
1
6
1
number_of_inputs = 3
2
set_of_values = [0, 1]
3
list_of_permutations = itertools.product(set_of_values, repeat=3)
4
print(*list_of_permutations)
5
# (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1)
6