编制一个能演示集合的交,并和差的运算的程序。要求能演示程序以用户和计算机的对话方式执行,集合的元素自行定义。
时间: 2024-03-20 17:39:55 浏览: 23
好的,我可以帮你编写一个程序来演示集合的交、并和差的运算。以下是程序的代码:
```python
def intersection(set1, set2):
"""求两个集合的交"""
return set1 & set2
def union(set1, set2):
"""求两个集合的并"""
return set1 | set2
def difference(set1, set2):
"""求两个集合的差"""
return set1 - set2
def main():
"""程序入口"""
print("欢迎使用集合运算演示程序!")
while True:
print("请输入第一个集合的元素,多个元素用空格隔开:")
input1 = input().split()
set1 = set(input1)
print("第一个集合为:", set1)
print("请输入第二个集合的元素,多个元素用空格隔开:")
input2 = input().split()
set2 = set(input2)
print("第二个集合为:", set2)
print("请选择要进行的集合运算:")
print("1. 交 2. 并 3. 差")
choice = input()
if choice == '1':
result = intersection(set1, set2)
print("两个集合的交为:", result)
elif choice == '2':
result = union(set1, set2)
print("两个集合的并为:", result)
elif choice == '3':
result = difference(set1, set2)
print("两个集合的差为:", result)
else:
print("选择错误,请重新输入!")
print("是否继续演示?(y/n)")
ans = input()
if ans == 'n':
break
if __name__ == '__main__':
main()
```
程序的运行方式是,首先提示用户输入第一个集合的元素,然后输入第二个集合的元素,接着让用户选择要进行的集合运算,最后输出运算结果。程序会不断循环,直到用户选择退出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)