python编写一个类,实现添加元素(如果存在则不添加),删除元素,弹出元素(pop),集合差集运算,集合并集运算,判断两个集合是否相等,>=运算符重载(集合包含关系),支持内置函数len,清空集合所有元素
时间: 2024-02-01 08:02:49 浏览: 19
string 类实现,构造函数、析构函数、操作符重载等
可以参考下面的代码实现:
```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 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)
set1.add(4)
print("set1:", set1.items)
set2 = MySet()
set2.add(3)
set2.add(4)
set2.add(5)
set2.add(6)
print("set2:", set2.items)
set3 = set1.difference(set2)
print("set1 - set2:", set3.items)
set4 = set1.union(set2)
print("set1 | set2:", set4.items)
print("set1 == set2:", set1 == set2)
print("set1 == set4:", set1 == set4)
print("set1 >= set2:", set1 >= set2)
print("set2 >= set1:", set2 >= set1)
print("len(set1):", len(set1))
set1.clear()
print("set1:", set1.items)
```
输出结果:
```
set1: [1, 2, 3, 4]
set2: [3, 4, 5, 6]
set1 - set2: [1, 2]
set1 | set2: [1, 2, 3, 4, 5, 6]
set1 == set2: False
set1 == set4: True
set1 >= set2: False
set2 >= set1: True
len(set1): 4
set1: []
```
阅读全文