The intersection n of two sets s1 s2 is the set of all eleme

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. 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

import java.util.*;
public class Intersect {
public static void main(String args[])
{
   List<Integer> s1 = new ArrayList<Integer>();
   List<Integer> s2 = new ArrayList<Integer>();
   s1.add(5);
   s1.add(6);
   s1.add(7);
   s2.add(3);
   s2.add(4);
   s2.add(5);
   Intersect ob=new Intersect();
   List<Integer> result = new ArrayList<Integer>();
   result=ob.commonElements(s1,s2);
   if (result.isEmpty())
   {
       System.out.println(\"Intersection set is empty\");
   }
   else
   {
       System.out.println(\"Intersection set : \"+result);
   }
  
}
public List<Integer> commonElements(List<Integer> list1,List<Integer> list2)
{
   List<Integer> intersection = new ArrayList<Integer>(list1);
   intersection.retainAll(list2);
   return intersection;
}
}

 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 in

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site