python编写一个类,实现添加元素(如果存在则不添加),删除元素,弹出元素(pop),集合差集运算,集合并集运算,判断两个集合是否相等,>=运算符重载(集合包含关系),支持内置函数len,清空集合所有元素
时间: 2024-02-06 11:10:14 浏览: 100
好的,我来为您编写一个类,实现上述功能:
```python
class MySet:
def __init__(self, elements=None):
if elements is None:
elements = []
self.elements = elements
def add_element(self, element):
if element not in self.elements:
self.elements.append(element)
def remove_element(self, element):
if element in self.elements:
self.elements.remove(element)
def pop_element(self):
if self.elements:
return self.elements.pop()
def difference(self, other_set):
return MySet([element for element in self.elements if element not in other_set.elements])
def union(self, other_set):
return MySet(self.elements + [element for element in other_set.elements if element not in self.elements])
def is_equal(self, other_set):
return set(self.elements) == set(other_set.elements)
def __ge__(self, other_set):
return set(self.elements).issuperset(set(other_set.elements))
def __len__(self):
return len(self.elements)
def clear(self):
self.elements = []
```
示例代码:
```python
# 初始化一个集合
my_set = MySet([1, 2, 3, 4, 5])
# 添加元素
my_set.add_element(6)
my_set.add_element(6) # 已存在的元素不会被添加
print(my_set.elements) # [1, 2, 3, 4, 5, 6]
# 删除元素
my_set.remove_element(4)
print(my_set.elements) # [1, 2, 3, 5, 6]
# 弹出元素
print(my_set.pop_element()) # 6
print(my_set.elements) # [1, 2, 3, 5]
# 集合差集运算
other_set = MySet([3, 4, 5, 6, 7])
print(my_set.difference(other_set).elements) # [1, 2]
# 集合并集运算
print(my_set.union(other_set).elements) # [1, 2, 3, 5, 4, 6, 7]
# 判断两个集合是否相等
print(my_set.is_equal(other_set)) # False
# >= 运算符重载
print(my_set >= other_set) # False
# 内置函数 len
print(len(my_set)) # 4
# 清空集合所有元素
my_set.clear()
print(my_set.elements) # []
```
阅读全文