s = {"Red", True, 2}
print(s)
Here, the set contains a string, a boolean, and an integer. The program will print output like the following:
{True, 2, 'Red'}
Example
Now, we have learned how to create a set, add elements to a set and perform various set operations on a set. So, let’s try to write a small program from what we have learned.
Let’s say we are given two numbers m and n. We need to find out the common factors of m and n. We can write a program easily using a set. We will first find out all factors or m and n and store them in two different sets factors_m and factors_n. Now, we can perform a set intersection operation to find out all the factors that divide both m and n.
m = 21
n = 15
factors_m = set()
factors_n = set()
for i in range(1, m + 1):
if m % i == 0:
factors_m.add(i)
print("Factors of m are: ")
print(factors_m)
for i in range(1, n + 1):
if n % i == 0:
factors_n.add(i)
print("Factors of m are: ")
print(factors_n)
print("Common factors of m and n are: ")
print(factors_m & factors_n)
The above program will print output like the following:
Factors of m are:
{1, 3, 21, 7}
Factors of m are:
{1, 3, 5, 15}
Common factors of m and n are:
{1, 3}








































0 Comments