PYTH-P3

The first repeated code

Practice 3 of 5Python for DSA7 tests

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

  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.

7 tests, not run yet
Test results
#TestResultReads · time
1A repeat in the middleNot run
2First to repeat, not first to appearNot run
3Two in a rowNot run
4No repeatsNot run
5Empty listNot run
6Case mattersNot run
7100,000 codes, repeat at the endNot run