What’s a typical Irish Rail delay when one train is much later than the rest?
Five Irish Rail trains arrive late, and one is much later than the rest. You want one number that describes a typical delay in this sample. What if you lined up the delays from shortest to longest and looked in the middle?
You already know how to sort a list. Here the delays run from shortest to longest. In Python you count positions from zero, so index zero holds six seconds, index one holds twelve seconds, and index two holds eighteen seconds.
Watch the five delays move into order. Six and eight end up to the left of twelve. Eighteen and thirty end up to its right. With two observations on either side, twelve seconds is the middle value. That’s the median.
Your next five delays are twenty, nine, four, two and twelve seconds. Put them in order from shortest to longest. Which delay ends up in the middle? Pick an answer.
Read the four sorted delays: four, ten, sixteen and forty seconds. The middle falls between ten and sixteen, at indices one and two. With an even number of observations, you take the mean of those two values. That gives thirteen seconds.
Start with twenty-eight, eight, two and fourteen seconds. Sort them into list a. Its length, n, is four. Integer division by two gives m equal to two. Since four is even, read indices m minus one and m. Average eight and fourteen to get eleven seconds.
Try the same trace with thirty, four, eighteen and ten seconds. First sort the four delays. Read the two middle values and use them to find the median. Pick an answer.
Compare the same delays in arrival order and in sorted order. Reading indices one and two too soon gives you eight and two, so you get five seconds. After sorting, those indices hold eight and fourteen, giving the correct median of eleven seconds.
Sort the non-empty list and count the delays. Integer division by two gives m. If the remainder is one, return the value at m. Otherwise, average the values at m minus one and m. Test that the five delays give twelve seconds and the four give eleven.
Try this exam-style instruction: state which route had the lower median delay. The chart shows eleven seconds for Route A and fifteen for Route B. State Route A and quote both values to support your answer. That comparison applies to the delays recorded in these samples.