A gate with n inputs has 2ⁿ input combinations. For some gates most combinations give 1, for others only a few.
What to build
Count how many of the 2ⁿ input combinations make a gate's output 1.
Requirements
- The gate is one of
AND,OR,XOR,NAND,NOR,XNOR. - XOR of several bits is 1 when an odd number of them are 1, and XNOR is its opposite.
Input
One line with a gate name and n, separated by a space.
Output
One number: how many of the 2ⁿ input combinations give output 1.
Constraints
1 ≤ n ≤ 6.
Example
Input:
AND 3
Output:
1
Why it works
Going through every row of the truth table and adding up the 1s is exactly what the count means. Checking it by hand for small n shows the pattern: an AND gate has one 1 in its table, an OR gate has all rows but one, and XOR has exactly half.
Examples
AND 3
1
XOR 2
2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Use itertools.product([0, 1], repeat=n) to go through every input combination.
Hint 2
Write each gate as a small function of the list of bits: AND is all(bits), OR is any(bits), XOR is sum(bits) % 2.
Hint 3
NAND, NOR and XNOR are the opposites of AND, OR and XOR.
Solution
Show one correct solution (try it yourself first)
from itertools import product
gate, n = input().split()
n = int(n)
base = {"AND": lambda b: all(b), "OR": lambda b: any(b), "XOR": lambda b: sum(b) % 2 == 1}
name = gate[1:] if gate in ("NAND", "NOR") else ("XOR" if gate == "XNOR" else gate)
invert = gate in ("NAND", "NOR", "XNOR")
count = 0
for bits in product([0, 1], repeat=n):
out = bool(base[name](bits))
if out != invert:
count += 1
print(count)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step