-4

I'm creating a truth table with Python and I have done so iteratively without any hassle, but I'm trying to figure out how to generate all possible values of True and False, for any number of variable recursively.

Starting with a list like: [[True], [False]]

I need to be able to generate a list like:

[[True, True, True], 
 [True, True, False], 
 [True, False, True], 
 [True, False, False], 
 [False, True, True], 
 [False, True, False], 
 [False, False, True], 
 [False, False, False]] 

where every list is a row in the truth table.

Based on this, you go through and evaluate each row, appending the value of true or false to the end of each list based on the expression being evaluated.

I have already solved the problem iteratively, but doing it recursively doesn't make any sense to me. I've always thought of recursion as starting large and becoming small (reducing toward the base case). Like in merge sort. Not the other way around.

I cannot use anything like itertools.

The hint in the assignment is "Tips: You can use the following recursive algorithm to create all combinations of variables for the truth table:

  • Base case: For a single variable, the list of all combinations is [ [True], [False] ]
  • Recursive case: each element in the list (which is itself a list), is replaced with two lists, one with True appended to it, and one with False appended to it."

The algorithm doesn't make sense to me.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • 1
    So you want to produce all the bit variations for N bits length data? The simplest way is to convert 2^N number to bits and read each bit separately an output True for 1 and False for 0 (or vise versa). – Mika72 Feb 07 '19 at 07:51
  • I assume the algorithm goes like this. You want to create a list of length ```3```. You are given a list of lists ```[[True], [False]]```. From each of the lists ```[True]``` ```[False]``` you create two lists. You will have ```[True, XXX]``` ```[True, XXX]``` ```[False, XXX]``` ```[False, XXX]```. Now, as in the description, you should append once ```True``` and ```False```. So... ```[True, True]``` ```[True, False]``` ```[False, True]``` ```[False, False]```. Rinse and repeat. In the end you should have a list of 8 lists, each containing three elements. – Melon Feb 07 '19 at 07:55

1 Answers1

1

The following recursive implementation will work. Note that you can have an even simpler base case:

def bool_combs(n):
    if not n:
        return [[]]
    result = []
    for comb in bool_combs(n-1):
        result.append(comb + [True])
        result.append(comb + [False])
    return result

>>> bool_combs(1)
[[True], [False]]
>>> bool_combs(2)
[[True, True], [True, False], [False, True], [False, False]]
>>> bool_combs(3)
[[True, True, True], [True, True, False], [True, False, True], [True, False, False], [False, True, True], [False, True, False], [False, False, True], [False, False, False]]
user2390182
  • 72,016
  • 6
  • 67
  • 89