কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

High School Computer Science · শ্রেণি 10–12

24Linked Lists, Stacks and Queues

The undo button of an editor cancels the last change first, then the one before it: the newest change leaves first. A printer serves its waiting documents in the order they came: the oldest leaves first. The two are the same idea, a line of things waiting, taken from opposite ends; and each has a name, an interface, and more than one way to build it.

This chapter separates what a structure does from how it is built. It builds the linked list, a chain of small cells, and from it the stack and the queue, each in two ways; it counts what each operation costs; and it uses them to check brackets, to compute, and to simulate a day at a post office counter.

You already know

A class groups data with its methods, and an invariant is kept by the methods (chapter 23). A module offers an interface and hides its implementation (chapter 20). The cost of an algorithm (chapter 17). A dictionary finds a value from its key (Book 1, grade 8).

24.1 A structure is defined by its operations

Definition 24.1 (Abstract data type)

An abstract data type is a kind of data defined only by its operations and what each one does: an interface with its specifications. How the data is stored, its implementation, is left out; one abstract data type can have several implementations, and a program that uses only the interface works with any of them.

This is the idea of the module interface, applied to data. The stack and the queue below are abstract data types; the linked list is one way to implement them.

24.2 The linked list

Definition 24.2 (Linked list, cell)

A linked list is a sequence stored as a chain of cells: each cell holds one value and a link to the next cell, and the last cell’s link is None. The list is known by its first cell, its head.

"""Linked lists made of cells."""


class Cell:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next                # the next cell, or None at the end


def from_list(values):
    head = None
    for v in reversed(values):          # build from the end: each new cell leads
        head = Cell(v, head)
    return head


def to_list(head):
    out = []
    cell = head
    while cell is not None:
        out.append(cell.value)
        cell = cell.next
    return out
Listing 24.1. Cells, and two conversions to and from Python lists. code/grade-12/03-lists-stacks-queues/listings/cell.py
The linked list 3, 1, 4, 1. Walking it means following the links from the head; the crossed box is the link None of the last cell. Inserting at the head is one new cell whose link is the old head.
The linked list 3,1,4,13, 1, 4, 1. Walking it means following the links from the head; the crossed box is the link None of the last cell. Inserting at the head is one new cell whose link is the old head.
from cell import Cell, from_list, to_list

head = Cell(3, Cell(1, Cell(4, Cell(1))))   # 3 -> 1 -> 4 -> 1 -> None
cell = head
while cell is not None:                     # walking: follow the links
    print(cell.value, end=" -> ")
    cell = cell.next
print(None)

head = Cell(9, head)                        # insert at the head: one new cell
print(to_list(head))
second = head.next
second.next = second.next.next              # remove the cell after 3: skip it
print(to_list(head))
print(to_list(from_list("abc")), to_list(from_list([])))
Listing 24.2. Walking, inserting at the head, and removing a cell by skipping it. code/grade-12/03-lists-stacks-queues/listings/linked_demo.py
$ python linked_demo.py
3 -> 1 -> 4 -> 1 -> None
[9, 3, 1, 4, 1]
[9, 3, 4, 1]
['a', 'b', 'c'] []
Output 24.1. Inserting and removing changed one link each; no value moved.

A linked list and a Python list cost differently. Reading the value at index ii of a Python list takes the same short time for every ii; in a linked list it means walking ii links. Inserting at the front of a Python list shifts every element by one place; in a linked list it is one new cell, whatever the length.

24.3 The stack

Definition 24.3 (Stack, push, pop, LIFO)

A stack is an abstract data type holding a sequence of elements, with four operations: create an empty stack; test whether it is empty; push an element on top; pop the top element, removing and returning it, which is refused on an empty stack. A fifth, top, returns the top without removing it. The last element pushed is the first popped: the stack is LIFO, last in, first out.

A stack before and after one push and one pop. Only the top is reachable; the pop gives back the element of the last push.
A stack before and after one push and one pop. Only the top is reachable; the pop gives back the element of the last push.

