Skip to content

Commit be8edb0

Browse files
committed
i0common_items.py
1 parent eed39e9 commit be8edb0

1 file changed

Lines changed: 42 additions & 1 deletion

File tree

Software Architecture with Python/4Performance/i0common_items.py

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,45 @@
33
from time import process_time as timer_func, sleep
44
from contextlib import contextmanager
55

6-
a1, a2 = [], []
6+
a1, a2 = [], []
7+
8+
def setup(n):
9+
global a1, a2
10+
a1 = random.sample(range(0, 2*n), n)
11+
a2 = random.sample(range(0, 2*n), n)
12+
13+
contextmanager
14+
def timer():
15+
try:
16+
start = timer_func()
17+
yield
18+
except Exception as e:
19+
print(e)
20+
raise
21+
finally:
22+
end = timer_func()
23+
print('time spent => ', 1000.0* (end - start), 'ms.')
24+
25+
26+
def common_items_v1(seq1, seq2):
27+
""" Find common items between two sequences - version #1 """
28+
29+
common = []
30+
for item in seq1:
31+
if item in seq2:
32+
common.append(item)
33+
34+
return common
35+
36+
def common_items_v2(seq1, seq2):
37+
""" Find common items between two sequences - optimized version (v2) """
38+
39+
# return set(seq1).intersection(set(seq2))
40+
seq_dict1 = {item:1 for item in seq1}
41+
for item in seq2:
42+
try:
43+
seq_dict1[item] += 1
44+
except KeyError:
45+
pass
46+
47+
return [item[0] for item in seq_dict1.items() if item[1]>1]

0 commit comments

Comments
 (0)