Python Frozenset set operations: Union, intersection, difference
Python Frozenset Views Data Type: Exercise-1 with Solution
Write a Python program that performs common set operations like union, intersection, and difference of two frozensets.
Sample Solution:
Code:
def main():
frozenset_x = frozenset([1, 2, 3, 4, 5])
frozenset_y = frozenset([0, 1, 3, 7, 8, 10])
print("Original frozensets:")
print(frozenset_x)
print(frozenset_y)
# Union of frozensets
union_result = frozenset_x.union(frozenset_y)
print("Union of two said frozensets:", union_result)
# Intersection of frozensets
intersection_result = frozenset_x.intersection(frozenset_y)
print("Intersection of two said frozensets:", intersection_result)
# Difference of frozensets (elements in frozenset_x but not in frozenset_y)
difference_result1 = frozenset_x.difference(frozenset_y)
# Difference of frozensets (elements in frozenset_y but not in frozenset_x)
difference_result2 = frozenset_y.difference(frozenset_x)
print("Difference of (frozenset_x - frozenset_y)", difference_result1)
print("Difference of (frozenset_y - frozenset_x)", difference_result2)
if __name__ == "__main__":
main()
Output:
Original frozensets: frozenset({1, 2, 3, 4, 5}) frozenset({0, 1, 3, 7, 8, 10}) Union of two said frozensets: frozenset({0, 1, 2, 3, 4, 5, 7, 8, 10}) Intersection of two said frozensets: frozenset({1, 3}) Difference of (frozenset_x - frozenset_y) frozenset({2, 4, 5}) Difference of (frozenset_y - frozenset_x) frozenset({0, 8, 10, 7})
Flowchart:
Previous: Python Extended Data Type Frozenset Views Exercises Home.
Next: Python frozen set and set conversion: Differences and comparisons.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-frozenset-views-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics