Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Python Set

collection of the unordered items ,unique,immutable,ets remove the duplicate elements
Each element in the set must be unique, immutable but Sets are mutable itself
set enclosing with curly braces {}
looping through the set elements in set to display its element
Adding items to the set
add multiple elements to the set using update()
Removing items from the set using discard() and remove() and pop()
remove all the items from the set
difference between discard() and remove()
Python Set Operations
(i)print(Days1|Days2)
(ii)print(Days1.union(Days2))

intersection_update() method
(i)Intersection==print(Days1&Days2)||set1.intersection(set2)
Difference between the two sets
(i)print(Days1-Days2)
Symmetric Difference of two sets
(i)a^b
Write a program to remove the given number from the set.
Write a program to add multiple elements to the set
Write a program to find the union between two set.
Write a program to find the intersection between two sets.
create a set using insert fun

Python Set
A Python set is the collection of the unordered items. Each element in the set must be unique, immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its creation.

Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together, or we can get the list of elements by looping through the set.

Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also provides the set() method, which can be used to create the set by the passed sequence.

Example 1: Using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}    
print(Days)    
print(type(Days))    
print("looping through the set elements ... ")    
for i in Days:    
    print(i)  
Enter fullscreen mode Exit fullscreen mode

Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ... 
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Enter fullscreen mode Exit fullscreen mode
Example 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])    
print(Days)    
print(type(Days))    
print("looping through the set elements ... ")    
for i in Days:    
    print(i) 
Enter fullscreen mode Exit fullscreen mode

Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ... 


Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
Enter fullscreen mode Exit fullscreen mode

Adding items to the set
Python provides the add() method and update() method which can be used to add some particular item to the set. The add() method is used to add a single element whereas the update() method is used to add multiple elements to the set. Consider the following example.

Example: 1 - Using add() method
Months = set(["January","February", "March", "April", "May", "June"])    
print("\nprinting the original set ... ")    
print(months)    
print("\nAdding other months to the set...");    
Months.add("July");    
Months.add ("August");    
print("\nPrinting the modified set...");    
print(Months)    
print("\nlooping through the set elements ... ")    
for i in Months:    
    print(i) 
Enter fullscreen mode Exit fullscreen mode

Output:

printing the original set ... 
{'February', 'May', 'April', 'March', 'June', 'January'}

Adding other months to the set...

Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

looping through the set elements ... 
February
July
May
April
March
August
June
January 
Enter fullscreen mode Exit fullscreen mode

To add more than one item in the set, Python provides the update() method. It accepts iterable as an argument.

Consider the following example.

Example - 2 Using update() function
Months = set(["January","February", "March", "April", "May", "June"])    
print("\nprinting the original set ... ")    
print(Months)    
print("\nupdating the original set ... ")    
Months.update(["July","August","September","October"]);    
print("\nprinting the modified set ... ")     
print(Months); 
Enter fullscreen mode Exit fullscreen mode

Output:

printing the original set ... 
{'January', 'February', 'April', 'May', 'June', 'March'}

updating the original set ... 
printing the modified set ... 
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Enter fullscreen mode Exit fullscreen mode

Removing items from the set
Python provides the discard() method and remove() method which can be used to remove the items from the set. The difference between these function, using discard() function if the item does not exist in the set then the set remain unchanged whereas remove() method will through an error.

Consider the following example.

Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])    
print("\nprinting the original set ... ")    
print(months)    
print("\nRemoving some months from the set...");    
months.discard("January");    
months.discard("May");    
print("\nPrinting the modified set...");    
print(months)    
print("\nlooping through the set elements ... ")    
for i in months:    
    print(i) 
Enter fullscreen mode Exit fullscreen mode

Output:

printing the original set ... 
{'February', 'January', 'March', 'April', 'June', 'May'}

Removing some months from the set...

Printing the modified set...
{'February', 'March', 'April', 'June'}

looping through the set elements ... 
February
March
April
June
Enter fullscreen mode Exit fullscreen mode

Python provides also the remove() method to remove the item from the set. Consider the following example to remove the items using remove() method.

Example-2 Using remove() function
months = set(["January","February", "March", "April", "May", "June"])    
print("\nprinting the original set ... ")    
print(months)    
print("\nRemoving some months from the set...");    
months.remove("January");    
months.remove("May");    
print("\nPrinting the modified set...");    
print(months)  
Enter fullscreen mode Exit fullscreen mode

Output:

printing the original set ... 
{'February', 'June', 'April', 'May', 'January', 'March'}

