用Python语言实现从set类型继承并设计一个名为CountedSet的子类型。通过重载set类型的某些函数使得CountedSet对象可以统计并记录各个元素被放入集合的总次数。下述伪代码描述了该CountedSet类型被使用的场景。class CountedSetsetpasssCountedSetsaddasaddcsaddaa=sgetCounta #a值应为2c= sgetCountc
class CountedSet(set): def init(self): self.counts = {}
def add(self, elem):
self.counts[elem] = self.counts.get(elem, 0) + 1
super().add(elem)
def remove(self, elem):
self.counts[elem] -= 1
if self.counts[elem] == 0:
del self.counts[elem]
super().remove(elem)
def getCount(self, elem):
return self.counts.get(elem, 0)
原文地址: https://www.cveoy.top/t/topic/ce2T 著作权归作者所有。请勿转载和采集!