CORR-P2

The second fastest train

Practice 2 of 5Correctness9 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1Different speedsNot run
2Fastest repeatedNot run
3Second best comes firstNot run
4Only one speedNot run
5One trainNot run
6Two speedsNot run
7Negative valuesNot run
8Input not changedNot run
9A million speedsNot run