forked from hcientist/OnlinePythonTutor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimize-find-dups.txt
More file actions
60 lines (43 loc) · 1.09 KB
/
optimize-find-dups.txt
File metadata and controls
60 lines (43 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
Name:
Optimize: Find duplicates
Question:
The given function returns a list of duplicate elements in the input
list. Optimize this function so that it works on any 10-element sorted
list by executing less than 50 instructions.
Hint:
Think about iterating through the list only once.
Solution:
Use a set to check for duplicates.
MaxInstructions: 50
Skeleton:
def findDups(lst):
dups = set()
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j]:
dups.add(lst[i])
return dups
// sample solution:
// def findDups(lst):
// seen = set()
// dups = set()
// for e in lst:
// if e in seen:
// dups.add(e)
// seen.add(e)
// return dups
Test:
input = ['a', 'b', 'c', 'a', 'd', 'c', 'e', 'f', 'g', 'f']
result = findDups(input)
Expect:
result = set(['a', 'c', 'f'])
Test:
input = ['a', 'b', 'xxx', 'c', 'd', 'e', 'f', 'g', 'h', 'xxx']
result = findDups(input)
Expect:
result = set(['xxx'])
Test:
input = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
result = findDups(input)
Expect:
result = set()