Ex 24: Set Comprehension Challenges
Problem
Sets are powerful for ensuring uniqueness and performing mathematical-style operations. Complete the following four tasks using set comprehensions:
- Vowel Extraction: From a sentence string, collect all unique vowels present.
- Intersection: Given two lists, build a set of values that appear in BOTH (without using the
&operator). - Length Set: From a list of words, build a set containing the unique lengths of those words.
- Prime Filtering: From a list of numbers, build a set of only the prime numbers.
Rules
- For Task 1, use the sentence:
"the quick brown fox jumps over the lazy dog". - For Task 2, use
list_a = [1, 2, 3, 4, 5]andlist_b = [3, 4, 5, 6, 7]. - For Task 3, use:
["cat", "elephant", "dog", "python", "owl", "snake", "rat"]. - For Task 4, use:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13].
Boilerplate
Copy below code and paste to our IDE for head start.
# Task 1: Vowels
sentence = "the quick brown fox jumps over the lazy dog"
unique_vowels = {} # Use a set comprehension
# Task 2: Intersection
list_a = [1, 2, 3, 4, 5]
list_b = [3, 4, 5, 6, 7]
common_elements = {}
# Task 3: Word Lengths
words = ["cat", "elephant", "dog", "python", "owl", "snake", "rat"]
unique_lengths = {}
# Task 4: Primes
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
prime_numbers = {}
Expected output
Note: Set order is not guaranteed, but the values should match.
{'a', 'e', 'i', 'o', 'u'}
{3, 4, 5}
{3, 5, 6, 8}
{2, 3, 5, 7, 11, 13}
Solution
Only view the solution after trying our best.
Show solution
# 1. Vowels
sentence = "the quick brown fox jumps over the lazy dog"
unique_vowels = {char for char in sentence if char in "aeiou"}
# 2. Intersection
list_a = [1, 2, 3, 4, 5]
list_b = [3, 4, 5, 6, 7]
common_elements = {item for item in list_a if item in list_b}
# 3. Word Lengths
words = ["cat", "elephant", "dog", "python", "owl", "snake", "rat"]
unique_lengths = {len(word) for word in words}
# 4. Primes
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
prime_numbers = {
num for num in numbers
if num > 1 and all(num % i != 0 for i in range(2, int(num**0.5) + 1))
}
Details
- Task 2: We simulate a set intersection by iterating through one list and checking for membership in the other within the comprehension.
- Task 4: We use a nested condition
all(...)to check if a number has any divisors other than 1 and itself, ensuring it meets the definition of a prime number.