12/37
Part 2 of 6 · The LRU orderLearn and do

A check method walks the list, with a step limit

Make the invariants executable. A check method walks the list and compares it with the map:

    def check(self):
        keys, node = [], self.head.next
        while node is not self.tail:
            assert node.next.prev is node, "a forward link has no matching backward link"
            keys.append(node.key)
            assert len(keys) <= self.capacity, "more nodes than capacity, or a cycle"
            node = node.next
        assert len(keys) == len(self.nodes) and set(keys) == set(self.nodes), "the map and the list disagree"

The second assert is a step limit, and it isn't decoration. A list can be broken in a way that a walk never leaves:

Predict

A walk collects keys from head until it reaches tail. A bug left c.next pointing back at b. What happens?

Pick an answer above to see the rest