Using Python The intersection n of two sets s1 s2 is the se

Using Python ..

The intersection (n) 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. 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]

Solution

Python CODE

# Function definition is here
def intersect( set1,set2 ):
   newset = [] # creating a new set to store the interset elements
   for i in set1: # selecting the elements of first list and iterating
       for j in set2: # selecting the elements of second list
           if i == j: # comparing the elements of each list
              newset = newset+[i] # adding the elements to the new set
   print newset # printing the intersection
   return

# Function call
intersect( [1,3,5,7,9,11,13,15,17,19,21,23,25], [1,4,9,16,25] )

OUTPUT

$ python 15884665.py
[1, 9, 25]

Using Python .. The intersection (n) 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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site