Removing some months from the set...

Printing the modified set...
{'February', 'June', 'April', 'March'}
Enter fullscreen mode Exit fullscreen mode

We can also use the pop() method to remove the item. Generally, the pop() method will always remove the last item but the set is unordered, we can't determine which element will be popped from set.

Consider the following example to remove the item from the set using pop() method.

Months = set(["January","February", "March", "April", "May", "June"])    
print("\nprinting the original set ... ")    
print(Months)    
print("\nRemoving some months from the set...");    
Months.pop();    
Months.pop();    
print("\nPrinting the modified set...");    
print(Months)  
Enter fullscreen mode Exit fullscreen mode

Output:

printing the original set ... 
{'June', 'January', 'May', 'April', 'February', 'March'}

Removing some months from the set...

Printing the modified set...
{'May', 'April', 'February', 'March'}
Enter fullscreen mode Exit fullscreen mode

In the above code, the last element of the Month set is March but the pop() method removed the June and January because the set is unordered and the pop() method could not determine the last element of the set.

Python provides the clear() method to remove all the items from the set.

Consider the following example.

Months = set(["January","February", "March", "April", "May", "June"])    
print("\nprinting the original set ... ")    
print(Months)    
print("\nRemoving all the items from the set...");    
Months.clear()    
print("\nPrinting the modified set...")    
print(Months)  
Enter fullscreen mode Exit fullscreen mode

Output:

printing the original set ... 
{'January', 'May', 'June', 'April', 'March', 'February'}

Removing all the items from the set...

Printing the modified set...
set()
Enter fullscreen mode Exit fullscreen mode

Difference between discard() and remove()
Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove().

If the key to be deleted from the set using discard() doesn't exist in the set, the Python will not give the error. The program maintains its control flow.

On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the Python will raise an error.

Consider the following example.

Example-

Months = set(["January","February", "March", "April", "May", "June"])    
print("\nprinting the original set ... ")    
print(Months)    
print("\nRemoving items through discard() method...");    
Months.discard("Feb"); #will not give an error although the key feb is not available in the set    
print("\nprinting the modified set...")    
print(Months)    
print("\nRemoving items through remove() method...");    
Months.remove("Jan") #will give an error as the key jan is not available in the set.     
print("\nPrinting the modified set...")    
print(Months) 
Enter fullscreen mode Exit fullscreen mode

Output:

printing the original set ... 
{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through discard() method...

printing the modified set...
{'March', 'January', 'April', 'June', 'February', 'May'}
Enter fullscreen mode Exit fullscreen mode

Removing items through remove() method...
Traceback (most recent call last):
File "set.py", line 9, in
Months.remove("Jan")
KeyError: 'Jan'
Python Set Operations
Set can be performed mathematical operation such as union, intersection, difference, and symmetric difference. Python provides the facility to carry out these operations with operators or methods. We describe these operations as follows.

Union of two Sets
The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all the items that are present in both the sets.

Image description

Python Set
Consider the following example to calculate the union of two sets.

Example 1: using union | operator

Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}    
Days2 = {"Friday","Saturday","Sunday"}    
print(Days1|Days2) #printing the union of the sets  
Enter fullscreen mode Exit fullscreen mode

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}
Enter fullscreen mode Exit fullscreen mode

Python also provides the union() method which can also be used to calculate the union of two sets. Consider the following example.

Example 2: using union() method

Days1 = {"Monday","Tuesday","Wednesday","Thursday"}    
Days2 = {"Friday","Saturday","Sunday"} 


print(Days1.union(Days2)) #printing the union of the sets    
Enter fullscreen mode Exit fullscreen mode

Output:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}
Enter fullscreen mode Exit fullscreen mode

Intersection of two sets
The intersection of two sets can be performed by the and & operator or the intersection() function. The intersection of the two sets is given as the set of the elements that common in both sets.

Image description

Python Set
Consider the following example.

Example 1: Using & operator

Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}    
Days2 = {"Monday","Tuesday","Sunday", "Friday"}    
print(Days1&Days2)
Enter fullscreen mode Exit fullscreen mode

#prints the intersection of the two sets

Output:

{'Monday', 'Tuesday'}
Enter fullscreen mode Exit fullscreen mode

Example 2: Using intersection() method

set1 = {"Devansh","John", "David", "Martin"}    
set2 = {"Steve", "Milan", "David", "Martin"}    
print(set1.intersection(set2)) #prints the intersection of the two sets  
Enter fullscreen mode Exit fullscreen mode

