编写一个类,实现添加元素(如果存在则不添加),删除元素,弹出元素(pop),集合差集运算,集合并集运算,判断两个集合是否相等,>=运算符重载(集合包含关系),支持内置函数len,清空集合所有元素。
时间: 2024-02-01 10:02:49 浏览: 16
下面是一个实现上述功能的类:
```python
class MySet:
def __init__(self):
self.items = []
def add(self, item):
if item not in self.items:
self.items.append(item)
def remove(self, item):
if item in self.items:
self.items.remove(item)
def pop(self):
if self.items:
return self.items.pop()
else:
return None
def difference(self, other_set):
diff_set = MySet()
for item in self.items:
if item not in other_set.items:
diff_set.add(item)
return diff_set
def union(self, other_set):
union_set = MySet()
for item in self.items:
union_set.add(item)
for item in other_set.items:
union_set.add(item)
return union_set
def __eq__(self, other_set):
if len(self.items) != len(other_set.items):
return False
else:
for item in self.items:
if item not in other_set.items:
return False
return True
def __ge__(self, other_set):
for item in other_set.items:
if item not in self.items:
return False
return True
def __len__(self):
return len(self.items)
def clear(self):
self.items.clear()
```
这个类使用列表(list)来存储元素,并且实现了添加、删除、弹出、差集、并集、判断相等、包含关系、长度、清空等操作。
阅读全文