生成在python求集合的交集,并集,对称差和对称补的代码
时间: 2024-03-23 08:36:42 浏览: 102
Python数组并集交集补集代码实例
下面是Python中求集合的交集、并集、对称差和对称补的代码:
```python
# 定义两个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 求交集
intersection = set1 & set2
print("交集为:", intersection)
# 求并集
union = set1 | set2
print("并集为:", union)
# 求对称差
symmetric_difference = set1 ^ set2
print("对称差为:", symmetric_difference)
# 求对称补
complement = (set1 | set2) - (set1 & set2)
print("对称补为:", complement)
```
输出结果为:
```
交集为: {3, 4}
并集为: {1, 2, 3, 4, 5, 6}
对称差为: {1, 2, 5, 6}
对称补为: {1, 2, 5, 6}
```
阅读全文