Output:

{'Martin', 'David'}
Example 3:

set1 = {1,2,3,4,5,6,7}  
set2 = {1,2,20,32,5,9}  
set3 = set1.intersection(set2)  
print(set3) 
Enter fullscreen mode Exit fullscreen mode

Output:

{1,2,5}
Enter fullscreen mode Exit fullscreen mode

The intersection_update() method
The intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified).

The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items, on the other hand, the intersection() method returns a new set.

Consider the following example.

a = {"Devansh", "bob", "castle"}    
b = {"castle", "dude", "emyway"}    
c = {"fuson", "gaurav", "castle"}    

a.intersection_update(b, c)    

print(a) 
Enter fullscreen mode Exit fullscreen mode

Output:

{'castle'}
Enter fullscreen mode Exit fullscreen mode

Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that element of A, which is not present in the set B.

Python Set
Consider the following example.

Image description

Example 1 : Using subtraction ( - ) operator

Days1 = {"Monday",  "Tuesday", "Wednesday", "Thursday"}    
Days2 = {"Monday", "Tuesday", "Sunday"}    
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}   
Enter fullscreen mode Exit fullscreen mode

Output:

{'Thursday', 'Wednesday'}
Example 2 : Using difference() method

Days1 = {"Monday",  "Tuesday", "Wednesday", "Thursday"}    
Days2 = {"Monday", "Tuesday", "Sunday"}    
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2 
Enter fullscreen mode Exit fullscreen mode

Output:

{'Thursday', 'Wednesday'}
Enter fullscreen mode Exit fullscreen mode

Symmetric Difference of two sets
The symmetric difference of two sets is calculated by ^ operator or symmetric_difference() method. Symmetric difference of sets, it removes that element which is present in both sets. Consider the following example:

Image description

Python Set
Example - 1: Using ^ operator

a = {1,2,3,4,5,6}  
b = {1,2,9,8,10}  
c = a^b  
print(c) 
Enter fullscreen mode Exit fullscreen mode

Output:

{3, 4, 5, 6, 8, 9, 10}
Enter fullscreen mode Exit fullscreen mode

Example - 2: Using symmetric_difference() method

a = {1,2,3,4,5,6}  
b = {1,2,9,8,10}  
c = a.symmetric_difference(b)  
print(c) 
Enter fullscreen mode Exit fullscreen mode

Output:

{3, 4, 5, 6, 8, 9, 10}
Enter fullscreen mode Exit fullscreen mode

Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is returned depending upon the items present inside the sets.

Consider the following example.

Days1 = {"Monday",  "Tuesday", "Wednesday", "Thursday"}    
Days2 = {"Monday", "Tuesday"}    
Days3 = {"Monday", "Tuesday", "Friday"} 
Enter fullscreen mode Exit fullscreen mode
Days1 is the superset of Days2 hence it will print true.     
print (Days1>Days2) 
Enter fullscreen mode Exit fullscreen mode
prints false since Days1 is not the subset of Days2     
print (Days1<Days2) 
Enter fullscreen mode Exit fullscreen mode
prints false since Days2 and Days3 are not equivalent     
print (Days2 == Days3) 
Enter fullscreen mode Exit fullscreen mode

Output:

True
False
False
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Set Programming Example
Example - 1: Write a program to remove the given number from the set.

my_set = {1,2,3,4,5,6,12,24}  
n = int(input("Enter the number you want to remove"))  
my_set.discard(n)  
print("After Removing:",my_set)  
Enter fullscreen mode Exit fullscreen mode

Output:

Enter the number you want to remove:12
After Removing: {1, 2, 3, 4, 5, 6, 24}
Enter fullscreen mode Exit fullscreen mode

Example - 2: Write a program to add multiple elements to the set.

set1 = set([1,2,4,"John","CS"])  
set1.update(["Apple","Mango","Grapes"])  
print(set1) 
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'}
Enter fullscreen mode Exit fullscreen mode

Example - 3: Write a program to find the union between two set.

set1 = set(["Peter","Joseph", 65,59,96])  
set2  = set(["Peter",1,2,"Joseph"])  
set3 = set1.union(set2)  
print(set3) 
Enter fullscreen mode Exit fullscreen mode

Output:

{96, 65, 2, 'Joseph', 1, 'Peter', 59}
Enter fullscreen mode Exit fullscreen mode

Example- 4: Write a program to find the intersection between two sets.

