编写一个类,实现添加元素(如果存在则不添加),删除元素,弹出元素(pop),集合差集运算,集合并集运算,判断两个集合是否相等,>=运算符重载(集合包含关系),支持内置函数len,清空集合所有元素
时间: 2024-01-28 07:03:50 浏览: 78
实现一个集合类`Set`,包含以下方法:
```python
class Set:
def __init__(self, elements=None):
"""
初始化集合,可以传入一个可迭代对象作为集合初始元素
"""
pass
def add(self, element):
"""
如果元素不存在,则添加元素到集合中
"""
pass
def remove(self, element):
"""
如果元素存在,则从集合中删除元素
"""
pass
def pop(self):
"""
弹出集合中的一个元素
"""
pass
def difference(self, other_set):
"""
返回与另一个集合的差集
"""
pass
def union(self, other_set):
"""
返回与另一个集合的并集
"""
pass
def is_equal(self, other_set):
"""
判断两个集合是否相等
"""
pass
def __ge__(self, other_set):
"""
重载>=运算符,判断是否为包含关系
"""
pass
def __len__(self):
"""
返回集合元素个数
"""
pass
def clear(self):
"""
清空集合所有元素
"""
pass
```
下面是具体实现:
```python
class Set:
def __init__(self, elements=None):
self._elements = set()
if elements is not None:
for element in elements:
self.add(element)
def add(self, element):
if element not in self._elements:
self._elements.add(element)
def remove(self, element):
self._elements.discard(element)
def pop(self):
if len(self._elements) > 0:
return self._elements.pop()
else:
raise KeyError("pop from an empty set")
def difference(self, other_set):
return Set(self._elements.difference(other_set._elements))
def union(self, other_set):
return Set(self._elements.union(other_set._elements))
def is_equal(self, other_set):
return self._elements == other_set._elements
def __ge__(self, other_set):
return self._elements.issuperset(other_set._elements)
def __len__(self):
return len(self._elements)
def clear(self):
self._elements.clear()
```
测试:
```python
s1 = Set([1, 2, 3])
s2 = Set([2, 3, 4])
s3 = Set([1, 2, 3])
assert len(s1) == 3
assert 1 in s1
assert 4 not in s1
s1.add(4)
assert 4 in s1
s1.remove(4)
assert 4 not in s1
s1.clear()
assert len(s1) == 0
s1.add(1)
s1.add(2)
s1.add(3)
s1.add(4)
s1.add(5)
s2.add(5)
s2.add(6)
assert s1.difference(s2).is_equal(Set([1, 2, 3, 4]))
assert s1.union(s2).is_equal(Set([1, 2, 3, 4, 5, 6]))
assert s1.is_equal(s3)
assert s1 >= s3
s1.pop()
assert len(s1) == 4
```
阅读全文