创建2个集合,每个集合包含10个50以内的随机整数,输出两个集合的数据,并且输出两个集合的并集、交集、差集和异或集合。
时间: 2024-05-02 07:17:25 浏览: 10
以下是Python代码实现:
```python
import random
# 创建两个集合
set1 = set(random.sample(range(1, 51), 10))
set2 = set(random.sample(range(1, 51), 10))
# 输出两个集合的数据
print("集合1:", set1)
print("集合2:", set2)
# 输出集合的并集
print("并集:", set1.union(set2))
# 输出集合的交集
print("交集:", set1.intersection(set2))
# 输出集合的差集
print("差集1:", set1.difference(set2))
print("差集2:", set2.difference(set1))
# 输出集合的异或集合
print("异或集合:", set1.symmetric_difference(set2))
```
输出结果类似如下:
```
集合1: {3, 5, 7, 11, 13, 15, 16, 29, 35, 45}
集合2: {1, 2, 5, 11, 12, 13, 23, 25, 28, 38}
并集: {1, 2, 3, 5, 7, 11, 12, 13, 15, 16, 23, 25, 28, 29, 35, 38, 45}
交集: {5, 11, 13}
差集1: {35, 3, 45, 7, 15, 16, 29}
差集2: {1, 2, 38, 25, 12, 23, 28}
异或集合: {1, 2, 3, 7, 12, 15, 16, 23, 25, 28, 29, 35, 38, 45}
```