---
title: Logic lab
heading: Truth tables, prime implicants and state machines in Python
eyebrow: C7 · Lesson 51 · Logic lab
xp: 50
---

::: hook
Karnaugh maps work by eye up to four variables; past that, and inside every synthesis tool, logic is minimized by algorithms. The classic one, **Quine–McCluskey**, finds every prime implicant by repeatedly merging terms that differ in one bit, which is exactly what circling neighbors on a map does. In this lab you'll write a truth-table generator, the prime-implicant search, and a simulator that runs a state machine from its table, and check them against the circuits of this course.
:::

::: play
- F is $\sum m(0, 1, 2, 5, 6, 7, 8, 9, 10, 14)$ written out in full. It has six prime implicants; G uses three of them, $\bar B\bar C + C\bar D + \bar ABD$, which together cover every minterm.
- The truth table confirms F and G agree in all 16 rows. Your prime-implicant function will find all six.
:::
:::

```sim logic
input A, B, C, D
output F, G
assign F = ~A&~B&~C&~D | ~A&~B&~C&D | ~A&~B&C&~D | ~A&B&~C&D | ~A&B&C&~D | ~A&B&C&D | A&~B&~C&~D | A&~B&~C&D | A&~B&C&~D | A&B&C&~D
assign G = ~B & ~C | C & ~D | ~A & B & D
table: on
```

::: predict
## Quine–McCluskey writes each term as a pattern of 0, 1 and −. Which two patterns can merge?

- [ ] 0011 and 1100
- [x] 01−1 and 00−1
- [ ] 0−01 and 01−1
- [ ] 1−−0 and 0−1−

::: reveal
01−1 and 00−1: they have their dashes in the same place and differ in exactly one other bit, so they merge into 0−−1. Merging two terms that differ in one variable removes that variable, just like circling two neighboring groups on a map.
:::
:::

::: nameit
## Truth tables in code

Represent an n-input function as a Python function of n bits. Row r (counting from 0) has bit i of r as input i, with the first input as the top bit: `bits = [(r >> (n - 1 - i)) & 1 for i in range(n)]`.

## Quine–McCluskey

1. Write every minterm and don't-care as an n-character string of 0s and 1s.
2. Compare every pair. Two strings **merge** if their dashes are in the same places and they differ in exactly one other position; the merged string has a dash there. Mark both as used.
3. Repeat with the merged strings until no more merges happen. Every string that was never used in a merge is a **prime implicant**.
4. Drop prime implicants that cover only don't-cares.

