Tautology, contradiction or neither?

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, not and brackets.
  • Print tautology if it is true for every input, contradiction if it is true for none, and contingent otherwise.
  • 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

Example 1 · Input
A B
A and B
Expected output
contingent 1
Example 2 · Input
A
A or not A
Expected output
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

Lesson: Boolean algebra →