কম্পিউটার বিজ্ঞান · বই 1 · শ্রেণি 1–9

Primary & Middle School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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; nn bits make 2n2^n 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)
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 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 1−a1 - a, XOR is the remainder of a+ba + b 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))
Listing 32.2. The four gates as functions, 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 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”.
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”.

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 2n2^n patterns of its nn inputs.

The circuit below computes (a AND b) OR (NOT c). Three inputs make 23=82^3 = 8 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))
Listing 32.3. The truth table of a circuit with three inputs. 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.
The circuit (a AND b) OR (NOT c): two gates feed a third. Its table is the output of .
The circuit (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)
Listing 32.4. Two circuits compared on every 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.

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 aa) =a= a
aa AND 1 =a= aaa OR 0 =a= a
aa AND 0 =0= 0aa OR 1 =1= 1
aa AND a=aa = aaa OR a=aa = a
aa AND (NOT aa) =0= 0aa OR (NOT aa) =1= 1

Each rule is checked by trying both values of aa. For instance, aa OR 1: if a=0a = 0, then 00 OR 1=11 = 1; if a=1a = 1, then 11 OR 1=11 = 1.

Proposition 32.4 (De Morgan’s laws for gates)

For any bits aa and bb, NOT (aa AND bb) == (NOT aa) OR (NOT bb), and NOT (aa OR bb) == (NOT aa) AND (NOT bb).

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())
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 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, aa XOR bb, and the carry bit, aa AND bb.

1+1=21 + 1 = 2, 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)
Listing 32.6. The 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.

The function returns two values; 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.
The half adder: an XOR gate and an AND gate share the same two inputs.

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.

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.
A battery, two switches and a lamp. In series, the lamp lights only if aa and bb are both closed; in parallel, it lights if aa or bb 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.
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 followed by a NOT gate. What does it output for a=1a = 1, b=0b = 0? And for a=0a = 0, b=0b = 0?

Solution

Solution of Exercise 32.1.

For a=1a = 1, b=0b = 0: the OR gives 1, the NOT turns it into 0. For a=0a = 0, b=0b = 0: the OR gives 0, and the output is 1. The circuit outputs 1 only when neither input is 1.

Exercise 32.2 ★

Write the truth table of XOR without looking, and say in words when its output is 1.

Solution

Solution of Exercise 32.2.

0 0 | 0, 0 1 | 1, 1 0 | 1, 1 1 | 0: the output is 1 when the two inputs are different.

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))
Listing 32.7. NOT, AND and OR from NAND alone. code/grade-9/02-logic-gates/listings/nand_only.py
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
Output 32.7. NAND, and the three gates built from it.

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

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)
Exactly one of three. code/grade-9/02-logic-gates/exercises/exactly_one.py

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)
Listing 32.8. A table with missing rows. code/grade-9/02-logic-gates/exercises/table_bug.py
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?

Solution

Solution of Exercise 32.6.

The input a=1a = 1, b=1b = 1: OR gives a sum bit 1, and the carry is 1, so the circuit claims that 1+11 + 1 is 11 in binary, which is 3.

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)))
The table of (a OR b) AND (NOT c). code/grade-9/02-logic-gates/exercises/table_or_not.py

The output is 1 on three rows only: 0 1 0, 1 0 0 and 1 1 0; at least one of aa and bb is 1, and cc 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
Two circuits compared on every input. code/grade-9/02-logic-gates/exercises/agree.py

Exercise 32.9 ★★

How many rows does the truth table of a circuit with 5 inputs have? And with 10?

Solution

Solution of Exercise 32.9.

25=322^5 = 32 rows, and 210=1,0242^{10} = 1{,}024 with 10 inputs.

Exercise 32.10 ★★★

Prove with a truth table that aa OR (aa AND bb) =a= a for all bits aa and bb. Then explain the rule in words.

Solution

Solution of Exercise 32.10.

0 0: aa AND bb 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 aa. In words: if aa is 1, the OR is 1 anyway; if aa is 0, then aa AND bb 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: 24=162^4 = 16 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 a=1a = 1, b=0b = 0, it is aa AND (NOT bb). The OR of these pieces gives 1 exactly on the rows wanted. If no row has output 1, aa AND (NOT aa) 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, a1a0a_1a_0 and b1b0b_1b_0, 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
Adding two numbers of two bits. code/grade-9/02-logic-gates/exercises/two_bit_adder.py

A test of the chapter checks 4×carry+2s1+s0=x+y4 \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: 8 rows, with the inputs aa, bb, cc (1 for a pressed button) and the output (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.

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
  1. Explain the idea of pairs.
  2. Explain the idea of majority: what happens when aa and bb agree, and when they do not?
  3. Run the program. Do the two circuits agree with the rule on all 8 inputs?
  4. Why does comparing them on 8 inputs prove that they are right, and not just likely to be right?

Part III — Counting.

  1. How many two-input gates does pairs use? And majority?
  2. Draw the circuit of pairs.
  3. With five judges and “at least three”, how many rows does the truth table have?
  4. Which circuit would you build, and why?
  5. 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: 23=82^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 aa and bb both press, aa AND bb makes the buzzer sound. If neither presses, at most one judge pressed, and aa OR bb is 0, so the output is 0. If they disagree, there is exactly one press already, and cc decides: cc AND (aa OR bb) is cc.

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 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 (aba b, bcb c, aca c); an OR joins the first two, and a second OR joins that with the third.

10. 25=322^5 = 32 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 (aa AND bb) OR (bb AND cc) OR (aa AND cc): 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.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো