Python Practice › Set Programs › Program 20
Are all elements prime?
Write a Python program to check whether all elements of a set are prime, and list the primes.
Input
{2, 3, 5, 9}Output
False [2, 3, 5]
Approach
- A prime test for each element.
Solution
def is_prime(n): return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) s = {2, 3, 5, 9}print(all(is_prime(x) for x in s), sorted(x for x in s if is_prime(x)))Output
False [2, 3, 5]
Learn the concept
New to this topic? Read the lesson, then come back.