0

How do i iterate through all possible X boolean values? i.e i have 2 booleans, how do i make a table with all truths and falses?

like:

  • A 0 0 1 1
  • B 0 1 0 1
timrau
  • 22,578
  • 4
  • 51
  • 64
Python User
  • 17
  • 1
  • 8
  • what format is the data in? what does "table" mean for you? where do you get this data from? you provide absolutely no info regarding this. – Bijay Regmi Nov 07 '22 at 18:29
  • Does this answer your question? [How to get all subsets of a set? (powerset)](https://stackoverflow.com/questions/1482308/how-to-get-all-subsets-of-a-set-powerset) – timrau Nov 07 '22 at 18:31
  • @BijayRegmi lets just say i need a list of tuples formatted like [(0,0,0),(0,0,1),(0,1,0)...] and so on. answer on timrau's suggestion also includes nulls i do not need. – Python User Nov 07 '22 at 18:55

1 Answers1

1

Try to iterate over the 2 ** number of variables integers. The following example for 4 variables:

variables = ['A', 'B', 'C', 'D']                                                                                                                                                                                                                              
lv = len(variables)

print(''.join(variables))
print('=' * lv)
for i in range(2**lv):
    print(f"{i:0{lv}b}")

will produce the following:

ABCD
====
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Alberto Garcia
  • 324
  • 1
  • 11
  • thanks! a quick question: does {i:0{lv}b} format the number to be binary? – Python User Nov 07 '22 at 19:20
  • @PythonUser - the `b` in `{i:0{lv}b}` is what makes the `int` to print in binary. The whole `{i:0{lv}b}` means "print `i` in binary format with `lv` digits, and fill with `0s` if `i` can be represented with less digits than `lv`" – Alberto Garcia Nov 07 '22 at 19:24