---
title: "Logic Gates and Boolean Algebra"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 32
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/32-logic-gates-and-boolean-algebra
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 32 — Logic Gates and Boolean Algebra

A lift moves only if its door is closed *and* a floor button has been pressed. A hall light comes on if this switch *or* the one at the other end of the hall is on. Inside a [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer), billions of tiny parts make such decisions on [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), billions of times a second. This chapter builds them, from the smallest one to a circuit that adds.

**You already know.**

A [Boolean value](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) is `True` or `False`; `and`, `or` and `not` combine them, and a table of the four cases shows the result of `and` and `or` ([Chapter 17](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#ch-g6-if-else)). Two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) are added column by column, with a [carry](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#def-g8-binary-and-hexadecimal-carry); $n$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) make $2^n$ patterns ([Chapter 25](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#ch-g8-binary-and-hexadecimal)).

## 32.1 True and false as 1 and 0

A [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) has two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), like a [Boolean value](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison): 1 can stand for true and 0 for false. Python itself counts `True` as 1 and `False` as 0:

```python
print(True + True, True * 5, int(False))
print(1 == 1, (3 > 5) or True)
```

***Listing 32.1.** Booleans are numbers. code/grade-9/02-logic-gates/listings/bits.py*

```
$ python bits.py
2 5 0
True True
```

***Output 32.1.** `True + True` is 2.*

In this chapter, every [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) is a [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), 0 or 1, and the operations are written in capitals, NOT, AND, OR, to keep them apart from Python’s words.

## 32.2 Gates and their truth tables

**Definition 32.1 (Logic gate, truth table).**

A *logic gate* is a small circuit that takes one or two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) as [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) and gives one [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) as [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input). Its *truth table* [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) for every possible [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input).

**Definition 32.2 (NOT, AND, OR and XOR gates).**

