创建一个函数,接收已读取的两个字符串,返回两个字符串集合的并集,交集,
时间: 2023-05-26 09:06:59 浏览: 106
Python基础从0到1作业练习(共24题)_python习题_
差集和对称差集。函数名为 set_operations。
```python
def set_operations(str1, str2):
set1 = set(str1.split())
set2 = set(str2.split())
union = set1.union(set2)
intersection = set1.intersection(set2)
difference = set1.difference(set2)
symmetric_difference = set1.symmetric_difference(set2)
return {
'union': union,
'intersection': intersection,
'difference': difference,
'symmetric_difference': symmetric_difference
}
```
函数使用示例:
```python
str1 = 'this is a test string'
str2 = 'this is another test string'
result = set_operations(str1, str2)
print(result['union']) # {'this', 'a', 'is', 'test', 'string', 'another'}
print(result['intersection']) # {'this', 'is', 'test', 'string'}
print(result['difference']) # {'a'}
print(result['symmetric_difference']) # {'another', 'a'}
```
阅读全文