set1 = {23,44,56,67,90,45,"Javatpoint"}  
set2 = {13,23,56,76,"Sachin"}  
set3 = set1.intersection(set2)  
print(set3) 
Enter fullscreen mode Exit fullscreen mode

Output:

{56, 23}
Enter fullscreen mode Exit fullscreen mode

Adding items in middile of to the set in python

create a set

my_set = {1, 2, 3, 5}

# convert the set into a list
my_list = list(my_set)

# insert the element 4 at index 3
my_list.insert(3, 4)

# convert the list back into a set
my_set = set(my_list)

print(my_set)  # Output: {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode
# create a set
my_set = {2, 3, 4, 5}

# convert the set into a list
my_list = list(my_set)

# insert the element 1 at index 0
my_list.insert(0, 1)

# convert the list back into a set
my_set = set(my_list)

print(my_set)  # Output: {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode
# create a set
my_set = {1, 2, 3, 4}

# convert the set into a list
my_list = list(my_set)

# insert the element 5 at the end of the list
my_list.append(5)

# convert the list back into a set
my_set = set(my_list)

print(my_set)  # Output: {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

============================================================

Set question

  1. Create an empty set and add integers 1 to 5 to it.
  2. Given two sets, find their union.
  3. Create a set of unique names and check if a specific name is present.
  4. Find the intersection of two sets containing numbers.
  5. Remove an element from a set and handle the case if the element is not present.
  6. Given a set of fruits, add a new fruit to it.
  7. Check if two sets are disjoint (have no common elements).
  8. Write a function to remove duplicates from a list using a set.
  9. Create a set of prime numbers and find the maximum and minimum values.
  10. Given a set of colors, find the length of the set.
  11. Write a function to create a set containing the unique characters from a string.
  12. Find the symmetric difference between two sets of numbers.
  13. Remove all elements from a set and print the empty set.
  14. Create a set of integers and find the sum of its elements.
  15. Write a function to check if a given set is a subset of another set.
  16. Find the difference between two sets containing letters.
  17. Write a function to check if a given string contains all unique characters.
  18. Create a set of odd numbers and find the largest value.
  19. Given a set of countries, add a new country and update an existing one.
  20. Check if a specific element is a member of a set and print the result.
  21. Write a function to remove common elements from two sets.
  22. Create a set of integers and find the sum and product of its elements.
  23. Given two sets of words, find their common words.
  24. Write a function to remove vowels from a string using a set.
  25. Find the length of the longest consecutive sequence in a set of numbers.
  26. Create a set of mixed data types and iterate through its elements.
  27. Write a function to check if two sets are equal.
  28. Find the union of multiple sets.
  29. Given a set of elements, create its power set (all possible subsets).
  30. Write a function to find the difference between two sets, considering only the unique elements
# Task 1: Create an empty set and add integers 1 to 5 to it.
empty_set = set()
for i in range(1, 6):
    empty_set.add(i)
print("Task 1 - Set with Integers 1 to 5:", empty_set)

# Task 2: Given two sets, find their union.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
union_set = set1.union(set2)
print("Task 2 - Union of Sets:", union_set)

# Task 3: Create a set of unique names and check if a specific name is present.
unique_names = {"Alice", "Bob", "Charlie", "David", "Eve"}
specific_name = "Alice"
is_present = specific_name in unique_names
print("Task 3 - Is '{}' Present in Unique Names Set: {}".format(specific_name, is_present))

# Task 4: Find the intersection of two sets containing numbers.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection_set = set1.intersection(set2)
print("Task 4 - Intersection of Sets:", intersection_set)

# Task 5: Remove an element from a set and handle the case if the element is not present.
fruits_set = {"apple", "banana", "cherry"}
element_to_remove = "banana"
if element_to_remove in fruits_set:
    fruits_set.remove(element_to_remove)
else:
    print("Task 5 - Element '{}' not found in set.".format(element_to_remove))
print("Task 5 - Updated Fruits Set:", fruits_set)

# Task 6: Given a set of fruits, add a new fruit to it.
fruits_set = {"apple", "banana", "cherry"}
new_fruit = "date"
fruits_set.add(new_fruit)
print("Task 6 - Updated Fruits Set:", fruits_set)

# Task 7: Check if two sets are disjoint (have no common elements).
set1 = {1, 2, 3}
set2 = {4, 5, 6}
are_disjoint = set1.isdisjoint(set2)
print("Task 7 - Are Sets Disjoint:", are_disjoint)

