CMU Coding Bootcamp
1from typing import List
2
3
4def repeats(L: List[int]) -> List[int]:
5 """Returns a sorted list of unique elements that are present in L more than once."""
6 return list(sorted({x for x in L if L.count(x) > 1}))
7
8
9def testRepeats():
10 print("Testing repeats()...", end="")
11 assert repeats([1, 2, 3, 2, 1]) == [1, 2]
12 assert repeats([1, 2, 3, 2, 2, 4]) == [2]
13 assert repeats([1, 5, 3, 5, 2, 3, 2, 1]) == [1, 2, 3, 5]
14 assert repeats([7, 9, 1, 3, 7, 1]) == [1, 7]
15 assert repeats(list(range(100))) == []
16 assert repeats(list(range(100)) * 5) == list(range(100))
17
18 # Verify that the function is nonmutating:
19 L = [1, 2, 3, 2, 1]
20 repeats(L)
21 assert L == [1, 2, 3, 2, 1]
22 print("Passed!")
23
24
25def main():
26 testRepeats()
27
28
29main()