Skip to content

Instantly share code, notes, and snippets.

@ZechCodes
Last active June 20, 2020 01:35
Show Gist options
  • Save ZechCodes/d0b4e2482091524071d45347d22993fb to your computer and use it in GitHub Desktop.
Save ZechCodes/d0b4e2482091524071d45347d22993fb to your computer and use it in GitHub Desktop.
Challenge #33 - Union & Intersection of Lists

Challenge #33 - Union & Intersection of Lists

Create a function takes in two lists and returns an intersection list and a union list.

  • Intersection List: Elements shared by both.
  • Union List: Elements that exist in first or second list, or both (not exclusive OR).

While the input lists may have duplicate numbers, the returned intersection and union lists should be set-ified - that is, contain no duplicates. Returned lists should be sorted in ascending order.

List 1: [5, 6, 6, 6, 8, 9]
List 2: [3, 3, 4, 4, 5, 5, 8]

Intersection: [5, 8]
# 5 and 8 are the only 2 numbers that exist in both lists.

Union: [3, 4, 5, 6, 8, 9]
# Each number exists in at least one list.

Examples

intersection_union([1, 2, 3, 4, 4], [4, 5, 9]) ➞ ([4], [1, 2, 3, 4, 5, 9])

intersection_union([1, 2, 3], [4, 5, 6]) ➞ ([], [1, 2, 3, 4, 5, 6])

intersection_union([1, 1], [1, 1, 1, 1]) ➞ ([1], [1])

Notes

  • Order of output should be: [Intersection], [Union].
  • Remember both output lists should be in ascending order.
  • Each input list will have at least one element.
  • If both lists are disjoint (share nothing in common), return an empty list [] for the intersection.
import unittest
from typing import List, Tuple
def intersection_union(list_a: List[int], list_b: List[int]) -> Tuple[List[int], List[int]]:
return [],[] # Put your code here!
class TestIntersectionUnion(unittest.TestCase):
def test_1(self):
self.assertEqual(intersection_union([1, 2, 3, 4, 4], [4, 5, 9]), ([4], [1, 2, 3, 4, 5, 9]))
def test_2(self):
self.assertEqual(intersection_union([1, 2, 3], [4, 5, 6]), ([], [1, 2, 3, 4, 5, 6]))
def test_3(self):
self.assertEqual(intersection_union([1, 1], [1, 1, 1, 1]), ([1], [1]))
def test_4(self):
self.assertEqual(intersection_union([5, 5], [5, 6]), ([5], [5, 6]))
def test_5(self):
self.assertEqual(intersection_union([7, 8, 9, 6], [9, 7, 6, 8]), ([6, 7, 8, 9], [6, 7, 8, 9]))
def test_6(self):
self.assertEqual(intersection_union([4, 1, 1, 2], [1, 4, 4, 4, 4, 4, 4]), ([1, 4], [1, 2, 4]))
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment