How many rows are true?

The number of true rows tells you how often a condition holds: a formula that is true in all 8 rows is a tautology, and one that is true in none is a contradiction.

What to build

A program that counts the rows of a truth table in which a formula is true.

Requirements

  • Read one formula, a Python expression using the names p, q and r and the operators and, or, not, == and !=.
  • Evaluate it in all 8 rows of p, q and r.
  • Print K of 8, where K is the number of rows in which the formula is true.

Input

One line: the formula.

Output

One line, such as 6 of 8.

Constraints

The formula has at most 60 characters and uses only p, q and r.

Example

Input:

p and q

Output:

2 of 8

Why it works

The truth table has 2 to the power 3 = 8 rows, one for each way to assign T or F to the three letters. Counting the rows where the formula is true is a loop over product with a counter, and letters that do not appear in the formula simply repeat each value.

Examples

Example 1 · Input
p and q
Expected output
2 of 8
Example 2 · Input
(not p) or q
Expected output
6 of 8

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

itertools.product([True, False], repeat=3) gives all 8 rows of p, q and r.

Hint 2

eval(formula, {"p": p, "q": q, "r": r}) evaluates the formula for one row.

Hint 3

A letter that the formula does not use still doubles the number of rows, so always count out of 8.

Solution

Show one correct solution (try it yourself first)
from itertools import product

formula = input()
count = 0
for p, q, r in product([True, False], repeat=3):
    if eval(formula, {"p": p, "q": q, "r": r}):
        count += 1
print(count, "of 8")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Propositions and truth tables →