Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The intersection (n) of two sets (s1, s2) is the set of all elements that are in

ID: 3929318 • Letter: T

Question

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]

Explanation / Answer

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;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote