Python Set Operations Implementation
This challenge focuses on implementing fundamental set operations in Python. Sets are a powerful data structure for managing unique elements and performing mathematical set operations like union, intersection, difference, and symmetric difference. Successfully completing this challenge will solidify your understanding of sets and their utility in various programming scenarios.
Problem Description
You are tasked with creating a module containing functions that implement the following set operations:
union(set1, set2): Returns a new set containing all elements from bothset1andset2.intersection(set1, set2): Returns a new set containing only the elements that are present in bothset1andset2.difference(set1, set2): Returns a new set containing elements that are present inset1but not inset2.symmetric_difference(set1, set2): Returns a new set containing elements that are present in eitherset1orset2, but not in both.
Your functions should accept two sets as input and return a new set as output, leaving the original sets unchanged. The input sets can contain any hashable data types (integers, strings, tuples, etc.). Handle edge cases gracefully, such as empty sets or sets with no common elements.
Examples
Example 1:
Input: set1 = {1, 2, 3}, set2 = {3, 4, 5}
Output: {1, 2, 3, 4, 5}
Explanation: The union of {1, 2, 3} and {3, 4, 5} is {1, 2, 3, 4, 5}.
Example 2:
Input: set1 = {1, 2, 3}, set2 = {4, 5, 6}
Output: set()
Explanation: The intersection of {1, 2, 3} and {4, 5, 6} is an empty set because they have no elements in common.
Example 3:
Input: set1 = {1, 2, 3}, set2 = {2, 3, 4}
Output: {1}
Explanation: The difference between {1, 2, 3} and {2, 3, 4} contains elements in set1 that are not in set2, which is {1}.
Example 4:
Input: set1 = {1, 2, 3}, set2 = {4, 5, 6}
Output: {1, 2, 3, 4, 5, 6}
Explanation: The symmetric difference between {1, 2, 3} and {4, 5, 6} contains elements that are in either set but not both, which is {1, 2, 3, 4, 5, 6}.
Constraints
- Input sets will contain only hashable data types.
- The input sets can be empty.
- The order of elements in the output set is not important.
- The functions should not modify the original input sets.
- The time complexity of each operation should be as efficient as possible, ideally leveraging Python's built-in set operations where appropriate.
Notes
Consider using Python's built-in set operations for efficiency. While you could implement these operations manually using loops and conditional statements, leveraging the built-in functionality will generally result in cleaner and faster code. Focus on creating a well-organized module with clear function definitions and docstrings. Remember to test your functions thoroughly with various inputs, including edge cases.