集合ADT
#-*-coding: utf-8-*-
# 使用python列表实现集合ADT
class MySet(object):
def __init__(self, *initElements):
self._theElements = list(initElements)
# 集合的基数
def __len__(self):
return len(self._theElements)
def isEmpty(self):
if len(self):
return False
else:
return True
# 判断元素从属
def __contains__(self, element):
return element in self._theElements
# 添加新元素
def add(self, element):
if element not in self:
self._theElements.append(element)
# 删除元素
def remove(self, element):
assert element in self, "The element must be in the set."
self._theElements.remove(element)
# 判断两集合是否相等
def __eq__(self, other):
if len(self) != len(other):
return False
else:
return self.isSubsetOf(other)
# 判断子集
def isSubsetOf(self, other):
for element in self:
if element not in other:
return False
return True
def __lt__(self, other):
return self.isSubsetOf(other)
# 判断真子集
def isProperSubsetOf(self, other):
if self.isSubsetOf(other) and len(self) < len(other):
return True
else:
return False
# 打印集合ADT
def __str__(self):
return "{%s}" % (", ".join([str(i) for i in self._theElements]))
# 并集
def union(self, other):
newSet = MySet()
newSet._theElements.extend(self._theElements)
for element in other:
if element not in self:
newSet._theElements.append(element)
return newSet
def __add__(self, other):
return self.union(other)
# 交集
def interset(self, other):
newSet = MySet()
newSet._theElements.extend(self._theElements)
for element in self:
if element not in other:
newSet.remove(element)
return newSet
def __mul__(self, other):
return self.interset(other)
# 差集
def difference(self, other):
newSet = MySet()
newSet.theElements.extend(self._theElements)
for element in self:
if element in other:
newSet.remove(element)
return newSet
def __sub__(self, other):
return self.difference(other)
# 迭代器
def __iter__(self):
return _SetIterator(self._theElements)
class _SetIterator(object):
def __init__(self, theSetList):
self._setRef = theSetList
self._curNdx = 0
def __iter__(self):
return self
def next(self):
if self._curNdx < len(self._setRef):
entry = self._setRef[self._curNdx]
self._curNdx += 1
return entry
else:
raise StopIteration
操作 | 最坏情况 |
s=Set() | O(1) |
len(s) | O(1) |
x in s | O(n) |
s.add(x) | O(n) |
s.isSubsetOf(t) | O(n²) |
s == t | O(n²) |
s.union(t) | O(n²) |
遍历 | O(n) |
对于in操作符,最坏情况显然是要遍历完所有元素之后,才能判断x是否存在,所以是O(n)。
合集
这里面包含了一个for循环,而循环体里又包含了in操作符,所以是O(n²)。
判断子集以及相等也是类似的。