Some expressions are always true, whatever the inputs: A or not A. Some are always false: A and not A. Most are neither. Algebra can show it, and a truth table always can.
What to build
Decide what kind of expression you were given, and count its true rows.
Requirements
- The expression uses Python syntax: variable names,
and,or,notand brackets. - Print
tautologyif it is true for every input,contradictionif it is true for none, andcontingentotherwise. - Also print how many of the 2ⁿ inputs make it true.
Input
A line with the variable names separated by spaces, then a line with the expression.
Output
One line: the word, a space, then the number of true rows, for example contingent 3.
Constraints
1 to 4 variables.
Example
Input:
A B
A and B
Output:
contingent 1
Why it works
The truth table has 2ⁿ rows and checks every case, so counting the true rows settles the question: all rows true is a tautology, no row true is a contradiction. For example, (A and B) or (not A and B) or (A and not B) or (not A and not B) covers all four combinations, so it is a tautology.
Examples
A B A and B
contingent 1
A A or not A
tautology 2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Try every assignment of the variables with itertools.product([0, 1], repeat=len(names)).
Hint 2
Evaluate the expression with eval(expression, {}, values), where values maps each name to its bit.
Hint 3
Count the assignments that make it true. All of them: a tautology. None: a contradiction.
Solution
Show one correct solution (try it yourself first)
from itertools import product
names = input().split()
expression = input()
rows = list(product([0, 1], repeat=len(names)))
true_rows = sum(1 for bits in rows if eval(expression, {}, dict(zip(names, bits))))
if true_rows == len(rows):
kind = "tautology"
elif true_rows == 0:
kind = "contradiction"
else:
kind = "contingent"
print(kind, true_rows)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step