Search code examples
pythoncomparison

How to compare two sets to each other?


I'm currently attempting to solve "Question 349 - Intersection of two arrays" on leetcode and was trying to return an array of their intersection. My goal was to make two separate sets that took in the values of each array because I need unique values.

I'm confused as to how I'm supposed to iterate through both sets now to return the elements that match and return that. This is my code and I'm having the issue where it tells me that bool object is not iterable which makes sense:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        set1 = set()
        set2 = set()
        newList = []
        for i in nums1:
            set1.add(i)
        for j in nums2:
            set2.add(j)
        for i in set1 and j in set2:
            if (set1(i) == set2(j)):
                newList.append[i]
        return newList

Solution

  • Use a sets intersection method.

    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:
        set1 = set(nums1)
        set2 = set(nums2)
        result = set1.intersection(set2)
        return list(result)
    

    And this can be shortened to

    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:
        return list(set(nums1).intersection(nums2))
    

    There's no need to iterate over the list manually to create a set. set accepts an iterable as a parameter so using a list is fine.