The *NOT gate* gives 1 when its [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 0, and 0 when it is 1. The *AND gate* gives 1 only when both [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) are 1. The *OR gate* gives 1 when at least one [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1. The *XOR gate* (for *exclusive or*) gives 1 when exactly one [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1.

With [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), each gate is a little arithmetic: AND is a product, NOT is $1 - a$, XOR is the remainder of $a + b$ divided by 2.

```python
def NOT(a):
    return 1 - a


def AND(a, b):
    return a * b


def OR(a, b):
    return a + b - a * b


def XOR(a, b):
    return (a + b) % 2


if __name__ == "__main__":
    print("a b | AND OR XOR")
    for a in [0, 1]:
        for b in [0, 1]:
            print(f"{a} {b} |  {AND(a, b)}   {OR(a, b)}   {XOR(a, b)}")
    print("NOT 0 =", NOT(0), " NOT 1 =", NOT(1))
```

***Listing 32.2.** The four gates as [functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function), and their tables. code/grade-9/02-logic-gates/listings/gates.py*

```
$ python gates.py
a b | AND OR XOR
0 0 |  0   0   0
0 1 |  0   1   1
1 0 |  0   1   1
1 1 |  1   1   0
NOT 0 = 1  NOT 1 = 0
```

***Output 32.2.** The [truth tables](#def-g9-logic-gates-gate) of the four gates.*

![The symbols of the NOT, AND, OR and XOR gates, each with its truth table. The inputs come in on the left, the output leaves on the right; NOT’s small circle means “the opposite”.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-logic-gates/fig-ccf556a6c32c.svg)

*The symbols of the NOT, AND, OR and [XOR gates](#def-g9-logic-gates-not-and-or-xor), each with its [truth table](#def-g9-logic-gates-gate). The [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) come in on the left, the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) leaves on the right; NOT’s small circle means “the opposite”.*

## 32.3 Circuits of gates

**Definition 32.3 (Logic circuit).**

A *logic circuit* is a set of gates wired together, the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) of one gate feeding an [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) of another. Its [truth table](#def-g9-logic-gates-gate) gives its [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) for each of the $2^n$ patterns of its $n$ [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input).

The circuit below computes `(a AND b) OR (NOT c)`. Three [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) make $2^3 = 8$ rows, and three [nested loops](https://one-course.com/books/computer-science/1/en/chapter/16-repeating-with-for-turtle-drawings#def-g6-for-loops-turtle-nested) go through them in the order of counting in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), from `0 0 0` to `1 1 1`:

```python
from gates import AND, NOT, OR


def circuit(a, b, c):
    """(a AND b) OR (NOT c)"""
    return OR(AND(a, b), NOT(c))


print("a b c | out")
for a in [0, 1]:
    for b in [0, 1]:
        for c in [0, 1]:
            print(a, b, c, "|", circuit(a, b, c))
```

***Listing 32.3.** The [truth table](#def-g9-logic-gates-gate) of a circuit with three [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input). code/grade-9/02-logic-gates/listings/circuit.py*

```
$ python circuit.py
a b c | out
0 0 0 | 1
0 0 1 | 0
0 1 0 | 1
0 1 1 | 0
1 0 0 | 1
1 0 1 | 0
1 1 0 | 1
1 1 1 | 1
```

***Output 32.3.** 8 rows, one per pattern of three [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

![The circuit (a AND b) OR (NOT c): two gates feed a third. Its table is the output of .](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-logic-gates/fig-e2721136f723.svg)

*The circuit `(a AND b) OR (NOT c)`: two gates feed a third. Its table is the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) of [Listing 32.3](#lst-g9-logic-gates-circuit).*

Two different circuits can compute the same thing. To be sure, compare them on every [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input): with two [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) there are only four.

```python
from gates import AND, NOT, OR


def first(a, b):
    return NOT(AND(a, b))


def second(a, b):
    return OR(NOT(a), NOT(b))


agree = True
for a in [0, 1]:
    for b in [0, 1]:
        print(a, b, first(a, b), second(a, b))
        if first(a, b) != second(a, b):
            agree = False
print("the same on every input:", agree)
```

***Listing 32.4.** Two circuits compared on every [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input). code/grade-9/02-logic-gates/listings/same_circuit.py*

```
$ python same_circuit.py
0 0 1 1
0 1 1 1
1 0 1 1
1 1 0 0
the same on every input: True
```

***Output 32.4.** Always the same [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input).*

## 32.4 Rules of Boolean algebra

In 1854, the English mathematician George Boole published a book that treated reasoning as a kind of algebra, with letters for true and false statements. The rules of that algebra, now called Boolean, hold for gates:

| NOT (NOT $a$) $= a$ |  |
| --- | --- |
| $a$ AND 1 $= a$ | $a$ OR 0 $= a$ |
| $a$ AND 0 $= 0$ | $a$ OR 1 $= 1$ |
| $a$ AND $a = a$ | $a$ OR $a = a$ |
| $a$ AND (NOT $a$) $= 0$ | $a$ OR (NOT $a$) $= 1$ |

Each rule is checked by trying both [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of $a$. For instance, $a$ OR 1: if $a = 0$, then $0$ OR $1 = 1$; if $a = 1$, then $1$ OR $1 = 1$.

**Proposition 32.4 (De Morgan’s laws for gates).**

For any [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) $a$ and $b$, NOT ($a$ AND $b$) $=$ (NOT $a$) OR (NOT $b$), and NOT ($a$ OR $b$) $=$ (NOT $a$) AND (NOT $b$).

**Proof.** Two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) have only four patterns. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) below computes both sides of each law for all four, and the two columns of each law are equal on every row. ∎

```python
from gates import AND, NOT, OR

print("a b | NOT(a AND b)  (NOT a) OR (NOT b) | NOT(a OR b)  (NOT a) AND (NOT b)")
for a in [0, 1]:
    for b in [0, 1]:
        left = f"{NOT(AND(a, b)):^12}  {OR(NOT(a), NOT(b)):^18}"
        right = f"{NOT(OR(a, b)):^11}  {AND(NOT(a), NOT(b)):^19}"
        print(f"{a} {b} | {left} | {right}".rstrip())
```

***Listing 32.5.** Both sides of De Morgan’s laws. code/grade-9/02-logic-gates/listings/de_morgan.py*

```
$ python de_morgan.py
a b | NOT(a AND b)  (NOT a) OR (NOT b) | NOT(a OR b)  (NOT a) AND (NOT b)
0 0 |      1                1          |      1                1
0 1 |      1                1          |      0                0
1 0 |      1                1          |      0                0
1 1 |      0                0          |      0                0
```

***Output 32.5.** Equal columns, row by row.*

In words: “not both” is “one of them is not”, and “neither” is “this one is not, and that one is not”. The circuits of [Listing 32.4](#lst-g9-logic-gates-same) were the first law.

## 32.5 The half adder; the transistor as a switch

**Definition 32.5 (Half adder).**

A *half adder* is a circuit that adds two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). It has two [outputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input): the *sum* [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), $a$ XOR $b$, and the *[carry](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#def-g8-binary-and-hexadecimal-carry)* [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), $a$ AND $b$.

$1 + 1 = 2$, written `10` in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary): a sum [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) 0 and a [carry](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#def-g8-binary-and-hexadecimal-carry) 1, as in the column additions of [Chapter 25](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#ch-g8-binary-and-hexadecimal).

```python
from gates import AND, XOR


def half_adder(a, b):
    """Add two bits: the sum bit and the carry bit."""
    return XOR(a, b), AND(a, b)


print("a + b = carry sum")
for a in [0, 1]:
    for b in [0, 1]:
        total, carry = half_adder(a, b)
        print(a, "+", b, "=", carry, total)
```

***Listing 32.6.** The [half adder](#def-g9-logic-gates-half-adder): two gates. code/grade-9/02-logic-gates/listings/half_adder.py*

```
$ python half_adder.py
a + b = carry sum
0 + 0 = 0 0
0 + 1 = 0 1
1 + 0 = 0 1
1 + 1 = 1 0
```

***Output 32.6.** The four sums of two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) returns two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value); `total, carry = half_adder(a, b)` puts the first in `total` and the second in `carry`.

![The half adder: an XOR gate and an AND gate share the same two inputs.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-logic-gates/fig-3c1740ac1329.svg)

*The [half adder](#def-g9-logic-gates-half-adder): an [XOR gate](#def-g9-logic-gates-not-and-or-xor) and an [AND gate](#def-g9-logic-gates-not-and-or-xor) share the same two [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input).*

Every addition a [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) makes is built from such circuits, chained column after column; the next book builds them. And what is a gate made of? Of *transistors*: tiny switches that are opened and closed by electricity instead of a finger. The physics books explain electric circuits and their switches; here, only one fact matters. Two switches in a row, in *series*, let the current through only if both are closed: AND. Two switches side by side, in *parallel*, let it through if either is closed: OR.

![A battery, two switches and a lamp. In series, the lamp lights only if a and b are both closed; in parallel, it lights if a or b is closed.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-logic-gates/fig-07fd5b965fd6.svg)

*A battery, two switches and a lamp. In series, the lamp lights only if $a$ and $b$ are both closed; in parallel, it lights if $a$ or $b$ is closed.*

**History — From switches to logic.**

A young engineer, Claude Shannon, showed in a thesis written in 1937, and published in 1938, that circuits of switches compute exactly Boole’s algebra, so that logic can be built with electricity. In December 1947, John Bardeen and Walter Brattain made the first transistor work, at Bell Labs, the laboratory of an American telephone company: a small slab of germanium with two gold contacts, which made a weak signal up to a hundred times stronger.

![A replica of the first transistor of 1947, made for its fiftieth anniversary: the triangle of plastic presses two gold contacts onto the germanium below.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-logic-gates/img-2f255e9c9624.jpg)

*A replica of the first transistor of 1947, made for its fiftieth anniversary: the triangle of plastic presses two gold contacts onto the germanium below.*

## 32.6 Exercises

**Exercise 32.1 ★.**

A circuit is an [OR gate](#def-g9-logic-gates-not-and-or-xor) followed by a [NOT gate](#def-g9-logic-gates-not-and-or-xor). What does it [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) for $a = 1$, $b = 0$? And for $a = 0$, $b = 0$?

**Solution of Exercise 32.1.**

For $a = 1$, $b = 0$: the OR gives 1, the NOT turns it into 0. For $a = 0$, $b = 0$: the OR gives 0, and the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1. The circuit [outputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) 1 only when neither [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1.

**Exercise 32.2 ★.**

Write the [truth table](#def-g9-logic-gates-gate) of XOR without looking, and say in words when its [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1.

**Solution of Exercise 32.2.**

`0 0 | 0`, `0 1 | 1`, `1 0 | 1`, `1 1 | 0`: the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1 when the two [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) are different.

**Exercise 32.3 ★.**

NAND is “NOT AND”. Read the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) below and write what it prints.

```python
def NAND(a, b):
    return 1 - a * b


def NOT(a):
    return NAND(a, a)


def AND(a, b):
    return NOT(NAND(a, b))


def OR(a, b):
    return NAND(NOT(a), NOT(b))


for a in [0, 1]:
    for b in [0, 1]:
        print(a, b, "| NAND", NAND(a, b), " AND", AND(a, b), " OR", OR(a, b),
              " NOT a", NOT(a))
```

***Listing 32.7.** NOT, AND and OR from NAND alone. code/grade-9/02-logic-gates/listings/nand_only.py*

**Solution of Exercise 32.3.**

```
$ python nand_only.py
0 0 | NAND 1  AND 0  OR 0  NOT a 1
0 1 | NAND 1  AND 0  OR 1  NOT a 1
1 0 | NAND 1  AND 0  OR 1  NOT a 0
1 1 | NAND 0  AND 1  OR 1  NOT a 0
```

***Output 32.7.** NAND, and the three gates built from it.*

The AND and OR columns are those of the real gates, and NOT $a$ is the opposite of $a$.

**Exercise 32.4 ★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `exactly_one(a, b, c)` that returns 1 when exactly one of its three [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) is 1.

**Solution of Exercise 32.4.**

With [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), “exactly one is 1” means “their sum is 1”:

```python
def exactly_one(a, b, c):
    """1 when exactly one of the three bits is 1."""
    return int(a + b + c == 1)
```

*Exactly one of three. code/grade-9/02-logic-gates/exercises/exactly_one.py*

**Exercise 32.5 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) should print the [truth table](#def-g9-logic-gates-gate) of AND. It prints one row only. Why? Fix it.

```python
for a in range(1):
    for b in range(1):
        print(a, b, a * b)
```

***Listing 32.8.** A table with missing rows. code/grade-9/02-logic-gates/exercises/table_bug.py*

**Solution of Exercise 32.5.**

`range(1)` holds only 0, so both [loops](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) make a single turn and print `0 0 0`. With `range(2)`, or `[0, 1]`, they print the four rows.

**Exercise 32.6 ★★.**

Someone draws a [half adder](#def-g9-logic-gates-half-adder) with an [OR gate](#def-g9-logic-gates-not-and-or-xor) for the sum [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) instead of XOR. Which [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) gives a wrong answer, and what does the circuit then claim?

**Solution of Exercise 32.6.**

The [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) $a = 1$, $b = 1$: OR gives a sum [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) 1, and the [carry](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#def-g8-binary-and-hexadecimal-carry) is 1, so the circuit claims that $1 + 1$ is `11` in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), which is 3.

**Exercise 32.7 ★★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that prints the [truth table](#def-g9-logic-gates-gate) of `(a OR b) AND (NOT c)`.

**Solution of Exercise 32.7.**

Saved next to `gates.py` ([Listing 32.2](#lst-g9-logic-gates-gates)), the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) imports the three gates it needs:

```python
from gates import AND, NOT, OR

for a in [0, 1]:
    for b in [0, 1]:
        for c in [0, 1]:
            print(a, b, c, "|", AND(OR(a, b), NOT(c)))
```

*The table of `(a OR b) AND (NOT c)`. code/grade-9/02-logic-gates/exercises/table_or_not.py*

The [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1 on three rows only: `0 1 0`, `1 0 0` and `1 1 0`; at least one of $a$ and $b$ is 1, and $c$ is 0.

**Exercise 32.8 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `agree(f, g)` that tells whether two [functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) of two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) give the same [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) on every [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input).

**Solution of Exercise 32.8.**

[Functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) can be passed as arguments, like the sort key of [Chapter 30](https://one-course.com/books/computer-science/1/en/chapter/30-project-a-data-explorer#ch-g8-project-data-explorer):

```python
def agree(f, g):
    """True when the two-input functions f and g give the same bit on every input."""
    for a in [0, 1]:
        for b in [0, 1]:
            if f(a, b) != g(a, b):
                return False
    return True
```

*Two circuits compared on every [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input). code/grade-9/02-logic-gates/exercises/agree.py*

**Exercise 32.9 ★★.**

How many rows does the [truth table](#def-g9-logic-gates-gate) of a circuit with 5 [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) have? And with 10?

**Solution of Exercise 32.9.**

$2^5 = 32$ rows, and $2^{10} = 1{,}024$ with 10 [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input).

**Exercise 32.10 ★★★.**

Prove with a [truth table](#def-g9-logic-gates-gate) that $a$ OR ($a$ AND $b$) $= a$ for all [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) $a$ and $b$. Then explain the rule in words.

**Solution of Exercise 32.10.**

`0 0`: $a$ AND $b$ is 0, the OR is 0. `0 1`: 0, then 0. `1 0`: 0, then 1. `1 1`: 1, then 1. The last column, 0, 0, 1, 1, is the column of $a$. In words: if $a$ is 1, the OR is 1 anyway; if $a$ is 0, then $a$ AND $b$ is 0 too, and the OR is 0.

**Exercise 32.11 ★★★.**

A [truth table](#def-g9-logic-gates-gate) with two [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) has four rows, each with an [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) of 0 or 1. How many different such tables are there? Show that each of them can be built with NAND gates only.

**Solution of Exercise 32.11.**

Each of the four rows has 2 possible [outputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input): $2^4 = 16$ tables. [Listing 32.7](#lst-g9-logic-gates-nand) builds NOT, AND and OR from NAND. Now take any table. For each row whose [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 1, an AND of the [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input), or of their NOT, gives 1 on that row only: for the row $a = 1$, $b = 0$, it is $a$ AND (NOT $b$). The OR of these pieces gives 1 exactly on the rows wanted. If no row has [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) 1, $a$ AND (NOT $a$) is always 0. So every table is a circuit of NOT, AND and OR, and therefore of NAND alone. A test of the chapter also builds all 16 by combining NAND gates.

**Exercise 32.12 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `add_two_bits(a1, a0, b1, b0)` that adds two numbers of two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) each, $a_1a_0$ and $b_1b_0$, using [half adders](#def-g9-logic-gates-half-adder) and one [OR gate](#def-g9-logic-gates-not-and-or-xor). It returns three [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). Check it on all 16 [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input).

**Solution of Exercise 32.12.**

A [half adder](#def-g9-logic-gates-half-adder) adds the units; a second one adds the twos; a third adds the [carry](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#def-g8-binary-and-hexadecimal-carry) of the units to that. The two carries can never both be 1, so an OR gives the last [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). The [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) sits next to `gates.py`:

```python
from gates import AND, OR, XOR


def half_adder(a, b):
    return XOR(a, b), AND(a, b)


def add_two_bits(a1, a0, b1, b0):
    """Add the two-bit numbers a1a0 and b1b0: three bits, carry first."""
    s0, c0 = half_adder(a0, b0)          # the units column
    t, c1 = half_adder(a1, b1)           # the twos column, without the carry
    s1, c2 = half_adder(t, c0)           # ... then with the carry
    return OR(c1, c2), s1, s0
```

*Adding two numbers of two [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). code/grade-9/02-logic-gates/exercises/two_bit_adder.py*

A test of the chapter checks $4 \times \text{carry} + 2 s_1 + s_0 = x + y$ for all 16 pairs of numbers from 0 to 3.

## 32.7 Problem: Three Judges and a Buzzer

**Problem 32.1.**

Weekend problem — three judges and a buzzer

In a talent show, three judges each have a button. The buzzer sounds when at least two of the three judges press.

**Part I — By hand.**

1. Write the [truth table](#def-g9-logic-gates-gate) : 8 rows, with the [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) $a$ , $b$ , $c$ (1 for a pressed button) and the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) (1 for the buzzer).
2. In which rows does the buzzer sound? What do they have in common?
3. Why do 8 rows cover every case?

**Part II — Two circuits.**

```python
from gates import AND, OR


def spec(a, b, c):
    """The rule itself: at least two of the three judges press."""
    return int(a + b + c >= 2)


def pairs(a, b, c):
    """Any pair of judges pressing: (a AND b) OR (b AND c) OR (a AND c)."""
    return OR(OR(AND(a, b), AND(b, c)), AND(a, c))


def majority(a, b, c):
    """Another idea: a and b agree, or else c decides."""
    return OR(AND(a, b), AND(c, OR(a, b)))


print("a b c | spec pairs majority")
ok = True
for a in [0, 1]:
    for b in [0, 1]:
        for c in [0, 1]:
            row = [spec(a, b, c), pairs(a, b, c), majority(a, b, c)]
            print(a, b, c, "|", row[0], "   ", row[1], "    ", row[2])
            if row[0] != row[1] or row[0] != row[2]:
                ok = False
print("all three agree on the 8 inputs:", ok)
print("rows for five judges:", 2**5)
```

***Listing 32.9.** The rule, and two circuits for it. code/grade-9/02-logic-gates/listings/judges.py*

4. Explain the idea of `pairs` .
5. Explain the idea of `majority` : what happens when $a$ and $b$ agree, and when they do not?
6. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . Do the two circuits agree with the rule on all 8 [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) ?
7. Why does comparing them on 8 [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) prove that they are right, and not just likely to be right?

**Part III — Counting.**

8. How many [two-input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) gates does `pairs` use? And `majority` ?
9. Draw the circuit of `pairs` .
10. With five judges and “at least three”, how many rows does the [truth table](#def-g9-logic-gates-gate) have?
11. Which circuit would you build, and why?
12. State the result.

**Solution of Problem 32.1.**

**1.** The rule’s column of the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program)’s [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) below.

**2.** `0 1 1`, `1 0 1`, `1 1 0` and `1 1 1`: the rows with at least two 1s.

**3.** Each judge presses or not, 2 choices each: $2^3 = 8$ patterns.

**4.** If at least two judges press, some pair of judges both press, and that pair’s AND gives 1; if at most one presses, no pair does.

**5.** If $a$ and $b$ both press, $a$ AND $b$ makes the buzzer sound. If neither presses, at most one judge pressed, and $a$ OR $b$ is 0, so the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) is 0. If they disagree, there is exactly one press already, and $c$ decides: $c$ AND ($a$ OR $b$) is $c$.

**6.** Yes:

```
$ python judges.py
a b c | spec pairs majority
0 0 0 | 0     0      0
0 0 1 | 0     0      0
0 1 0 | 0     0      0
0 1 1 | 1     1      1
1 0 0 | 0     0      0
1 0 1 | 1     1      1
1 1 0 | 1     1      1
1 1 1 | 1     1      1
all three agree on the 8 inputs: True
rows for five judges: 32
```

***Output 32.8.** The rule and the two circuits.*

**7.** The 8 [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) are all the [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) there are: agreeing on each of them is agreeing everywhere, not on a sample.

**8.** `pairs`: three ANDs and two ORs, 5 gates. `majority`: two ANDs and two ORs, 4 gates.

**9.** Three [AND gates](#def-g9-logic-gates-not-and-or-xor), one per pair ($a b$, $b c$, $a c$); an OR joins the first two, and a second OR joins that with the third.

**10.** $2^5 = 32$ rows.

**11.** `majority` saves a gate; `pairs` is easier to check by reading. Both are proved right by the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program).

**12.** **Result.** “At least two of three” is ($a$ AND $b$) OR ($b$ AND $c$) OR ($a$ AND $c$): five [two-input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) gates, and the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) checks it, against the rule, on all 8 [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input); a circuit of four gates does the same. Five judges need a [truth table](#def-g9-logic-gates-gate) of 32 rows.
