Problem No 17
Find the intersection and union of two sets
Medium≈ 16 minute session
Lesson guide
What this Python exercise practices
Find the intersection and union of two sets is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 16 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 16 minutes
Practice path
Summary
Compute the intersection and union of two collections, returning sorted lists for deterministic output.
Problem statement
Given two iterables (e.g., lists or sets) of hashable items, compute their intersection and union. Return a tuple (intersection_list, union_list) where both lists are sorted in ascending order. Duplicate items in input should be ignored because sets only contain unique elements. Sorting ensures deterministic output for tests and users.
Task
Write a function that accepts two iterables, computes their set intersection and union, and returns both as sorted lists.
Examples
Intersection and union of small sets
Input
set_intersection_union({1, 2, 3}, {2, 3, 4})
Output
([2, 3], [1, 2, 3, 4])
Explanation
Intersection is {2,3} and union is {1,2,3,4}, returned as sorted lists.
Input format
Two iterables containing hashable items (e.g., lists, sets, tuples).
Output format
A tuple of two lists: (sorted_intersection, sorted_union).
Constraints
Do not assume inputs are sets; convert them to sets first. Sorting should use the default order for the item types (numbers or strings).
Samples
Sample input 0
set_intersection_union([3, 1, 2], [2, 4])
Sample output 0
([2], [1, 2, 3, 4])
Explanation 0
Duplicates removed; intersection [2], union [1,2,3,4].
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.