NAND is a universal gate: with enough NAND gates you can build NOT, AND, OR and every other gate.
What to build
Build NOT, AND, OR and XOR out of NAND gates only, and print their outputs for pairs of input bits.
Requirements
- Define one function
nand(x, y)and make every other gate by calling it. - For each pair print four numbers on one line: NOT a, a AND b, a OR b and a XOR b.
- Do not use
&,|,^ornotoutside thenandfunction. XOR needs four NAND gates: let m = NAND(a, b); the answer is NAND(NAND(a, m), NAND(b, m)).
Input
The first line has the number of pairs q. Then q lines, each with two bits a and b.
Output
One line for each pair, with four bits.
Constraints
1 ≤ q ≤ 8. a and b are each 0 or 1.
Example
Input:
4
0 0
0 1
1 0
1 1
Output:
1 0 0 0
1 0 1 1
0 0 1 1
0 1 1 0
Why it works
NAND(a, a) is NOT a because both inputs are the same. AND is the opposite of NAND, so inverting a NAND gives AND. For OR, De Morgan says a OR b = (a' AND b')', which is NAND(a', b'). XOR takes the four NANDs shown above. All four come from one kind of gate, which is why a chip can be made from NAND gates alone.
Examples
4 0 0 0 1 1 0 1 1
1 0 0 0 1 0 1 1 0 0 1 1 0 1 1 0
1 1 0
0 0 1 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Write a function nand(a, b) that returns 1 - (a & b) and build the others from it.
Hint 2
NOT a is NAND(a, a). AND is a NAND followed by a NOT. OR is the NAND of the two inverted inputs.
Hint 3
Use no other operator on the bits than nand: that is the exercise.
Solution
Show one correct solution (try it yourself first)
q = int(input())
def nand(x, y):
return 1 - (x & y)
def inv(x):
return nand(x, x)
for _ in range(q):
a, b = map(int, input().split())
m = nand(a, b)
print(inv(a), inv(m), nand(inv(a), inv(b)), nand(nand(a, m), nand(b, m)))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step