These questions follow Stacks and Queues. Both containers hold things in order; they differ only in which one is allowed out next, and that difference is usually a promise to a person.

Reading and choosing

  1. Predict all four printed lines.
    line = []
    line.append("Nadia")
    line.append("Rowan")
    line.append("Bea")
    print(line.pop())
    print(line.pop(0))
    print(line)
    print(len(line) == 0)
  2. For each job, name the structure and say what would go wrong with the other one: (a) the library’s hold list for one copy; (b) undo in an editor; (c) print jobs sent to one printer; (d) checking that every opening bracket is closed; (e) students waiting to speak in a class discussion.
  3. Find the fault. The hold list serves the wrong person. What is the single-character change?
    def next_hold(holds):
        """Return the person who has been waiting longest."""
        return holds.pop()

Writing

  1. Write a Stack class with push, pop, peek, is_empty, and size, storing its items in _items. Show what happens when you pop one more time than you pushed.
  2. Write is_balanced(text) using a stack: True when every ( is closed by a ) in the right order. Test it on "(a + (b * c))", "(a + b))", "((a + b)", and "no brackets".
  3. Write reversed_text(text) using a stack — push every character, then pop them all back off.
  4. Write a BoundedStack that keeps only the most recent limit items, dropping the oldest when it overflows. Push four actions with a limit of three and show what survives.
  5. Add position_of(item) to a Queue class, returning how many people are ahead of somebody, or -1 if they are not waiting. Show a whole hold list being served in order.
  6. Judgement. Your Queue uses self._items.pop(0). A teammate says this is “inefficient and should be fixed”. Under what circumstances are they right, under what circumstances does it not matter, and what would you need to measure before changing it?

Answers

Curriculum connection

A1.5

describe and use one-dimensional arrays of compound data types (e.g., objects, structures, records) in a computer program.

Link to original

A3.3

create subprograms to insert and delete array elements;

Link to original

C1.1

decompose a problem into modules, classes, or abstract data types (e.g., stack, queue, dictionary) using an object-oriented design methodology (e.g., CRC [Class Responsibility Collaborator] or UML [Unified Modeling Language]);

Link to original

C1.2

demonstrate the ability to apply data encapsulation in program design (e.g., classes, records, structures);

Link to original

C2.1

demonstrate the ability to analyse a precondition (i.e., starting state) and a postcondition (i.e., ending state) in an algorithm;

Link to original