编写一个类,实现添加元素(如果存在则不添加),删除元素,弹出元素(pop),集合差集运算,集合并集运算,判断两个集合是否相等,>=运算符重载(集合包含关系),支持内置函数len,清空集合所有元素。
时间: 2024-02-01 14:02:49 浏览: 25
下面是一个简单的实现:
```python
class Set:
def __init__(self, iterable=None):
self.items = []
if iterable is not None:
for item in iterable:
self.add(item)
def add(self, item):
if item not in self.items:
self.items.append(item)
def remove(self, item):
try:
self.items.remove(item)
except ValueError:
pass
def pop(self):
if len(self.items) == 0:
raise KeyError('pop from an empty set')
return self.items.pop()
def difference(self, other_set):
return Set([item for item in self.items if item not in other_set])
def union(self, other_set):
return Set(self.items + [item for item in other_set.items if item not in self.items])
def __eq__(self, other_set):
if isinstance(other_set, Set):
return set(self.items) == set(other_set.items)
return False
def __ge__(self, other_set):
if isinstance(other_set, Set):
return set(self.items) >= set(other_set.items)
return False
def __len__(self):
return len(self.items)
def clear(self):
self.items = []
```
这个类有一个items属性,它是一个列表,用于存储集合中的元素。构造函数可以接受一个可迭代对象,将其转换为集合。add方法用于添加元素,如果元素已经存在则不添加。remove方法用于删除元素,如果元素不存在则不进行操作。pop方法用于弹出集合中的一个元素。difference方法用于返回集合的差集,union方法用于返回集合的并集。__eq__方法用于判断两个集合是否相等,__ge__方法用于重载>=运算符(集合包含关系)。__len__方法用于支持内置函数len,clear方法用于清空集合所有元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)