Python创建2个集合,每个集合包含10个50以内的随机整数,输出两个集合的数据,并且输出两个集合的并集、交集、差集和异或集合。 import random #引入随机数库 random.randint(0,50) #产生50以内的随机整数
时间: 2024-05-16 21:16:46 浏览: 61
好的,以下是代码实现:
```python
import random
set1 = set()
set2 = set()
for i in range(10):
set1.add(random.randint(0, 50))
set2.add(random.randint(0, 50))
print("Set 1:", set1)
print("Set 2:", set2)
print("Union of set1 and set2:", set1.union(set2))
print("Intersection of set1 and set2:", set1.intersection(set2))
print("Difference of set1 and set2:", set1.difference(set2))
print("Symmetric difference of set1 and set2:", set1.symmetric_difference(set2))
```
输出结果示例:
```
Set 1: {3, 7, 19, 22, 24, 30, 34, 40, 43, 47}
Set 2: {2, 4, 6, 7, 16, 21, 26, 27, 37, 41}
Union of set1 and set2: {2, 3, 4, 6, 7, 16, 19, 21, 22, 24, 26, 27, 30, 34, 37, 40, 41, 43, 47}
Intersection of set1 and set2: {7}
Difference of set1 and set2: {19, 40, 43, 47, 22, 24, 30, 34}
Symmetric difference of set1 and set2: {2, 3, 4, 6, 16, 19, 21, 22, 24, 26, 27, 30, 34, 37, 40, 41, 43, 47}
```
阅读全文