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.