The problem
The list speeds holds the top speed of each train. Return the second largest different speed. Equal values count as one speed. If there are fewer than two different speeds, return None.
second_largest([110, 130, 90, 120]) # 120
second_largest([130, 110, 130]) # 110: 130 counts once
second_largest([100, 100]) # None
second_largest([75]) # None
Solve it in one pass, as in lesson 2. Keep two names, the best and the second best seen so far. Write down the invariant they keep, then check that every step keeps it.
Limits
- Up to 1,000,000 speeds. The list has at least one speed.
- Speeds can be negative. Do not sort or change
speeds.
Builds on CORR-1 What “correct” means and CORR-2 Loop invariants.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Different speeds | Not run | |
| 2 | Fastest repeated | Not run | |
| 3 | Second best comes first | Not run | |
| 4 | Only one speed | Not run | |
| 5 | One train | Not run | |
| 6 | Two speeds | Not run | |
| 7 | Negative values | Not run | |
| 8 | Input not changed | Not run | |
| 9 | A million speeds | Not run |