A brief note on Data Structures, Testing and Debugging: stacks, queues, linked lists, search trees, graphs with BFS and DFS, tables of tests, unittest, edge cases, and the steps to find a bug. With a worked example, practice, a program and questions to check yourself.
A brief note on Data Structures, Testing and Debugging. Read it before a test. Try each question at the end before you open its answer.
| Structure | Its rule | In Python |
|---|---|---|
| Stack | last in, first out | a list: append, pop |
| Queue | first in, first out | deque: append, popleft |
| Linked list | a chain of nodes | node.next |
| Search tree | left smaller, right bigger | node.left, node.right |
| Graph | nodes and edges | a dictionary of neighbours |
stack[-1] looks at the top without removing it.None. Walk it with current = current.next while current is not None. Save the next node before you change a link.assert condition, "message" is silent when the condition is true, and stops with an AssertionError when it is false.unittest, a class inherits from unittest.TestCase, and each method whose name starts with test is a test. setUp runs before each one.assertEqual, assertAlmostEqual for decimals, and assertRaises with with. In the report, . is a pass, F a failure and E an error.The usual causes: off by one, a wrong condition at an edge, a variable that is not what you think, and a list changed by accident.
Six towns are joined by roads. BFS finds the route from Amberly to Fern with the fewest roads.
| Town taken | Queue after | New in came_from |
|---|---|---|
| (start) | Amberly | Amberly |
| Amberly | Brook, Cedar | Brook, Cedar |
| Brook | Cedar, Dune | Dune |
| Cedar | Dune, Elm | Elm |
| Dune | Elm, Fern | Fern |
| Elm | Fern | none |
| Fern | the goal |
came_from marks each town as seen and records where it was reached from. When Cedar is taken, Dune is already in it, so Dune is not added again.['Amberly', 'Brook', 'Dune', 'Fern']: 3 roads.median should give the middle plant height. A table of tests, with answers worked out from the rule, shows that it has a bug.
[].pop() stops with IndexError: pop from empty list, and an empty deque gives IndexError: pop from an empty deque. Check first.list.pop(0) for a long queue. It is slow. Use deque and popleft.roads["Fern"] stops with KeyError: 'Fern'. Every node needs an entry, even with an empty list.assertEqual for decimals. 0.1 + 0.2 is not exactly 0.3. Use assertAlmostEqual.head.next = new and then new.next = head.next. What happens to 9 and 2?unittest report starts with the line .F.E. How many tests ran, and what happened to each?Log in to join the discussion.
Loading…