This Python code demonstrates operations on sets such as adding and removing elements, union, intersection, difference and symmetric difference of two sets. It first creates an empty set and allows the user to add single and multiple elements. It then discards an element, clears the set and performs set operations on two user-defined sets by taking their union, intersection, difference and symmetric difference.
This Python code demonstrates operations on sets such as adding and removing elements, union, intersection, difference and symmetric difference of two sets. It first creates an empty set and allows the user to add single and multiple elements. It then discards an element, clears the set and performs set operations on two user-defined sets by taking their union, intersection, difference and symmetric difference.
This Python code demonstrates operations on sets such as adding and removing elements, union, intersection, difference and symmetric difference of two sets. It first creates an empty set and allows the user to add single and multiple elements. It then discards an element, clears the set and performs set operations on two user-defined sets by taking their union, intersection, difference and symmetric difference.
add_val = input("Enter a value to add: ") my_set.add(add_val) print("Set after add:", my_set)
# Add multiple elements to the set
add_str = input("Enter comma-separated values to add: ") add_list = add_str.split(",") my_set.update(add_list) print("Set after update:", my_set)
# Discard an element from the set
discard_val = input("Enter a value to discard: ") my_set.discard(discard_val) print("Set after discard:", my_set)
# Clear the set
my_set.clear() print("Set after clear:", my_set)
# Create two sets for set operations
set1_str = input("Enter comma-separated values for set 1: ") set2_str = input("Enter comma-separated values for set 2: ") set1 = set(set1_str.split(",")) set2 = set(set2_str.split(","))
# Union of two sets
union_set = set1.union(set2) print("Union of set1 and set2:", union_set)
# Intersection of two sets
intersection_set = set1.intersection(set2) print("Intersection of set1 and set2:", intersection_set)
# Set difference between two sets
set_diff = set1.difference(set2) print("Set difference of set1 and set2:", set_diff)
# Symmetric difference between two sets
sym_diff = set1.symmetric_difference(set2) print("Symmetric difference of set1 and set2:", sym_diff) Enter a value to add: 2 Set after add: {'2'} Enter comma-separated values to add: 3,4,5,1,6,9 Set after update: {'5', '2', '1', '6', '4', '9', '3'} Enter a value to discard: 1 Set after discard: {'5', '2', '6', '4', '9', '3'} Set after clear: set() Enter comma-separated values for set 1: 2,4,6,8 Enter comma-separated values for set 2: 1,4,2,7 Union of set1 and set2: {'2', '1', '7', '8', '6', '4'} Intersection of set1 and set2: {'4', '2'} Set difference of set1 and set2: {'8', '6'} Symmetric difference of set1 and set2: {'1', '7', '8', '6'}