Python Practice › Set Programs › Program 20

Are all elements prime?

EasySet Programs · 20 of 48

Write a Python program to check whether all elements of a set are prime, and list the primes.

Advertisement
Input
{2, 3, 5, 9}
Output
False [2, 3, 5]

Approach

  1. A prime test for each element.

Solution

Python
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.

More set programs

← All 48 Set Programs

Leave a Comment