NAND-NAND form

Any sum of products can be built with two levels of NAND gates. The first level makes the products, and the second level adds them. This is the same as AND-OR, because of De Morgan's law.

What to build

Evaluate a sum of products as a NAND-NAND circuit.

Requirements

  • A term is written with letters, A, B, C, D, …, and a ' after a letter means its complement, for example AB'C.
  • The first level has one NAND gate for each term, which takes the term's literals.
  • The second level has one NAND gate that takes all the first-level outputs.
  • For each query, print the output of the circuit.

Input

The first line has the terms separated by spaces. The second line has the number of queries q. Then q lines, each with the values of A, B, C, … in order (as many values as the largest letter used), separated by spaces.

Output

One line for each query: the output of the circuit, 0 or 1.

Constraints

Use up to 4 variables, 1 to 4 terms, and 1 to 16 queries.

Example

Input:

AB' C
4
1 0 0
1 1 0
0 0 1
0 1 0

Output:

1
0
1
0

Why it works

A NAND gate with all its inputs 1 gives 0, so a first-level gate gives 0 exactly when its term is true. The second-level NAND is 1 as soon as one of its inputs is 0, so it is 1 when at least one term is true. That is the OR of the terms, so NAND-NAND gives the same function as AND-OR while using one kind of gate.

Examples

Example 1 · Input
AB' C
4
1 0 0
1 1 0
0 0 1
0 1 0
Expected output
1
0
1
0
Example 2 · Input
AB CD
3
1 1 0 0
0 0 1 1
1 0 1 0
Expected output
1
1
0

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

Hints

Hint 1

Each product term becomes one NAND gate over its literals. A literal like `B'` is the input B inverted.

Hint 2

The second level is one NAND gate over the outputs of all the first-level gates.

Hint 3

NAND of a list of bits is 1 - all(bits); with no input at all, the NAND is 0, but every term here has at least one literal.

Solution

Show one correct solution (try it yourself first)
terms = input().split()
q = int(input())


def literal(text, i, values):
    letter = text[i]
    value = values[ord(letter) - ord("A")]
    if i + 1 < len(text) and text[i + 1] == "'":
        return 1 - value
    return value


def literals(term, values):
    out = []
    for i, ch in enumerate(term):
        if ch != "'":
            out.append(literal(term, i, values))
    return out


for _ in range(q):
    values = list(map(int, input().split()))
    level1 = [1 - int(all(literals(t, values))) for t in terms]
    print(1 - int(all(level1)))

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

Lesson: NAND and NOR: the universal gates →