20. Problem to check if elements in a set are prime

In this Python set program, we will check whether all elements in a set are prime numbers with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Elements in a set are prime number:

Steps to solve the program

1. Create a set using {}.
2. Add some elements in the set.
3. Create an empty list
4. Use a for loop to iterate over elements in the set.
5. Create a count variable and assign its value equal to 0.
6. Use a nested for loop to iterate over the number from 2 to the loop number.
7. Check whether the loop number is divided by any number from the above loop.
8. If yes then add 1 to the count variable.
9. After the second loop is complete check whether the value of the count variable is equal to 0 for the first loop number.
10. If yes then add that number to the empty list.
11. At the end check whether the length of the list is equal to the length of the set using an if-else statement.
12. If yes then all elements in a set are prime numbers, else not all elements in a set are prime numbers.
13. Print the respective output.

				
					Set = {1,2,3,4,5}
prime = []
print("Original set1: ",Set)
for ele in Set:
    count = 0
    for num in range(2,ele):
        if ele%num == 0:
            count +=1
    if count == 0:
        prime.append(ele)
if len(prime) == len(Set):
    print("All elements in the set are prime numbers")
else:
    print("All elements in the set are not prime number")
				
			

Output :

				
					Original set1:  {1, 2, 3, 4, 5}
All elements in the set are not prime number
				
			

Related Articles

check if all elements in a set are odd.

check if a set is a proper subset of another set.

Leave a Comment