-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_common_elements_in_list.py
44 lines (34 loc) · 1.15 KB
/
find_common_elements_in_list.py
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
# Implement your function below.
#Big O(n)
def common_elements(list1, list2):
p1 = 0
p2 = 0
result = []
while p1 < len(list1) and p2 < len(list2):
if list1[p1] == list2[p2]:
result.append(list1[p1])
p1 += 1
p2 += 1
elif list1[p1] > list2[p2]:
p2 += 1
else:
p1 += 1
return result
# NOTE: The following input values will be used for testing your solution.
list_a1 = [1, 3, 4, 6, 7, 9]
list_a2 = [1, 2, 4, 5, 9, 10]
print(common_elements(list_a1,list_a2))
# common_elements(list_a1, list_a2) should return [1, 4, 9] (a list).
list_b1 = [1, 2, 9, 10, 11, 12]
list_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15]
print(common_elements(list_b1,list_b2))
# common_elements(list_b1, list_b2) should return [1, 2, 9, 10, 12] (a list).
list_c1 = [0, 1, 2, 3, 4, 5]
list_c2 = [6, 7, 8, 9, 10, 11]
print(common_elements(list_c1,list_c2))
# common_elements(list_b1, list_b2) should return [] (an empty list).
OR
#Short one using comprehension
def common_elements(list1, list2):
return [element for element in list1 if element in list2]
print(common_elements(list_a1, list_a2))