Question 5 : How to check if there are any common elements in two sets. If yes, print them.
Given Sets:
set1 = {10, 20, 30, 40}
set2 = {20, 30, 40, 50}
Expected Output:
Here is the list of common elements:
{40, 20, 30}
For this, we will use the isdisjoint() method and intersection() method.
set1 = {10, 20, 30, 40}
set2 = {20, 30, 40, 50}
if set1.isdisjoint(set2):
print("Nothing in Common")
else:
print("Here is the list of common elements:")
print(set1.intersection(set2))
Output:
Here is the list of common elements:
{40, 20, 30}
Question 6 : From the given set of names, separate the names that start with j and t and create two new sets.
names = {"Jack", "John", "Tim", "Thomas", "Jim", "Tom" }
j_names = set()
t_names = set()
for n in names:
if n.startswith("J"):
j_names.add(n)
if n.startswith("T"):
t_names.add(n)
print(j_names)
print(t_names)
Output:
{'Jim', 'John', 'Jack'}
{'Tim', 'Thomas', 'Tom'}
Question 7 : In Python, which operator is used to determine that if a set is the subset of another set?
Approach 1 : Using the issubset() method:
s1 = {1,2,3,4,5,6,7,8,9}
s2 = {1,2,3,4}
print(s2.issubset(s1)) #s2 is subset of s1
print(s1.issubset(s2)) #s1 is subset of s2
Approach 2 : Using the < operator:
s1 = {1,2,3,4,5,6,7,8,9}
s2 = {1,2,3,4}
print(s2 < s1) #s2 is subset of s1
print(s1 < s2) #s1 is subset of s2
Output:
True
False
Question 8 : Create an empty “names” set and then add 4 names, rename 1 of them and then remove 2 names from the set.
Solution:
my_set = set()
my_set.add("Steve")
my_set.add("Jeff")
my_set.add("Jack")
my_set.add("Elon")
print("Four elements are :", my_set)
my_set.remove("Steve")
my_set.add("Tim")
print("Elements after modifying one are :", my_set)
my_set.remove("Jeff")
my_set.remove("Elon")
print("Elements after removing two :", my_set)
Output:
Four elements are : {'Jeff', 'Jack', 'Elon', 'Steve'}
Elements after modifying one are : {'Jeff', 'Jack', 'Elon', 'Tim'}
Elements after removing two : {'Jack', 'Tim'}
Question 9 : Create a set of 10 random integers between 10 and 40. Now print the count of numbers less than 20 and remove numbers > 30 from the set.
Solution:
import random
count = 0
s = set()
temp_set = set()
while len(s) < 10:
s.add(random.randint(10,40))
print("Original Set =", s)
for i in s:
if i < 20:
count = count + 1
if i <= 30:
temp_set.add(i)
s = temp_set
print("Items less than 20 =", count)
print("Set after deleting items =", s)
Output:
Original Set = {32, 36, 38, 39, 40, 11, 16, 27, 28, 30}
Items less than 20 = 2
Set after deleting items = {11, 16, 27, 28, 30}