In: Computer Science
The intersection (∩) of two sets (s1, s2) is the set of all elements that are in s1 and are also in s2. Write a function (intersect) that takes two lists as input (you can assume they have no duplicate elements), and returns the intersection of those two sets (as a list) without using the in operator or any built-in functions, except for range() and len(). Write some code to test your function, as well.
Note: Do not use the in operator for this assignment. The keyword in used in for loops (e.g. for x in list) is allowed, as that is not the same as using the in operator. The following code, which uses the in operator, would not be permitted, since it makes this question too easy:
if elem in set2:
# do something
Sample Output for Part 1:
>>> intersect([1,3,5,7,9,11,13,15,17,19,21,23,25], [1,4,9,16,25]) [1, 9, 25]
def intersect(list1,list2):
list3=[]
for i in list1:#check for each number in 1st list
k=0
while k<len(list2) and list2[k]!=i:#go through list2 untill we
find element i or end is reached
k+=1
if k!=len(list2):#if we find an element in both lists
m=0
while m<len(list3) and list3[m]!=i:#check if the element is not
already in intersection list
m+=1
if m==len(list3):#add to list if it is not already in
list3.append(i)
return list3