The problem
A signal box logs the code of each train as it passes. Reading the log from left to right, find the first code that you see for the second time. Return that code, or None if every code is different.
first_repeat(["BCT", "HWH", "MAS", "HWH", "BCT"]) # "HWH"
first_repeat(["A", "B", "B", "A"]) # "B"
first_repeat(["BCT", "HWH"]) # None
In the second example, A appears first, but B is the first code to appear again. Codes are compared exactly, so "bct" and "BCT" are different.
Limits
- Up to about 100,000 codes.
Builds on PYTH-4 Dicts, sets and tuples.
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 | A repeat in the middle | Not run | |
| 2 | First to repeat, not first to appear | Not run | |
| 3 | Two in a row | Not run | |
| 4 | No repeats | Not run | |
| 5 | Empty list | Not run | |
| 6 | Case matters | Not run | |
| 7 | 100,000 codes, repeat at the end | Not run |