python 编写一个类,实现添加元素(如果存在则不添加),删除元素,弹出元素(pop),集合差集运算,集合并集运算,判断两个集合是否相等,>=运算符重载(集合包含关系),支持内置函数len,清空集合所有元素
时间: 2024-02-06 07:10:42 浏览: 42
下面是一个示例代码,实现了上述功能:
```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 len(self.items) == 0:
return None
return self.items.pop()
def difference(self, other_set):
result = MySet()
for item in self.items:
if item not in other_set.items:
result.add(item)
return result
def union(self, other_set):
result = MySet()
for item in self.items:
result.add(item)
for item in other_set.items:
result.add(item)
return result
def __eq__(self, other_set):
if len(self.items) != len(other_set.items):
return False
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 = []
```
使用示例:
```python
set1 = MySet()
set1.add(1)
set1.add(2)
set1.add(3)
set2 = MySet()
set2.add(2)
set2.add(3)
set2.add(4)
set3 = set1.union(set2)
print(set3.items) # [1, 2, 3, 4]
set4 = set1.difference(set2)
print(set4.items) # [1]
print(set1 >= set4) # True
set1.clear()
print(len(set1.items)) # 0
```
阅读全文