# Task 8: Write a function to remove duplicates from a list using a set.
def remove_duplicates(input_list):
    return list(set(input_list))

original_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = remove_duplicates(original_list)
print("Task 8 - Unique List:", unique_list)

# Task 9: Create a set of prime numbers and find the maximum and minimum values.
prime_numbers = {2, 3, 5, 7, 11}
max_value = max(prime_numbers)
min_value = min(prime_numbers)
print("Task 9 - Max Value:", max_value)
print("Task 9 - Min Value:", min_value)

# Task 10: Given a set of colors, find the length of the set.
colors_set = {"red", "green", "blue", "yellow"}
set_length = len(colors_set)
print("Task 10 - Length of Colors Set:", set_length)

# Task 11: Write a function to create a set containing the unique characters from a string.
def unique_characters(input_string):
    return set(input_string)

input_string = "programming"
unique_chars_set = unique_characters(input_string)
print("Task 11 - Unique Characters Set:", unique_chars_set)
Enter fullscreen mode Exit fullscreen mode

output

Task 1 - Set with Integers 1 to 5: {1, 2, 3, 4, 5}
Task 2 - Union of Sets: {1, 2, 3, 4, 5, 6, 7, 8}
Task 3 - Is 'Alice' Present in Unique Names Set: True
Task 4 - Intersection of Sets: {4, 5}
Task 5 - Updated Fruits Set: {'cherry', 'apple'}
Task 6 - Updated Fruits Set: {'date', 'banana', 'cherry', 'apple'}
Task 7 - Are Sets Disjoint: True
Task 8 - Unique List: [1, 2, 3, 4, 5]
Task 9 - Max Value: 11
Task 9 - Min Value: 2
Task 10 - Length of Colors Set: 4
Task 11 - Unique Characters Set: {'g', 'a', 'm', 'p', 'i', 'o', 'r', 'n'}

Enter fullscreen mode Exit fullscreen mode
# Task 12: Find the symmetric difference between two sets of numbers.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
symmetric_difference = set1.symmetric_difference(set2)
print("Task 12 - Symmetric Difference:", symmetric_difference)

# Task 13: Remove all elements from a set and print the empty set.
empty_set = set()
print("Task 13 - Empty Set:", empty_set)

# Task 14: Create a set of integers and find the sum of its elements.
integers_set = {1, 2, 3, 4, 5}
sum_of_elements = sum(integers_set)
print("Task 14 - Sum of Elements in Integers Set:", sum_of_elements)

# Task 15: Write a function to check if a given set is a subset of another set.
def is_subset(subset, superset):
    return subset.issubset(superset)

set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
is_subset_result = is_subset(set1, set2)
print("Task 15 - Is Set1 a Subset of Set2:", is_subset_result)

# Task 16: Find the difference between two sets containing letters.
set1 = {'a', 'b', 'c', 'd', 'e'}
set2 = {'c', 'd', 'e', 'f', 'g'}
difference_set = set1.difference(set2)
print("Task 16 - Difference Between Sets:", difference_set)

# Task 17: Write a function to check if a given string contains all unique characters.
def has_unique_characters(input_string):
    return len(set(input_string)) == len(input_string)

input_string = "programming"
has_unique_result = has_unique_characters(input_string)
print("Task 17 - Does '{}' Contain Unique Characters: {}".format(input_string, has_unique_result))

# Task 18: Create a set of odd numbers and find the largest value.
odd_numbers_set = {1, 3, 5, 7, 9}
largest_value = max(odd_numbers_set)
print("Task 18 - Largest Value in Odd Numbers Set:", largest_value)

# Task 19: Given a set of countries, add a new country and update an existing one.
countries_set = {"USA", "Canada", "Mexico"}
countries_set.add("Brazil")
countries_set.update(["Canada", "Argentina"])
print("Task 19 - Updated Countries Set:", countries_set)

# Task 20: Check if a specific element is a member of a set and print the result.
fruits_set = {"apple", "banana", "cherry"}
specific_fruit = "banana"
is_member = specific_fruit in fruits_set
print("Task 20 - Is '{}' a Member of Fruits Set: {}".format(specific_fruit, is_member))

# Task 21: Write a function to remove common elements from two sets.
def remove_common_elements(set1, set2):
    return set1.difference(set2), set2.difference(set1)

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1_result, set2_result = remove_common_elements(set1, set2)
print("Task 21 - Set1 Result:", set1_result)
print("Task 21 - Set2 Result:", set2_result)

