用python编写程序,输入俩个集合setA好serB,分别输出他们的交集,并集和差集
时间: 2023-03-28 17:01:40 浏览: 119
您好,我是 CSDN 开发的 C 知道,我可以回答您的问题。对于您的问题,可以使用 Python 编写程序来实现。代码如下:
```python
setA = {1, 2, 3, 4, 5}
setB = {4, 5, 6, 7, 8}
# 求交集
intersection = setA & setB
print("交集:", intersection)
# 求并集
union = setA | setB
print("并集:", union)
# 求差集
difference = setA - setB
print("差集:", difference)
```
希望能够帮助您解决问题。如果您还有其他问题,欢迎继续提问。
相关问题
编写程序,输入俩个集合setA好serB,分别输出他们的交集,并集和差集
您好,我可以回答这个问题。以下是程序的代码:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> setA = {1, 2, 3, 4, 5};
set<int> setB = {3, 4, 5, 6, 7};
// 输出交集
set<int> intersection;
set_intersection(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(intersection, intersection.begin()));
cout << "交集:";
for (auto it = intersection.begin(); it != intersection.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 输出并集
set<int> unionSet;
set_union(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(unionSet, unionSet.begin()));
cout << "并集:";
for (auto it = unionSet.begin(); it != unionSet.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 输出差集
set<int> difference;
set_difference(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(difference, difference.begin()));
cout << "A-B差集:";
for (auto it = difference.begin(); it != difference.end(); ++it) {
cout << *it << " ";
}
cout << endl;
difference.clear();
set_difference(setB.begin(), setB.end(), setA.begin(), setA.end(), inserter(difference, difference.begin()));
cout << "B-A差集:";
for (auto it = difference.begin(); it != difference.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return ;
}