python编写一个类,实现添加元素(如果存在则不添加),删除元素,弹出元素(pop),集合差集运算,集合并集运算,判断两个集合是否相等,>=运算符重载(集合包含关系),支持内置函数len,清空集合所有元素。
时间: 2024-02-06 20:10:28 浏览: 111
string 类实现,构造函数、析构函数、操作符重载等
下面是一个简单的示例代码:
```python
class MySet:
def __init__(self):
self.elements = []
def add(self, element):
if element not in self.elements:
self.elements.append(element)
def remove(self, element):
if element in self.elements:
self.elements.remove(element)
def pop(self):
if len(self.elements) > 0:
return self.elements.pop()
def difference(self, other_set):
result_set = MySet()
for element in self.elements:
if element not in other_set.elements:
result_set.add(element)
return result_set
def union(self, other_set):
result_set = MySet()
for element in self.elements:
result_set.add(element)
for element in other_set.elements:
result_set.add(element)
return result_set
def __eq__(self, other_set):
if len(self.elements) != len(other_set.elements):
return False
for element in self.elements:
if element not in other_set.elements:
return False
return True
def __ge__(self, other_set):
for element in other_set.elements:
if element not in self.elements:
return False
return True
def __len__(self):
return len(self.elements)
def clear(self):
self.elements = []
```
可以用以下方式测试:
```python
# 创建两个集合
set1 = MySet()
set2 = MySet()
# 添加元素
set1.add(1)
set1.add(2)
set1.add(3)
set2.add(2)
set2.add(3)
set2.add(4)
# 删除元素
set1.remove(2)
# 弹出元素
popped_element = set1.pop()
# 集合差集运算
difference_set = set1.difference(set2)
# 集合并集运算
union_set = set1.union(set2)
# 判断两个集合是否相等
is_equal = set1 == set2
# >=运算符重载(集合包含关系)
is_superset = set1 >= set2
# 支持内置函数len
set_len = len(set1)
# 清空集合所有元素
set1.clear()
```
阅读全文