用python写出两个集合的并集 差集(两种情况都要输出,先A- B)、交集和对称差分,并按ASCII码顺序,分行输出
时间: 2023-05-12 16:06:22 浏览: 206
基于python求两个列表的并集.交集.差集
以下是Python代码:
```python
# 定义两个集合
setA = {'a', 'b', 'c', 'd', 'e'}
setB = {'d', 'e', 'f', 'g', 'h'}
# 计算并集
unionSet = setA.union(setB)
# 计算差集
diffSet1 = setA.difference(setB)
diffSet2 = setB.difference(setA)
# 计算交集
intersectSet = setA.intersection(setB)
# 计算对称差分
symDiffSet = setA.symmetric_difference(setB)
# 按ASCII码顺序排序
unionSet = sorted(list(unionSet))
diffSet1 = sorted(list(diffSet1))
diffSet2 = sorted(list(diffSet2))
intersectSet = sorted(list(intersectSet))
symDiffSet = sorted(list(symDiffSet))
# 分行输出
print("并集:")
for i in unionSet:
print(i)
print("")
print("差集(A-B):")
for i in diffSet1:
print(i)
print("")
print("差集(B-A):")
for i in diffSet2:
print(i)
print("")
print("交集:")
for i in intersectSet:
print(i)
print("")
print("对称差分:")
for i in symDiffSet:
print(i)
```
输出结果如下:
```
并集:
a
b
c
d
e
f
g
h
差集(A-B):
a
b
c
差集(B-A):
f
g
h
交集:
d
e
对称差分:
a
b
c
f
g
h
```
阅读全文