Choosing the fewest prime implicants that cover all the minterms is a separate step (lesson 14's essential-first method, or a search).

## Running a state machine

A Mealy machine's table maps (state, input) to (next state, output). Simulating it is a loop: look up the current state and input, record the output, and move to the next state.
:::

::: example
## Find the prime implicants of $\sum m(0, 1, 5, 7)$ (three inputs).

::: solution
1. **List the minterms.** 000, 001, 101, 111.
2. **Merge pairs.** 000 + 001 → 00−; 001 + 101 → −01; 101 + 111 → 1−1.
3. **Try to merge again.** None of those merge further (their dashes differ).
4. **Read off the primes.** The primes are 00−, −01 and 1−1: $\bar A\bar B$, $\bar BC$ and AC.

**Answer:** $\bar A\bar B$, $\bar BC$ and AC.
:::
:::

::: example
## Run the Mealy 101 detector (states S0, S1, S2; output 1 on S2 with input 1) on 1, 0, 1, 0, 1, 1, 0, 1.

::: solution
1. **Run the machine.** Starting in S0, each input moves it to the next state with the output shown:

| Input | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 1 |
|---|---|---|---|---|---|---|---|---|
| Next state | S1 | S2 | S1 | S2 | S1 | S1 | S2 | S1 |
| Output | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 |

2. **Compare with Moore.** The outputs, 0, 0, 1, 0, 1, 0, 0, 1, come one cycle earlier than the Moore version would flag them.

**Answer:** the outputs are 0, 0, 1, 0, 1, 0, 0, 1.
:::
:::

::: check
given: v = 4 | 5 | 7; k = 1 | 3
answer: v - k
tolerance: 0

## A pattern in a {v}-variable Quine–McCluskey table has {k} dashes. How many literals does its product term have?

::: right
Right. {answer}.
:::

::: misses
- [k] The dashes are the variables that dropped out.
- [any] Not yet. One literal per 0 or 1.
:::
:::

::: check
given: k = 0 | 1 | 3
answer: 2^k
tolerance: 0

## How many minterms does a pattern with {k} dashes cover?

::: right
Right. $2^k$ = {answer}.
:::

::: misses
- [k] Each dash doubles the coverage.
- [any] Not yet. Each dash can be 0 or 1.
:::
:::

::: check
kind: python

## Write `truth_table(f, n)`: call `f` with a tuple of n bits for each row 0 to $2^n - 1$ (first bit as the top bit) and return the list of outputs as 0s and 1s.

```python starter
def truth_table(f, n):
    return [f((r,)) for r in range(n)]
```

```python solution
def truth_table(f, n):
    out = []
    for r in range(2 ** n):
        bits = tuple((r >> (n - 1 - i)) & 1 for i in range(n))
        out.append(1 if f(bits) else 0)
    return out
```

```python tests
xor3 = lambda b: b[0] ^ b[1] ^ b[2]
assert truth_table(xor3, 3) == [0, 1, 1, 0, 1, 0, 0, 1], f"3-input XOR: got {truth_table(xor3, 3)}."
mux = lambda b: b[1] if b[0] == 0 else b[2]
assert truth_table(mux, 3) == [0, 0, 1, 1, 0, 1, 0, 1], f"A 2:1 mux selected by the first input: got {truth_table(mux, 3)}."
g = lambda b: (not b[1] and not b[2]) or (b[2] and not b[3]) or (not b[0] and b[1] and b[3])
assert [r for r, v in enumerate(truth_table(g, 4)) if v] == [0, 1, 2, 5, 6, 7, 8, 9, 10, 14], "The lab's G should give minterms 0, 1, 2, 5, 6, 7, 8, 9, 10, 14."
```

::: right
Right. With this you can check any hand simplification against the original function in one line.
:::
:::

::: check
kind: python

## Write `prime_implicants(minterms, n, dontcares=())`: the Quine–McCluskey prime implicants as a sorted list of strings of 0, 1 and -, leaving out any that cover only don't-cares.

```python starter
def prime_implicants(minterms, n, dontcares=()):
    return sorted(format(m, f"0{n}b") for m in minterms)
```

```python solution
from itertools import combinations

def prime_implicants(minterms, n, dontcares=()):
    terms = {format(m, f"0{n}b") for m in list(minterms) + list(dontcares)}
    primes = set()
    while terms:
        merged, used = set(), set()
        for a, b in combinations(sorted(terms), 2):
            diff = [i for i in range(n) if a[i] != b[i]]
            if len(diff) == 1 and "-" not in (a[diff[0]], b[diff[0]]):
                i = diff[0]
                merged.add(a[:i] + "-" + a[i + 1:])
                used |= {a, b}
        primes |= terms - used
        terms = merged
    def covers(p, m):
        return all(c == "-" or c == b for c, b in zip(p, format(m, f"0{n}b")))
    return sorted(p for p in primes if any(covers(p, m) for m in minterms))
```

```python tests
cases = [(([0, 2, 5, 7, 8, 10, 13, 15], 4, ()), ["-0-0", "-1-1"]),
         (([1, 3, 7, 11, 15], 4, (0, 2, 5)), ["--11", "0--1", "00--"]),
         (([0, 1, 5, 7], 3, ()), ["-01", "00-", "1-1"]),
         (([0, 1, 2, 5, 6, 7, 8, 9, 10, 14], 4, ()), ["--10", "-0-0", "-00-", "0-01", "01-1", "011-"]),
         (([4, 5, 6, 7, 8, 9], 4, (10, 11, 12, 13, 14, 15)), ["-1--", "1---"])]
for (m, n, d), want in cases:
    got = prime_implicants(m, n, d)
    assert got == want, f"For minterms {m} with don't-cares {list(d)}: expected {want}, got {got}."
```

::: right
Right. The last case is the BCD "5 or more" circuit: with don't-cares, the primes are just B (−1−−) and A (1−−−).
:::
:::

::: check
kind: python

## Write `run_mealy(table, start, xs)`: `table` maps `(state, x)` to `(next_state, output)`. Starting in `start`, return the list of outputs for the inputs `xs`.

```python starter
def run_mealy(table, start, xs):
    return [table[(start, x)][1] for x in xs]
```

```python solution
def run_mealy(table, start, xs):
    state, out = start, []
    for x in xs:
        state, o = table[(state, x)]
        out.append(o)
    return out
```

```python tests
det = {("S0", 0): ("S0", 0), ("S0", 1): ("S1", 0),
       ("S1", 0): ("S2", 0), ("S1", 1): ("S1", 0),
       ("S2", 0): ("S0", 0), ("S2", 1): ("S1", 1)}
got = run_mealy(det, "S0", [1, 0, 1, 0, 1, 1, 0, 1])
assert got == [0, 0, 1, 0, 1, 0, 0, 1], f"The 101 detector should flag positions 3, 5 and 8; got {got}."
par = {(0, 0): (0, 0), (0, 1): (1, 1), (1, 0): (1, 1), (1, 1): (0, 0)}
assert run_mealy(par, 0, [1, 1, 0, 1, 0]) == [1, 0, 0, 1, 1], "A running-parity machine outputs the parity so far."
```

::: right
Right. The starter never left the start state, so it only noticed patterns that begin in S0.
:::
:::

::: explain
## Why do the prime implicants found by merging pairs match the groups you'd circle on a Karnaugh map?

::: model
Two minterms are neighbors on a Karnaugh map exactly when their binary codes differ in one bit, and circling them removes that variable. Quine–McCluskey's merge rule is the same test: two patterns combine when they differ in one position, and the merged pattern puts a dash, a removed variable, there. Merging merged patterns builds groups of 4, 8 and so on, the same rectangles the map shows. A pattern that never merges with anything is a group that can't be doubled, which is the definition of a prime implicant. The algorithm just does the circling systematically, for any number of variables.
:::
:::

::: practice

::: check
given: n = 3 | 4 | 6
answer: 2^n
tolerance: 0

## How many rows does `truth_table` produce for {n} inputs?

::: misses
- [any] $2^n$.
:::
:::

::: check
given: r = 5 | 9 | 14
answer: floor(r/8) - 2*floor(r/16)
tolerance: 0

## In a 4-input table, what is the first input's bit in row {r}?

::: misses
- [any] The top bit of {r} written in 4 bits.
:::
:::

::: check
given: k = 1..6 int
answer: 2^k
tolerance: 0

## How many minterms does a pattern with {k} dashes merge together?

::: misses
- [any] $2^k$.
:::
:::
:::
