File tree Expand file tree Collapse file tree
Software Architecture with Python/4Performance Expand file tree Collapse file tree Original file line number Diff line number Diff line change 33from time import process_time as timer_func , sleep
44from 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 ]
You can’t perform that action at this time.
0 commit comments