Two implementations share one interface. In the first, the top is the end of a Python list; in the second, the top is the head of a linked list. Both push and pop in a time that does not depend on the number of elements.

"""A stack kept in a Python list: the top is the end of the list."""


class Stack:
    def __init__(self):
        self._items = []

    def is_empty(self):
        return self._items == []

    def push(self, x):
        self._items.append(x)

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from an empty stack")
        return self._items.pop()

    def top(self):
        if self.is_empty():
            raise IndexError("top of an empty stack")
        return self._items[-1]
Listing 24.3. A stack in a Python list. code/grade-12/03-lists-stacks-queues/listings/stack_list.py
"""A stack made of linked cells: the top is the first cell."""
from cell import Cell


class Stack:
    def __init__(self):
        self._head = None

    def is_empty(self):
        return self._head is None

    def push(self, x):
        self._head = Cell(x, self._head)

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from an empty stack")
        x = self._head.value
        self._head = self._head.next
        return x

    def top(self):
        if self.is_empty():
            raise IndexError("top of an empty stack")
        return self._head.value
Listing 24.4. The same interface, with linked cells. code/grade-12/03-lists-stacks-queues/listings/stack_linked.py

Since both promise the same behaviour, one test suite checks both: the tests use only the interface, and the class under test is chosen by a loop.

"""One test suite, run on both implementations of the stack."""
import unittest

import stack_linked
import stack_list


class StackTests(unittest.TestCase):
    Stack = None                                # set for each implementation

    def test_new_stack_is_empty(self):
        self.assertTrue(self.Stack().is_empty())

    def test_last_in_first_out(self):
        s = self.Stack()
        for x in [1, 2, 3]:
            s.push(x)
        self.assertEqual([s.pop(), s.pop(), s.pop()], [3, 2, 1])
        self.assertTrue(s.is_empty())

    def test_top_does_not_remove(self):
        s = self.Stack()
        s.push("a")
        self.assertEqual((s.top(), s.top()), ("a", "a"))
        self.assertFalse(s.is_empty())

    def test_empty_stack_refuses(self):
        with self.assertRaises(IndexError):
            self.Stack().pop()
        with self.assertRaises(IndexError):
            self.Stack().top()
Listing 24.5. One suite of tests for the stack interface. code/grade-12/03-lists-stacks-queues/listings/stacks_tests.py
for module in [stack_list, stack_linked]:
    suite = unittest.TestSuite()
    for name in unittest.TestLoader().getTestCaseNames(StackTests):
        test = StackTests(name)
        test.Stack = module.Stack
        suite.addTest(test)
    result = unittest.TestResult()
    suite.run(result)
    print(f"{module.__name__:13} {result.testsRun} tests, "
          f"{len(result.failures)} failures, {len(result.errors)} errors")
Listing 24.6. The suite run on each implementation in turn. code/grade-12/03-lists-stacks-queues/listings/stacks_tests.py
$ python stacks_tests.py
stack_list    4 tests, 0 failures, 0 errors
stack_linked  4 tests, 0 failures, 0 errors
Output 24.2. Both implementations pass the four tests.

24.4 The queue

Definition 24.4 (Queue, enqueue, dequeue, FIFO)

A queue is an abstract data type holding a sequence, with the operations: create an empty queue; test whether it is empty; enqueue an element at the back; dequeue the element at the front, removing and returning it, refused on an empty queue. The first element enqueued is the first dequeued: the queue is FIFO, first in, first out.

A linked list makes a queue if the program keeps a second pointer, to the last cell: elements leave at the head and arrive after the tail. Both operations then change one or two links.

A linked queue holding 5, 8, 2. Enqueueing 7 links a new cell after the tail and moves _tail to it (dashed); dequeueing moves _head to the next cell.
A linked queue holding 5,8,25, 8, 2. Enqueueing 77 links a new cell after the tail and moves _tail to it (dashed); dequeueing moves _head to the next cell.
"""A queue of linked cells, with a pointer to each end."""
from cell import Cell


