A circuit is a list of gates, where each gate reads from the circuit's inputs or from gates before it. This is how a netlist works inside a design tool.
What to build
Evaluate a small circuit and print the output of every gate.
Requirements
- The inputs are numbered 0, 1, 2, … in the order they are given. The first gate is numbered after the last input, and so on.
- A gate line is a type and its source numbers:
NOT 0, orAND 0 1. The types are NOT, AND, OR, XOR, NAND, NOR. - Gates only use sources with a smaller number than their own.
Input
The first line has the number of inputs k and the number of gates m. The second line has the k input bits. Then m gate lines.
Output
One line with the output of every gate, in order, separated by spaces.
Constraints
1 ≤ k ≤ 6, 1 ≤ m ≤ 20.
Example
Input:
3 4
1 0 1
AND 0 1
NOT 1
OR 3 4
XOR 5 2
Output:
0 1 1 0
Why it works
Because a gate only uses earlier numbers, one pass from the first gate to the last is enough: when a gate is reached, all its sources already have values. That is the same reason a combinational circuit has no loops.
Examples
3 4 1 0 1 AND 0 1 NOT 1 OR 3 4 XOR 5 2
0 1 1 0
2 3 1 1 NAND 0 1 NOR 0 1 XOR 2 3
0 0 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep a list `values` that starts with the input bits; each gate appends its output, so a gate can use any earlier value by its index.
Hint 2
NOT has one source, the other gates have two. Look at the gate name to know how many.
Hint 3
Print the value of every gate in order, on one line.
Solution
Show one correct solution (try it yourself first)
k, m = map(int, input().split())
values = list(map(int, input().split()))
for _ in range(m):
parts = input().split()
kind = parts[0]
src = [values[int(x)] for x in parts[1:]]
if kind == "NOT":
out = 1 - src[0]
else:
a, b = src
out = {"AND": a & b, "OR": a | b, "XOR": a ^ b, "NAND": 1 - (a & b), "NOR": 1 - (a | b)}[kind]
values.append(out)
print(*values[k:])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step