# Task 22: Create a set of integers and find the sum and product of its elements.
integers_set = {1, 2, 3, 4, 5}
sum_of_elements = sum(integers_set)
product_of_elements = 1
for element in integers_set:
    product_of_elements *= element
print("Task 22 - Sum of Elements:", sum_of_elements)
print("Task 22 - Product of Elements:", product_of_elements)

# Task 23: Given two sets of words, find their common words.
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "elderberry"}
common_words = set1.intersection(set2)
print("Task 23 - Common Words:", common_words)

# Task 24: Write a function to remove vowels from a string using a set.
def remove_vowels(input_string):
    vowels = "aeiouAEIOU"
    return ''.join(char for char in input_string if char not in vowels)

input_string = "programming"
no_vowels_string = remove_vowels(input_string)
print("Task 24 - String with Vowels Removed:", no_vowels_string)

# Task 25: Find the length of the longest consecutive sequence in a set of numbers.
numbers_set = {1, 2, 4, 5, 6, 8, 9}
sorted_numbers = sorted(numbers_set)
max_consecutive_length = 0
current_length = 1
for i in range(1, len(sorted_numbers)):
    if sorted_numbers[i] == sorted_numbers[i - 1] + 1:
        current_length += 1
    else:
        max_consecutive_length = max(max_consecutive_length, current_length)
        current_length = 1
max_consecutive_length = max(max_consecutive_length, current_length)
print("Task 25 - Length of Longest Consecutive Sequence:", max_consecutive_length)

# Task 26: Create a set of mixed data types and iterate through its elements.
mixed_set = {1, "apple", 3.14, (4, 5)}
for element in mixed_set:
    print("Task 26 - Set Element:", element)

# Task 27: Write a function to check if two sets are equal.
def are_sets_equal(set1, set2):
    return set1 == set2

set1 = {1, 2, 3}
set2 =
{3, 2, 1}
are_equal = are_sets_equal(set1, set2)
print("Task 27 - Are Sets Equal:", are_equal)

# Task 28: Find the union of multiple sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {5, 6, 7}
union_result = set1.union(set2, set3)
print("Task 28 - Union of Sets:", union_result)

# Task 29: Given a set of elements, create its power set (all possible subsets).
def powerset(input_set):
    from itertools import chain, combinations
    input_list = list(input_set)
    return list(chain.from_iterable(combinations(input_list, r) for r in range(len(input_list)+1)))

input_set = {1, 2, 3}
power_set = powerset(input_set)
print("Task 29 - Power Set:", power_set)

# Task 30: Write a function to find the difference between two sets, considering only the unique elements.
def unique_difference(set1, set2):
    return set1.symmetric_difference(set2)

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
unique_diff = unique_difference(set1, set2)
print("Task 30 - Unique Difference Between Sets:", unique_diff)

Enter fullscreen mode Exit fullscreen mode

output

Task 12 - Symmetric Difference: {1, 2, 3, 6, 7, 8}
Task 13 - Empty Set: set()
Task 14 - Sum of Elements in Integers Set: 15
Task 15 - Is Set1 a Subset of Set2: True
Task 16 - Difference Between Sets: {'b', 'a'}
Task 17 - Does 'programming' Contain Unique Characters: False
Task 18 - Largest Value in Odd Numbers Set: 9
Task 19 - Updated Countries Set: {'USA', 'Argentina', 'Canada', 'Mexico', 'Brazil'}
Task 20 - Is 'banana' a Member of Fruits Set: True
Task 21 - Set1 Result: {1, 2, 3}, Set2 Result: {8, 6, 7}
Task 22 - Sum of Elements: 15, Product of Elements: 120
Task 23 - Common Words: {'banana'}
Task 24 - String with Vowels Removed: prgrmmng
Task 25 - Length of Longest Consecutive Sequence: 3
Task 26 - Set Element: 1, Set Element: apple, Set Element: 3.14, Set Element: (4, 5)
Task 27 - Are Sets Equal: True
Task 28 - Union of Sets: {1, 2, 3, 4, 5, 6, 7}
Task 29 - Power Set: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Task 30 - Unique Difference Between Sets: {1, 2, 3, 6, 7, 8}
Enter fullscreen mode Exit fullscreen mode

Good question with sets

Create an empty set and add integers 1 to 5 to it..
Write a function to remove vowels from a string using a set.
Write a function to check if a given string contains all unique characters..
Write a function to remove common elements from two sets.

Top comments (0)