class Queue:
    def __init__(self):
        self._head = None                   # the first in line: dequeued next
        self._tail = None                   # the last in line
        self.moves = 0                      # cells linked or unlinked

    def is_empty(self):
        return self._head is None

    def enqueue(self, x):
        cell = Cell(x)
        if self.is_empty():
            self._head = cell
        else:
            self._tail.next = cell
        self._tail = cell
        self.moves += 1

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from an empty queue")
        x = self._head.value
        self._head = self._head.next
        if self._head is None:              # the queue is empty again
            self._tail = None
        self.moves += 1
        return x
Listing 24.7. A linked queue, which also counts its moves. code/grade-12/03-lists-stacks-queues/listings/queue_linked.py

The second implementation surprises: a queue made of two stacks. Arrivals are pushed on an in-stack. To dequeue, the program pops from an out-stack; when the out-stack is empty, it first pops every element of the in-stack and pushes it on the out-stack, which reverses their order and puts the oldest on top.

A queue from two stacks. The transfer pops 3, 2, 1 from the in-stack and pushes them on the out-stack, where 1, the oldest, is now on top. The next two dequeues pop 2 and 3 with no transfer.
A queue from two stacks. The transfer pops 33, 22, 11 from the in-stack and pushes them on the out-stack, where 11, the oldest, is now on top. The next two dequeues pop 22 and 33 with no transfer.
"""A queue made of two stacks: arrivals go in, departures come out."""
from stack_linked import Stack


class Queue:
    def __init__(self):
        self._in = Stack()                  # the newest on top
        self._out = Stack()                 # the oldest on top
        self.moves = 0                      # elements placed or removed

    def is_empty(self):
        return self._in.is_empty() and self._out.is_empty()

    def enqueue(self, x):
        self._in.push(x)
        self.moves += 1

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from an empty queue")
        if self._out.is_empty():            # transfer: reverses the order
            while not self._in.is_empty():
                self._out.push(self._in.pop())
                self.moves += 1
        self.moves += 1
        return self._out.pop()
Listing 24.8. A queue made of two stacks. code/grade-12/03-lists-stacks-queues/listings/queue_two_stacks.py

One dequeue can be slow: it may transfer every element. But an element is transferred at most once, since it never goes back to the in-stack. Counting a “move” each time an element is pushed on the in-stack, transferred, or popped from the out-stack, each element makes at most three moves in its whole life: nn enqueues followed by any dequeues cost at most 3n3n moves in all, however they are interleaved (exercise 24.12).

The two queues pass one suite of tests, written like the stack suite; here is one of its four tests.

    def test_mixed_operations(self):
        q, out = self.Queue(), []
        for step in "ab-c--d-":                  # a letter enqueues, - dequeues
            if step == "-":
                out.append(q.dequeue())
            else:
                q.enqueue(step)
        self.assertEqual(out, ["a", "b", "c", "d"])
Listing 24.9. A test that mixes enqueues and dequeues. code/grade-12/03-lists-stacks-queues/listings/queues_tests.py
$ python queues_tests.py
queue_linked     4 tests, 0 failures, 0 errors
queue_two_stacks 4 tests, 0 failures, 0 errors
Output 24.3. Both queues pass.

24.5 Using them

Checking brackets

In a program, every opening bracket must be closed by a bracket of the same kind, the last opened being the first closed: a stack. Each opening is pushed; each closing must match the top, which is popped; at the end nothing may be left open.

from stack_list import Stack

PAIRS = {")": "(", "]": "[", "}": "{"}


def balanced(text):
    s = Stack()
    for ch in text:
        if ch in "([{":
            s.push(ch)                       # an opening waits for its closing
        elif ch in PAIRS:
            if s.is_empty() or s.pop() != PAIRS[ch]:
                return False                 # nothing open, or the wrong kind
    return s.is_empty()                      # nothing left open


for text in ["f(a[i], {k: (1, 2)})", "(]", "((x)", "x)(", "print('hi')"]:
    print(f"{text:22} {balanced(text)}")
