The statement you proposed ((T| (F& (T|F))) where | = or, & = and) can be simplified to: T or (F and (T or F))
Now, as @tobias_k said, T and F could be variable names or just abreviations of True and False.
Variable names:
T or (F and (T or F)) == T or F
Abreaviations of True and False:
True or (False and (True or False))
True or (False and True)
True or False
True
You considered them to be 4 different variables: X, Y, P and Q. X or (Y and (P or Q)) is a valid Python expression that will evaluate to True or False depending on the X, Y, P and Q values. There is no recursion to apply. Even if you wanted to get the full truth table you would not need any recursion.
The following function accepts as arguments a dict whose keys are used as column names and whose values are functions that will be called with all the imputs and must return a boolean value, and a second argument with the names of the input variables.
import itertools
def truth_table(f, field_names):
outputs = list(f.keys())
cols = list(field_names) + outputs
format = ""
separator = ""
for width in (len(name) + 2 if len(name) > 5 else 7 for name in cols):
format += "{!s:^" + str(width) + "}|"
separator += ("-" * width) + "+"
format = format[:-1]
separator = separator[:-1]
print(format.format(*cols))
print(separator)
for case in itertools.product((False, True), repeat=len(field_names)):
row = list(case)
for output in outputs:
row.append(f[output](*case))
print(format.format(*row))
You would then call it:
truth_table(
{
"P or Q": lambda x, y, p, q: p or q,
"Y and (P or Q)": lambda x, y, p, q: y and (p or q),
"X or (Y and (P or Q))": lambda x, y, p, q: x or (y and (p or q)),
},
("X", "Y", "P", "Q")
)
Which will output:
X | Y | P | Q | P or Q | Y and (P or Q) | X or (Y and (P or Q))
-------+-------+-------+-------+--------+----------------+-----------------------
False | False | False | False | False | False | False
False | False | False | True | True | False | False
False | False | True | False | True | False | False
False | False | True | True | True | False | False
False | True | False | False | False | False | False
False | True | False | True | True | True | True
False | True | True | False | True | True | True
False | True | True | True | True | True | True
True | False | False | False | False | False | True
True | False | False | True | True | False | True
True | False | True | False | True | False | True
True | False | True | True | True | False | True
True | True | False | False | False | False | True
True | True | False | True | True | True | True
True | True | True | False | True | True | True
True | True | True | True | True | True | True