关于《Python计算与编程导论》第8章IntSet类代码的技术问询
关于IntSet类的代码解析与常见问题解答
嘿,我来帮你拆解这个《Python计算与编程导论》里的IntSet类示例代码,从你给出的片段来看,首先就能发现几个关键问题需要修正,还有一些核心方法的实现可以补充完整,咱们一步步来:
1. 先修复构造方法里的低级bug
你写的__init__方法里,self.vals == []这行用了双等号(比较运算符),这只是在判断self.vals是不是等于空列表,但根本没给它赋值!这会导致后续调用insert之类的方法时直接抛出AttributeError。正确的写法应该是用单等号做赋值:
def __init__(self): """创建一个空整数集合""" self.vals = []
2. 补全insert方法的实现
你给出的insert方法只写了开头的注释,完整的实现需要保证集合的核心特性——元素唯一性,所以得先检查元素是否已经在集合里,再决定要不要添加:
def insert(self, e): """Assumes e is an integer and inserts e into the set""" if not self.member(e): # 先调用member方法检查是否存在 self.vals.append(e)
3. 实现member方法(判断元素是否存在)
上面的insert依赖member方法来检查元素,这个方法的逻辑很直接:
def member(self, e): """Assumes e is an integer Returns True if e is in the set, False otherwise""" return e in self.vals
4. 实现remove方法(移除元素)
移除元素的时候要考虑元素不存在的情况,通常会抛出异常来提示,这里直接复用列表的remove方法并捕获处理:
def remove(self, e): """Assumes e is an integer and removes e from the set Raises ValueError if e is not in the set""" try: self.vals.remove(e) except ValueError: raise ValueError(f"{e} not found in the set")
5. 给集合加个友好的字符串输出(__str__方法)
默认打印实例会显示内存地址,很不直观,咱们实现__str__方法让它像内置集合那样输出:
def __str__(self): """Returns a string representation of the set""" self.vals.sort() # 先排序让输出更整齐 return "{" + ", ".join(str(e) for e in self.vals) + "}"
6. 实际使用示例
写完这些方法后,咱们来测试下:
# 创建空集合 my_set = IntSet() my_set.insert(5) my_set.insert(2) my_set.insert(5) # 重复插入,不会被添加 print(my_set) # 输出 {2, 5} print(my_set.member(3)) # 输出 False my_set.remove(2) print(my_set) # 输出 {5}
7. 聊聊这个实现的优缺点
- 优点:逻辑非常直白,完全是面向对象入门级的示例,能帮你快速理解集合的核心特性(元素唯一),以及类的方法设计思路。
- 缺点:因为是基于列表实现的,
member和remove方法的时间复杂度都是O(n),当集合里元素很多时效率会很低。实际开发中咱们肯定优先用Python内置的set,它是基于哈希表实现的,这些操作的时间复杂度都是O(1),快得多。
内容的提问来源于stack exchange,提问作者Madmint
相关产品推荐
相关产品推荐