Listing 24.10. Balanced brackets, with a stack. code/grade-12/03-lists-stacks-queues/listings/brackets.py
$ python brackets.py
f(a[i], {k: (1, 2)})   True
(]                     False
((x)                   False
x)(                    False
print('hi')            True
Output 24.4. (] closes the wrong kind; ((x) leaves one open; x)( closes before opening.

Computing in postfix notation

Definition 24.5 (Postfix notation)

In postfix notation, an operator is written after its two operands: 3+43 + 4 is 3 4 +, and (3+4)×2(3 + 4) \times 2 is 3 4 + 2 *. No brackets and no priority rules are needed: the order of the operators says everything.

A postfix expression is evaluated with one stack: a number is pushed; an operator pops two numbers, the right operand first, and pushes the result. At the end the stack holds exactly one number, the value.

The stack while 3 4 + 2 * is read, one picture per token. An operator replaces the two numbers on top by its result (shaded); 14 is left alone at the end.
The stack while 3 4 + 2 * is read, one picture per token. An operator replaces the two numbers on top by its result (shaded); 1414 is left alone at the end.
from stack_list import Stack

OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
       "*": lambda a, b: a * b, "/": lambda a, b: a / b}


def evaluate(expression, show=False):
    s = Stack()
    for token in expression.split():
        if token in OPS:
            b = s.pop()                      # the right operand is on top
            a = s.pop()
            s.push(OPS[token](a, b))
        else:
            s.push(float(token))
        if show:
            print(f"  read {token:>2}   top {s.top()}")
    result = s.pop()
    if not s.is_empty():
        raise ValueError("too many numbers")
    return result


print(evaluate("3 4 + 2 *", show=True))      # (3 + 4) * 2
print(evaluate("3 4 2 * +"))                 # 3 + 4 * 2
print(evaluate("10 2 8 * + 3 -"))            # 10 + 2 * 8 - 3
try:
    evaluate("1 +")
except IndexError as error:
    print("IndexError:", error)
Listing 24.11. A postfix calculator. code/grade-12/03-lists-stacks-queues/listings/postfix.py
$ python postfix.py
  read  3   top 3.0
  read  4   top 4.0
  read  +   top 7.0
  read  2   top 2.0
  read  *   top 14.0
14.0
11.0
23.0
IndexError: pop from an empty stack
Output 24.5. The top after each token, then three values and a malformed expression.

A waiting line

A counter serves people in the order they came: a queue. Here people arrive at random, and the counter serves one every two minutes.

"""Ten minutes at a counter: one person served per two minutes."""
import random

from queue_linked import Queue

rng = random.Random(7)
line, served = Queue(), 0
for minute in range(10):
    arrived = [f"c{minute}{k}" for k in range(rng.randint(0, 2))]
    for person in arrived:
        line.enqueue(person)
    leaving = line.dequeue() if minute % 2 == 1 and not line.is_empty() else "-"
    print(f"minute {minute}: arrive {' '.join(arrived) or '-':8} served {leaving}")
Listing 24.12. Ten minutes at a counter. code/grade-12/03-lists-stacks-queues/listings/waiting_line.py
$ python waiting_line.py
minute 0: arrive c00      served -
minute 1: arrive -        served c00
minute 2: arrive c20      served -
minute 3: arrive c30 c31  served c20
minute 4: arrive -        served -
minute 5: arrive -        served c30
minute 6: arrive c60 c61  served -
minute 7: arrive -        served c31
minute 8: arrive c80      served -
minute 9: arrive c90 c91  served c60
Output 24.6. Each person leaves in the order of arrival; c31 waits four minutes behind c30.

Choosing a structure

The choice follows from the operations the program needs. Undo, brackets, the calls of a recursive function: a stack. Services in order of arrival, a printer, the visit of a graph level by level (chapter 26): a queue. Many insertions at the front: a linked list. Reading by index: a Python list. Finding a value from a key: a dictionary, which does not scan its keys at all.

"""Looking up a key among n pairs: scanning a list against a dictionary."""
import timeit



def scan(pairs, key):
    for k, v in pairs:
        if k == key:
            return v


for n in [1_000, 10_000, 100_000]:
    pairs = [(f"name{i}", i) for i in range(n)]
    book = dict(pairs)
    key = f"name{n - 1}"                       # the worst case for the scan
    env = {"scan": scan, "pairs": pairs, "book": book, "key": key}
    t_list = min(timeit.repeat("scan(pairs, key)", globals=env, number=20)) / 20
    t_dict = min(timeit.repeat("book[key]", globals=env, number=20_000)) / 20_000
    print(f"n = {n:>7}: list {t_list * 1e6:9.2f} us   dict {t_dict * 1e6:6.3f} us"
          f"   ratio {t_list / t_dict:8.0f}")
Listing 24.13. Finding a key in a list of pairs and in a dictionary. code/grade-12/03-lists-stacks-queues/listings/list_vs_dict.py
$ python list_vs_dict.py
n =    1000: list     11.01 us   dict  0.013 us   ratio      821
n =   10000: list    104.92 us   dict  0.015 us   ratio     7224
n =  100000: list   1056.88 us   dict  0.012 us   ratio    87679
Output 24.7. On the author’s laptop: the scan grows ten times with nn, the dictionary stays at about 0.010.01 microseconds.

24.6 Exercises

Exercise 24.1 ★

From an empty stack: push 11, push 22, push 33, pop, push 44, pop, pop. What did the pops return, and what is left?

Solution

Solution of Exercise 24.1.

The pops return 33, then 44, then 22; the stack holds 11 alone.

Exercise 24.3 ★

Give the stack after each character of {[()]}(, and the answer of balanced.

Solution

Solution of Exercise 24.3.

Bottom first: {, {[, {[(, then {[ after ), { after ], empty after }, and ( after the last character. The string ends with a bracket still open: False.

Exercise 24.4 ★

Evaluate 5 1 2 + 4 * + 3 - by hand, with the stack after each token.

Solution

Solution of Exercise 24.4.

Bottom first: [5][5], [5,1][5, 1], [5,1,2][5, 1, 2], then + gives [5,3][5, 3], [5,3,4][5, 3, 4], * gives [5,12][5, 12], + gives [17][17], [17,3][17, 3], and - gives [14][14]. The value is 1414, that is 5+(1+2)×4−35 + (1 + 2) \times 4 - 3.

Exercise 24.5 ★

Add a method size to both stacks. In the linked stack, it must not walk the cells.

Solution

Solution of Exercise 24.5.

In the list stack, return len(self._items). The linked stack keeps a counter: the constructor sets self._size = 0, push adds 11, pop subtracts 11 after a successful pop, and size returns it. The count is then a second invariant of the class: _size is the number of cells.

Exercise 24.6 ★★

If pop did not test for an empty stack, what would each implementation raise on an empty stack? Why is the test worth writing?

Solution

Solution of Exercise 24.6.

The list stack would raise IndexError: pop from empty list, from Python’s list; the linked stack would raise AttributeError: 'NoneType' object has no attribute 'value', since _head is None. Two implementations of one interface would fail in two different ways, and the second message speaks of the implementation, not of the stack. The test makes both raise the error the interface promises, with a message a user understands.

Exercise 24.7 ★★

Write the length of a linked list given by its head, recursively and with a loop.

Solution

Solution of Exercise 24.7.

def length_rec(cell):

return 0 if cell is None else 1 + length_rec(cell.next)

def length_iter(cell):

n = 0

while cell is not None:

n, cell = n + 1, cell.next

return n

The recursive one needs one frame per cell, and fails beyond Python’s recursion limit (chapter 22); the loop does not.

Exercise 24.8 ★★

A student’s queue decides that it is empty by self._tail is None, and its dequeue never changes _tail. Enqueue 11, dequeue, enqueue 22: where is 22, and what does the next dequeue do?

Solution

Solution of Exercise 24.8.

After the dequeue, _head is None but _tail still points at the cell of 11. Enqueueing 22 finds _tail not None, so it links the new cell after the cell of 11, which is no longer in the queue, and leaves _head at None. The 22 is lost: nothing in the queue leads to it. The next dequeue reads self._head.value and fails with AttributeError. The repair: in dequeue, set _tail to None when _head becomes None.

Exercise 24.9 ★★

On the two-stack queue: enqueue 11, 22, 33, dequeue, enqueue 44, then dequeue three times. Count the moves after each operation.

Solution

Solution of Exercise 24.9.

Enqueues: 11, 22, 33 moves. The first dequeue finds the out-stack empty, transfers 33 elements (66) and pops 11 (77). Enqueue 44: 88. Dequeue 22: 99; dequeue 33: 1010. The last dequeue finds the out-stack empty again, transfers 44 (1111) and pops it (1212). Four elements, 12=3×412 = 3 \times 4 moves.

Exercise 24.10 ★★

Write reverse(head), which reverses a linked list by changing its links, without creating a cell, and returns the new head.

Solution

Solution of Exercise 24.10.

def reverse(head):

previous = None

while head is not None:

following = head.next

head.next = previous

previous, head = head, following

return previous

Invariant of the loop: previous is the reversed list of the cells already visited, and head the rest, untouched. One pass, no new cell.

Exercise 24.11 ★★

Write (2+3)×(7−4)/5(2 + 3) \times (7 - 4) / 5 in postfix notation, and evaluate it with the stack method.

Solution

Solution of Exercise 24.11.

2 3 + 7 4 - * 5 /. The stack, bottom first: [2][2], [2,3][2, 3], [5][5], [5,7][5, 7], [5,7,4][5, 7, 4], [5,3][5, 3], [15][15], [15,5][15, 5], [3][3]: the value is 33.

Exercise 24.12 ★★★

Prove that, in the two-stack queue, each element makes at most three moves, and deduce that any sequence of operations containing nn enqueues makes at most 3n3n moves.

Solution

Solution of Exercise 24.12.

Follow one element. It is pushed on the in-stack once, by its enqueue: one move. Only a transfer takes elements off the in-stack, and a transfer puts each one on the out-stack: one move. Nothing ever puts an element back on the in-stack, so an element is transferred at most once. Only a dequeue takes an element off the out-stack, and it leaves the queue: one move. So each element makes at most three moves. Every move counted by the class is one of these three, charged to one element; with nn elements enqueued, the total is at most 3n3n, whatever the order of the operations. A single dequeue may make many moves, but the total stays in proportion to nn.

Exercise 24.13 ★★★

Write a queue of fixed capacity kept in a Python list of that length, with the index of the oldest element and the number of elements; the indices wrap around to 00 at the end of the list. A full queue refuses to enqueue.

Solution

Solution of Exercise 24.13.

def enqueue(self, x):

if self._count == len(self._slots):

raise OverflowError("the queue is full")

self._slots[(self._first + self._count) % len(self._slots)] = x

self._count += 1

def dequeue(self):

if self._count == 0:

raise IndexError("dequeue from an empty queue")

x = self._slots[self._first]

self._first = (self._first + 1) % len(self._slots)

self._count -= 1

return x

The constructor sets _slots = [None] * capacity, _first = 0 and _count = 0. The remainder by the capacity makes the index wrap from the last slot to slot 00; no element ever moves.

Exercise 24.14 ★★★

Write to_postfix(expression) for expressions of numbers, +, -, *, / and brackets, tokens separated by spaces. Numbers go straight to the output; operators wait on a stack, which first gives up the operators of priority greater than or equal to the new one; a closing bracket empties the stack down to its opening bracket.

Solution

Solution of Exercise 24.14.

PRIORITY = {"+": 1, "-": 1, "*": 2, "/": 2}

def to_postfix(expression):

out, ops = [], Stack()

for token in expression.split():

if token in PRIORITY:

while (not ops.is_empty() and ops.top() != "("

and PRIORITY[ops.top()] >= PRIORITY[token]):

out.append(ops.pop())

ops.push(token)

elif token == "(":

ops.push(token)

elif token == ")":

while ops.top() != "(":

out.append(ops.pop())

ops.pop()

else:

out.append(token)

while not ops.is_empty():

out.append(ops.pop())

return " ".join(out)

“Greater than or equal” makes operators of equal priority leave from the left: 10 - 2 - 3 gives 10 2 - 3 -, which is 55, and not 10−(2−3)10 - (2 - 3). The tests check the expression of exercise 24.11, and that 1 + 2 * 3 - 8 / 4 evaluates to 55.

Exercise 24.15 ★★★

Call a string of the characters (, ), [, ] balanced if it is empty, or of the form (u)v(u)v or [u]v[u]v with uu and vv balanced. Prove that balanced returns True exactly on the balanced strings.

Solution

Solution of Exercise 24.15.

Only the bracket characters count here; other characters do nothing to the stack.

Balanced strings are accepted. We prove more, by induction on the length: started with any stack SS, the loop reads a balanced string ww without returning False and ends with the stack SS again. The empty string does nothing. If w=(u)vw = (u)v, the ( is pushed; uu, shorter, leaves the stack as SS with ( on top; the ) matches that top and pops it, giving SS; vv, shorter, leaves SS. The same for [u]v[u]v. Started with an empty stack, the function therefore ends with an empty stack and returns True.

Accepted strings are balanced, by induction on the length. The empty string is balanced. Let ww be accepted and not empty. Its first character is an opening bracket, since a closing one would meet an empty stack. That bracket lies at the bottom of the stack, and is popped at some point, since the stack ends empty: by a closing bracket of the same kind, at some position. Call uu the characters strictly between, and vv those after. While uu is read, the bottom bracket is never reached, so uu is read exactly as from an empty stack, and ends with the stack holding only that bracket: uu is accepted, and balanced by induction. After the matching closing bracket the stack is empty, and vv is read from an empty stack and accepted: balanced by induction. So w=(u)vw = (u)v or [u]v[u]v is balanced.

24.7 Problem: The Queue at the Post Office

Problem 24.1

Weekend problem — a day at the counter

A post office opens for 480480 minutes. In each minute, a customer arrives with chance 0.30.3; one clerk serves the line in order, each service taking 11 to 55 minutes. At closing time the doors shut and the people inside are still served. The program runs the same day, with the same random numbers, on both queues.

"""A day at the post office: 480 minutes of arrivals, one clerk, two queues."""
import random

import queue_linked
import queue_two_stacks


def simulate(Queue, seed=2026):
    rng = random.Random(seed)
    line = Queue()
    waiting = longest_line = longest_wait = customers = 0
    busy_until = 0
    minute = 0
    while minute < 480 or not line.is_empty():   # doors close, the line is served
        if minute < 480 and rng.random() < 0.3:      # an arrival this minute
            line.enqueue(minute)
            customers += 1
            waiting += 1
        if minute >= busy_until and not line.is_empty():
            arrived = line.dequeue()
            waiting -= 1
            longest_wait = max(longest_wait, minute - arrived)
            busy_until = minute + rng.randint(1, 5)  # service of 1 to 5 minutes
        longest_line = max(longest_line, waiting)
        minute += 1
    return customers, longest_line, longest_wait, line.moves


for module in [queue_linked, queue_two_stacks]:
    customers, length, wait, moves = simulate(module.Queue)
    print(f"{module.__name__}: {customers} customers, longest line {length},"
          f" longest wait {wait} min")
    print(f"  moves {moves} = {moves / customers:.2f} per customer")
Listing 24.14. A day at the post office, on both queues. code/grade-12/03-lists-stacks-queues/listings/post_office.py
$ python post_office.py
queue_linked: 114 customers, longest line 5, longest wait 13 min
  moves 228 = 2.00 per customer
queue_two_stacks: 114 customers, longest line 5, longest wait 13 min
  moves 342 = 3.00 per customer
Output 24.8. One day, two implementations.

Part I — The queue as an abstract data type.

  1. Which operations of the queue does simulate use? Which attribute does it read that is not part of the abstract data type?
  2. Why can simulate take the class Queue as an argument and work with either?
  3. What does the queue hold: the customers’ names, or something else? Why is that enough?
  4. The variable waiting counts the people in line. Why does the program keep it, rather than ask the queue?

Part II — Two implementations.

  1. In queue_linked, which links change at an enqueue on an empty queue, and on a queue of three?
  2. Why must dequeue set _tail to None when the queue becomes empty?
  3. In queue_two_stacks, when does a dequeue transfer elements, and how many?
  4. Give a sequence of 66 operations in which one dequeue makes 44 moves.
  5. Which implementation would you pick for a queue that is mostly empty? For one where every dequeue must be fast?

Part III — The simulation.

  1. Why is the random generator built from a fixed seed?
  2. Why do both implementations give exactly the same customers, line and waits?
  3. A service lasts 33 minutes on average over the five durations, and a customer arrives about every 1/0.3≈3.31/0.3 \approx 3.3 minutes. What happens to the line if the services become a little longer?
  4. Why does the loop go on after minute 480480, and when does it stop?
  5. Explain how the program finds each customer’s wait.

Part IV — Results and costs.

  1. Read the number of customers, the longest line and the longest wait.
  2. How many moves does the linked queue make per customer? Why exactly that number?
  3. How many does the two-stack queue make per customer? Why exactly 33, and not at most 33?
  4. Is the two-stack queue slower in time? Compare the work of one move in each.
  5. What would change in the moves if the program stopped at minute 480480, with people still in line?
  6. State the result of the day, and of the comparison.
Solution

Solution of Problem 24.1.

1. The constructor, enqueue, dequeue and is_empty. It also reads moves, a counter added for this chapter, which is not part of the queue’s interface.

2. A class is a value: simulate receives it and calls it to build a queue. It then uses only the interface, which both classes offer with the same behaviour.

3. The minute of each arrival. The only thing the program needs to know about a customer is how long they waited, and that is the minute of service minus the minute of arrival.

4. The abstract data type has no operation giving the number of elements. Counting arrivals and departures answers in one step, where walking the queue would cost a step per person.

5. On an empty queue, no link between cells: _head and _tail are both set to the new cell. On a queue of three, the link of the old last cell, and _tail.

6. With this enqueue, which tests emptiness on _head, the queue would still work. But _tail would keep pointing at a cell that has left the queue, so the invariant “_tail is None exactly when the queue is empty” would be false, and any method relying on it would fail, as in exercise 24.8.

7. When the out-stack is empty. It transfers every element of the in-stack.

8. Enqueue 11, 22, 33, then dequeue three times. The first dequeue makes 44 moves: 33 transfers and one pop.

9. For both, the linked queue: it makes fewer moves, and every operation takes a time that does not depend on the length, where a dequeue of the two-stack queue can transfer the whole line at once.

10. So that the run is the same day every time: the output printed in the book is reproduced exactly, and both implementations are compared on the same arrivals.

11. The queue draws no random numbers, so the generator gives the same numbers in the same order to both runs; and both are queues, giving back the same arrival minutes in the same order. Every decision of the program is then the same.

12. The clerk is already busy most of the time. If services were longer than the time between arrivals, people would arrive faster than they leave, and the line would grow all day.

13. The doors close at minute 480480, but the people inside are served. The loop stops at the first minute from 480480 on at which the line is empty.

14. The queue holds each customer’s arrival minute; when one is served, at minute minute, the wait is minute - arrived, and the longest is kept.

15. 114114 customers; at most 55 people waiting at once; the longest wait 1313 minutes.

16. 22: one enqueue and one dequeue per customer, and all 114114 were served.

17. 33: every customer is enqueued, and, being served, has been transferred once and popped once. The bound of exercise 24.12 is reached because nobody is left in line.

18. A move of either queue creates or unlinks one cell, a few steps of the same kind. The two-stack queue does 342342 moves against 228228: half as much work again, but the same order of cost, in proportion to the number of customers.

19. The people still in line would not be dequeued: fewer than 22 moves per customer for the linked queue, fewer than 33 for the two-stack queue, where those still in the in-stack would have made only one.

20. Over the day, 114114 customers, a longest line of 55 and a longest wait of 1313 minutes, the same with both queues; the linked queue makes 228228 moves, 22 per customer, the two-stack queue 342342, exactly 33 per customer.

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

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