এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
Primary & Middle School Computer Science · শ্রেণি 1–9
32Logic 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, billions of tiny parts make such decisions on bits, billions of times a second. This chapter builds them, from the smallest one to a circuit that adds.
You already know
A Boolean value 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). Two bits are added column by column, with a carry; bits make patterns (Chapter 25).
32.1 True and false as 1 and 0
A bit has two values, like a Boolean value: 1 can stand for true and 0 for false. Python itself counts True as 1 and False as 0:
print(True + True, True * 5, int(False))
print(1 == 1, (3 > 5) or True)
$ python bits.py
2 5 0
True True
True + True is 2.In this chapter, every value is a 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 as inputs and gives one bit as output. Its truth table lists the output for every possible input.
Definition 32.2 (NOT, AND, OR and XOR gates)
The NOT gate gives 1 when its input is 0, and 0 when it is 1. The AND gate gives 1 only when both inputs are 1. The OR gate gives 1 when at least one input is 1. The XOR gate (for exclusive or) gives 1 when exactly one input is 1.
With bits, each gate is a little arithmetic: AND is a product, NOT is , XOR is the remainder of divided by 2.
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))
$ 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
32.3 Circuits of gates
Definition 32.3 (Logic circuit)
A logic circuit is a set of gates wired together, the output of one gate feeding an input of another. Its truth table gives its output for each of the patterns of its inputs.
The circuit below computes (a AND b) OR (NOT c). Three inputs make rows, and three nested loops go through them in the order of counting in binary, from 0 0 0 to 1 1 1:
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))
$ 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
(a AND b) OR (NOT c): two gates feed a third. Its table is the output of Listing 32.3.Two different circuits can compute the same thing. To be sure, compare them on every input: with two inputs there are only four.
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)
$ 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
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 ) | |
| AND 1 | OR 0 |
| AND 0 | OR 1 |
| AND | OR |
| AND (NOT ) | OR (NOT ) |
Each rule is checked by trying both values of . For instance, OR 1: if , then OR ; if , then OR .
Proposition 32.4 (De Morgan’s laws for gates)
For any bits and , NOT ( AND ) (NOT ) OR (NOT ), and NOT ( OR ) (NOT ) AND (NOT ).
Proof. Two bits have only four patterns. The program below computes both sides of each law for all four, and the two columns of each law are equal on every row. ∎
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())
$ 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
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 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. It has two outputs: the sum bit, XOR , and the carry bit, AND .
, written 10 in binary: a sum bit 0 and a carry 1, as in the column additions of Chapter 25.
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)
$ python half_adder.py
a + b = carry sum
0 + 0 = 0 0
0 + 1 = 0 1
1 + 0 = 0 1
1 + 1 = 1 0
The function returns two values; total, carry = half_adder(a, b) puts the first in total and the second in carry.
Every addition a 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.
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.
32.6 Exercises
Exercise 32.1 ★
A circuit is an OR gate followed by a NOT gate. What does it output for , ? And for , ?
Exercise 32.2 ★
Write the truth table of XOR without looking, and say in words when its output is 1.
Exercise 32.3 ★
NAND is “NOT AND”. Read the program below and write what it prints.
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))
Solution
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
The AND and OR columns are those of the real gates, and NOT is the opposite of .
Exercise 32.4 ★
Write a function exactly_one(a, b, c) that returns 1 when exactly one of its three bits is 1.
Solution
Solution of Exercise 32.4.
With bits, “exactly one is 1” means “their sum is 1”:
def exactly_one(a, b, c):
"""1 when exactly one of the three bits is 1."""
return int(a + b + c == 1)
Exercise 32.5 ★★
This program should print the truth table of AND. It prints one row only. Why? Fix it.
for a in range(1):
for b in range(1):
print(a, b, a * b)
Solution
Solution of Exercise 32.5.
range(1) holds only 0, so both loops 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 with an OR gate for the sum bit instead of XOR. Which input gives a wrong answer, and what does the circuit then claim?
Exercise 32.7 ★★
Write a program that prints the truth table of (a OR b) AND (NOT c).
Solution
Solution of Exercise 32.7.
Saved next to gates.py (Listing 32.2), the program imports the three gates it needs:
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)))
(a OR b) AND (NOT c). code/grade-9/02-logic-gates/exercises/table_or_not.pyThe output is 1 on three rows only: 0 1 0, 1 0 0 and 1 1 0; at least one of and is 1, and is 0.
Exercise 32.8 ★★
Write a function agree(f, g) that tells whether two functions of two bits give the same output on every input.
Solution
Solution of Exercise 32.8.
Functions can be passed as arguments, like the sort key of Chapter 30:
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
Exercise 32.9 ★★
How many rows does the truth table of a circuit with 5 inputs have? And with 10?
Exercise 32.10 ★★★
Prove with a truth table that OR ( AND ) for all bits and . Then explain the rule in words.
Solution
Solution of Exercise 32.10.
0 0: AND 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 . In words: if is 1, the OR is 1 anyway; if is 0, then AND is 0 too, and the OR is 0.
Exercise 32.11 ★★★
A truth table with two inputs has four rows, each with an output of 0 or 1. How many different such tables are there? Show that each of them can be built with NAND gates only.
Solution
Solution of Exercise 32.11.
Each of the four rows has 2 possible outputs: tables. Listing 32.7 builds NOT, AND and OR from NAND. Now take any table. For each row whose output is 1, an AND of the inputs, or of their NOT, gives 1 on that row only: for the row , , it is AND (NOT ). The OR of these pieces gives 1 exactly on the rows wanted. If no row has output 1, AND (NOT ) 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 add_two_bits(a1, a0, b1, b0) that adds two numbers of two bits each, and , using half adders and one OR gate. It returns three bits. Check it on all 16 inputs.
Solution
Solution of Exercise 32.12.
A half adder adds the units; a second one adds the twos; a third adds the carry of the units to that. The two carries can never both be 1, so an OR gives the last bit. The file sits next to gates.py:
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
A test of the chapter checks 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.
- Write the truth table: 8 rows, with the inputs , , (1 for a pressed button) and the output (1 for the buzzer).
- In which rows does the buzzer sound? What do they have in common?
- Why do 8 rows cover every case?
Part II — Two circuits.
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)
- Explain the idea of
pairs. - Explain the idea of
majority: what happens when and agree, and when they do not? - Run the program. Do the two circuits agree with the rule on all 8 inputs?
- Why does comparing them on 8 inputs prove that they are right, and not just likely to be right?
Part III — Counting.
- How many two-input gates does
pairsuse? Andmajority? - Draw the circuit of
pairs. - With five judges and “at least three”, how many rows does the truth table have?
- Which circuit would you build, and why?
- State the result.
Solution
Solution of Problem 32.1.
1. The rule’s column of the program’s output 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: 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 and both press, AND makes the buzzer sound. If neither presses, at most one judge pressed, and OR is 0, so the output is 0. If they disagree, there is exactly one press already, and decides: AND ( OR ) is .
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
7. The 8 inputs are all the inputs 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, one per pair (, , ); an OR joins the first two, and a second OR joins that with the third.
10. rows.
11. majority saves a gate; pairs is easier to check by reading. Both are proved right by the program.
12. Result. “At least two of three” is ( AND ) OR ( AND ) OR ( AND ): five two-input gates, and the program checks it, against the rule, on all 8 inputs; a circuit of four gates does the same. Five judges need a truth table of 32 rows.