← 路线图复习卡片
Module 00 · Phase 1 · 重建基础

Python 快速重建(给 C 程序员)

你已经懂 C:内存、指针、数组、结构体、循环。这一章不从"什么是变量"讲起,而是把你脑子里已有的 C 模型逐条映射到 Python,重点讲两者不一样、并且面试里会出错的地方:名字绑定、可变性、数据结构的复杂度、惯用写法,以及 coding 面试要背熟的模板。

这一章的目标。学完后你应该能:(1) 用 Python 的对象模型解释任何"为什么这个列表被改了"的现象;(2) 不查文档写出 deque / heapq / Counter / bisect / lru_cache 的正确用法,并说出每个操作的复杂度;(3) 在 20 分钟内从空白文件写出 BFS、Dijkstra、并查集、二分、滑动窗口等模板;(4) 回答"GIL 是什么""为什么 Python 循环慢"这类语言机制题;(5) 看懂 PyTorch 代码里的 class、super().__init__()、__call__、with torch.no_grad() 和装饰器。

建议顺序。§0 总表先扫一遍 → §1 对象模型(最重要,坑最多)→ §2–§3(数据结构复杂度一定要背)→ §4 惯用写法 → 直接跳到 §9 模板和 §10 练习,每天手写 2–3 题;§5–§8 穿插阅读。时间紧就开"速记模式",只看一句话结论和英文回答。

和其他模块的关系。这里是 01 NumPy/PyTorch、14 ML Coding 和 15 算法题 的语言地基。§5 的类和 §6 的上下文管理器直接对应 nn.Module 和 torch.no_grad();§8 的"循环慢 → 向量化"是 01 的出发点。

怎么验证。本页所有代码块都在 Python 3.13 上实际运行过(断言全部通过);C 代码用 gcc -std=c11 编译运行过。建议你打开一个终端,自己敲一遍,而不是复制。

§0 · HOW TO LEARN + C → PYTHON MAP怎么学 + C 概念对照总表

先建立"翻译表"。C 程序员学 Python 最大的障碍不是语法,而是心智模型:C 里"变量 = 一块内存",Python 里"变量 = 贴在对象上的标签"。下面这张表把你熟悉的每个 C 概念对应到 Python,并标出最容易出错的差异。

★

学习方法:为什么这章要"写",不能只"读"

一句话

面试 coding 考的是"不靠补全,在白板/空白编辑器里流畅写出正确代码"的能力;这种能力只能靠关掉 AI 补全、计时手写、立刻跑测试来恢复。

Fluency without autocomplete only comes back through deliberate, timed practice from a blank file.

你目前的情况(C 基础 + 长期依赖 AI 补全)非常常见。问题不是"不懂",而是提取速度:面试时你需要在 1–2 秒内想起 heapq.heappush(h, x) 的参数顺序、deque.popleft() 的名字、sorted(..., key=...) 的写法。每次卡 30 秒查语法,45 分钟的面试就很被动。

  • 关掉补全:练习时用纯文本编辑器或关闭 Copilot / Cursor Tab。面试平台(CoderPad、HackerRank、Google Doc)大多没有补全,甚至不能运行。
  • 先说再写:每道题先用英文口述思路和复杂度(见每个概念的 "Say it in English"),再写代码。面试官打分时,沟通和代码同样重要。
  • 写完立刻测:本页每个模板都附了 assert。养成习惯:写完函数,马上写 2–3 个断言,包括空输入、单元素、重复元素。
  • 间隔重复:页底卡片和 复习页 用 Leitner 盒子安排复习。做错的题 2 天后从空白文件重写。
  • 用 REPL 验证直觉:任何"我觉得是这样"的语言行为,打开 python3 试 5 秒。比如 -7 // 2、[[0]*3]*3。
Say it in English

Before I write any code, let me restate the problem and walk through a small example. My first idea is a brute-force O(n²) approach; I think we can get to O(n) with a hash map. I'll code that up, and then test it on an empty input, a single element, and a case with duplicates.

★

C → Python 总对照表

一句话

Python 里一切都是堆上的对象,变量只是名字(引用);没有指针运算、没有手动内存管理、没有头文件,类型属于对象而不属于变量。

In Python everything is a heap object, variables are just names bound to objects, and types belong to objects, not variables.

C 概念Python 对应关键差异 / 坑
int x = 5; 变量 = 有类型的内存格子x = 5 名字绑定到 int 对象名字无类型,可以重新绑定到任何类型;赋值从不拷贝对象(§1)
指针 int *p = &x;没有显式指针;每个名字本身就是引用b = a ≈ C 里两个指针指向同一块内存;没有 &、*、指针运算;id(obj) 在 CPython 中就是地址
数组 int a[10];list(动态数组,元素是引用);数值计算用 numpy.ndarraylist 可以混装任意类型、自动扩容;越界抛 IndexError 而不是未定义行为;支持负下标 a[-1]
结构体 struct Point {int x, y;};class / @dataclass / namedtuple / 直接用 tuple 或 dict对象可以随时加属性;@dataclass 自动生成 __init__、__repr__、__eq__(§5)
malloc / free创建对象自动分配;引用计数 + 循环 GC 自动回收没有悬空指针和 double free;但"还有引用就不释放"——PyTorch 显存泄漏常见原因(§8)
#include "foo.h"import foo / from foo import barimport 会执行模块代码(只执行一次并缓存在 sys.modules);没有声明/定义分离
int main(int argc, char **argv)if __name__ == "__main__": main();参数在 sys.argv脚本从上到下执行,没有强制入口;这个守卫防止被 import 时运行(§7)
printf("%d %.3f\n", a, b)print(f"{a} {b:.3f}")print 默认用空格分隔、末尾换行;sep=、end= 可改
scanf("%d", &n)n = int(input());大量输入用 sys.stdininput() 返回字符串(去掉换行),要自己转换;读一行多个数:map(int, input().split())
for (int i = 0; i < n; i++)for i in range(n):Python 的 for 是"遍历可迭代对象";要下标和值用 enumerate;循环里改 i 不影响下一次迭代
while (cond) { }while cond:没有 do-while;用 while True: ... if not cond: break
switch (x) { case 1: ... }match x: case 1: ...(3.10+),或 dict 分发 {"add": f, "sub": g}[op]()match 没有贯穿(fall-through),不需要 break;面试里 dict 分发更常见
NULLNoneNone 是单例对象,判断用 x is None;它和 0、False 不相等但都是"假"
char *s = "hi"; / char buf[]str(不可变 Unicode 序列)没有 '\0' 结尾;不能 s[0] = 'H';单字符也是长度 1 的 str;ord('a') == 97、chr(97) == 'a'
char c = 'a';没有 char 类型,'a' 和 "a" 都是 strc - 'a' 要写成 ord(c) - ord('a')
bool(C99 _Bool)、! && ||True/False,not and orand/or 返回操作数本身而非 0/1:x or default;bool 是 int 的子类,True + True == 2
a ? b : cb if a else c顺序不同:值在前,条件在中间
x++, ++xx += 1Python 没有 ++;++x 合法但只是两次一元正号,什么都不做
a / b(整数除法截断)a // b(向下取整);a / b 永远返回 float负数时结果不同:-7 // 2 == -4,C 是 -3(§2)
INT_MAX、溢出int 任意精度,不溢出"无穷大"用 float('inf') 或 math.inf
块用 { },语句用 ;块用缩进(4 空格),语句换行结束缩进是语法;混用 tab 和空格会报错
块作用域 { int i; }函数作用域(LEGB:Local, Enclosing, Global, Builtin)for 循环变量在循环结束后仍然存在;if/for 不创建新作用域
函数指针 int (*f)(int)函数是一等对象,直接传 f;匿名函数 lambda x: x + 1可以放进 list/dict,可以返回函数(闭包,§4)
errno / 返回 -1异常 try/except/finally,raise"请求原谅比请求许可容易"(EAFP)是 Python 风格
const没有真正的常量;约定全大写 MAX_N = 10**5;不可变类型(tuple, frozenset)"不可变"是对象的性质,不是名字的性质
sizeofsys.getsizeof(obj)(只算对象自身,不算引用的子对象)一个 int 在 64 位 CPython 上约 28 字节,比 C 的 4 字节大得多——这是 Python 慢且占内存的原因之一
C
#include <stdio.h>
#include <stdlib.h>

typedef struct { int x, y; } Point;

int sum(const int *a, int n) {
    int s = 0;
    for (int i = 0; i < n; i++) s += a[i];
    return s;
}

int main(void) {
    int n;
    if (scanf("%d", &n) != 1) return 1;
    int *a = malloc(n * sizeof(int));
    for (int i = 0; i < n; i++)
        if (scanf("%d", &a[i]) != 1) return 1;
    Point p = {1, 2};
    printf("sum=%d p=(%d,%d)\n", sum(a, n), p.x, p.y);
    free(a);
    return 0;
}
PYTHON
import sys
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def main():
    data = sys.stdin.read().split()
    n = int(data[0])
    a = list(map(int, data[1:1 + n]))  # no malloc
    p = Point(1, 2)
    print(f"sum={sum(a)} p=({p.x},{p.y})")
    # no free: refcount drops to 0 at exit

if __name__ == "__main__":
    main()
验证:上面的 Python 版本(用模拟的 stdin 运行)
import io, sys
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def main():
    data = sys.stdin.read().split()
    n = int(data[0])
    a = list(map(int, data[1:1 + n]))
    p = Point(1, 2)
    print(f"sum={sum(a)} p=({p.x},{p.y})")

sys.stdin = io.StringIO("3\n1 2 3\n")
buf = io.StringIO(); old = sys.stdout; sys.stdout = buf
main()
sys.stdout = old
assert buf.getvalue() == "sum=6 p=(1,2)\n"
print("ok")
常见误区把 Python 的 list 想成 C 的 int a[]。实际上 Python list 更像 C 的 PyObject **items:一个指针数组,每个指针指向一个独立的堆对象。所以 [1, 2, 3] 存的是 3 个指针 + 3 个 int 对象。这解释了为什么 list 可以混装类型、为什么数值计算要用 NumPy(NumPy 才是连续的原始数值数组,和 C 数组一样)。
Say it in English

Coming from C, the biggest shift for me was that Python variables are names, not memory locations. Every value is a heap-allocated object with its own type, and assignment just binds a name to an object, so nothing gets copied. A Python list is really an array of pointers to objects, which is why it can hold mixed types, and also why we use NumPy for dense numeric work.

追问链
  1. If Python lists are arrays of pointers, what does that mean for cache performance compared to a C array?
    思路
    C 数组的元素连续存放,遍历时 CPU cache 和预取非常高效。Python list 只有指针是连续的,真正的 int/float 对象散落在堆上,每次访问要多一次间接寻址,cache 局部性差;再加上每个元素都有对象头(引用计数 + 类型指针),内存放大好几倍。NumPy 数组把原始数值连续存放(像 C 的 double[]),所以向量化运算快得多。
  2. Is there any way to get a C-like typed array in pure Python without NumPy?
    思路
    有:标准库 array 模块(array('i', [1,2,3]))存连续的原始 C 类型;bytes/bytearray 存原始字节;memoryview 可以零拷贝切片。但它们没有向量化运算,所以 ML 里还是用 NumPy/PyTorch。

§1 · OBJECT MODEL对象模型:名字、对象与可变性

这是全章最重要的一节。几乎所有"Python 诡异行为"——列表被莫名修改、默认参数累积、二维数组一改全改——都来自同一个事实:赋值是绑定名字,不是拷贝值。把这一节彻底弄懂,后面的坑都能自己推出来。

★

名字绑定 vs 内存格子

一句话

C 的变量是一块有类型的内存,赋值 = 把值写进去;Python 的变量是一个名字,赋值 = 让名字指向某个对象,对象自己带类型。

In C, a variable is a typed box and assignment copies a value into it; in Python, a variable is a label and assignment makes the label point at an object.

在 C 里写 int a = 5; int b = a;,内存里有两个格子,各自存一个 5。改 b 不影响 a。

在 Python 里写 a = [1, 2]; b = a,内存里只有一个 list 对象,a 和 b 是贴在它上面的两张标签。b.append(3) 修改的是那个唯一的对象,所以 a 也"变了"。

最接近的 C 心智模型:Python 中每个变量都是一个 PyObject * 指针,赋值就是指针赋值。

C(Python 赋值的等价物)
#include <stdio.h>
#include <stdlib.h>

typedef struct { int len; int data[8]; } List;

int main(void) {
    List *a = malloc(sizeof(List));
    a->len = 2; a->data[0] = 1; a->data[1] = 2;
    List *b = a;            /* b = a : copy the POINTER */
    b->data[b->len++] = 3;  /* b.append(3) */
    printf("%d\n", a->len); /* 3 : a sees it */
    b = malloc(sizeof(List)); /* b = [] : rebind b */
    b->len = 0;
    printf("%d\n", a->len); /* still 3 */
    free(a); free(b);
    return 0;
}
PYTHON
>>> a = [1, 2]
>>> b = a          # no copy: two names, one object
>>> b.append(3)    # MUTATE the shared object
>>> a
[1, 2, 3]
>>> b = []         # REBIND b to a new object
>>> a              # a unaffected
[1, 2, 3]
>>> x = 5
>>> y = x
>>> y += 1         # ints are immutable: y is rebound
>>> x, y
(5, 6)
直觉只要记住两类操作:重新绑定(name = ...、name += ... 作用在不可变对象上)只改变这一个名字指向谁;原地修改(.append、[i] = 、.update、.sort())改变对象本身,所有指向它的名字都看得到。
Say it in English

Python variables are names that refer to objects. Assignment never copies data; it just binds a name to an existing object. So if two names refer to the same list and I mutate it through one name, the other name sees the change. Rebinding a name, on the other hand, only affects that name.

★

id、is、== 与小整数缓存

一句话

== 比较值(调用 __eq__),is 比较是不是同一个对象(id 相同);is 只用于 None/True/False 这种单例。

== checks value equality, is checks identity; only use is for singletons like None.

id(obj) 返回对象在其生命周期内唯一的整数,CPython 中就是内存地址。a is b 等价于 id(a) == id(b),相当于 C 里比较两个指针 p == q;而 a == b 相当于 memcmp 或自定义的比较函数。

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b, a is b      # equal values, different objects
(True, False)
>>> c = a
>>> c is a
True
>>> x = None
>>> x is None           # the idiomatic check
True

小整数缓存(CPython 实现细节):CPython 预先创建了 −5 到 256 的 int 对象并复用,所以 a = 256; b = 256; a is b 是 True。大整数每次运算可能产生新对象,is 就可能是 False。字符串也有类似的"驻留"(interning)。这些都是实现细节,结果甚至会随写法(同一行字面量会被编译器合并)而变。结论:比较数字和字符串永远用 ==。

a = 256
b = int("256")          # computed at runtime
assert a is b           # cached small int (CPython detail)
c = 10**6
d = int("1000000")
assert c == d           # values equal
print(c is d)           # False in CPython: two distinct objects
常见误区(1) 用 if x is 5 或 if s is "abc":Python 3.8+ 会给出 SyntaxWarning,而且结果不可靠。(2) 用 if x == None:能工作,但如果 x 是 NumPy 数组会逐元素比较、返回数组;x is None 永远安全。(3) 用 if not x 判断"是否为 None":x 为 0 或空列表时也会进入分支。
Say it in English

Double-equals compares values by calling __eq__, while is compares identity, meaning whether both names point to the same object. I only use is for singletons like None. CPython caches small integers from minus five to 256, so is can appear to work on small numbers, but that is an implementation detail you should never rely on.

追问链
  1. Why is x is None preferred over x == None?
    思路
    (1) None 是单例,身份比较语义正确且最快;(2) == 会调用 __eq__,可被重载,比如 NumPy/PyTorch 的 arr == None 返回逐元素的布尔数组,放进 if 会报 "truth value of an array is ambiguous"。
  2. Can two different live objects have the same id?
    思路
    同一时刻存活的两个对象不会有相同的 id。但一个对象被回收后,它的地址可以被新对象复用,所以生命周期不重叠的对象可能 id 相同,比如 id([]) == id([]) 常常是 True(第一个临时 list 立刻被释放,第二个复用了同一地址)。
★

可变 vs 不可变;可哈希

一句话

不可变:int、float、bool、str、tuple、frozenset、bytes、None;可变:list、dict、set、bytearray、大多数自定义对象。只有可哈希(通常 = 不可变)的对象能做 dict 的 key 或放进 set。

Immutable types can't be changed in place; only hashable objects can be dict keys or set members.

类型可变?可哈希?面试用途
int, float, bool否是计数、下标
str否是key;拼接要用 join
tuple否元素都可哈希时才是坐标 (r, c) 做 key、放进 visited set、heap 元素
frozenset否是"集合的集合"、状态压缩
list是否不能做 key → 先 tuple(lst)
dict, set是否
自定义类实例是(默认)默认是(按 id 哈希);定义 __eq__ 而不定义 __hash__ 后变为不可哈希§5

为什么 key 必须不可变?哈希表根据 hash(key) 决定把条目放在哪个桶。如果 key 被原地修改,它的哈希值变了,但条目还在旧桶里,之后就再也找不到它了。所以 Python 直接禁止 list 做 key。

"不可变"只是浅层的:tuple 不能换元素,但如果元素本身是 list,这个 list 仍然可以改,而且这样的 tuple 不可哈希。

>>> t = (1, [2, 3])
>>> t[1].append(4)       # the tuple didn't change: same list object
>>> t
(1, [2, 3, 4])
>>> hash((1, 2)) == hash((1, 2))
True
>>> try:
...     hash(t)
... except TypeError as e:
...     print(e)
unhashable type: 'list'
>>> seen = {(0, 0), (0, 1)}   # grid coordinates as tuples
>>> (0, 1) in seen
True
常见误区以为"字符串可以原地修改":s[0] = 'H' 会报 TypeError。所有字符串"修改"方法(replace、upper、strip)都返回新字符串,必须接住返回值:s = s.strip()。相反,list.sort()、list.reverse() 是原地操作,返回 None——a = a.sort() 会把 a 变成 None。
Say it in English

Immutable objects like ints, strings and tuples can't be modified in place; any "change" creates a new object. Lists, dicts and sets are mutable. Dictionary keys and set members must be hashable, which in practice means immutable, because the hash determines the bucket; if a key could change, the table would lose track of it. That's why I convert a list to a tuple before using it as a key.

★

传参:call by object reference

一句话

函数参数是调用者对象的新名字:在函数内原地修改可变对象,外面看得到;在函数内重新绑定参数名,外面看不到。

Python passes object references by value: mutations are visible to the caller, rebinding is not.

C 里只有传值;要让函数修改调用者的数据,就传指针。Python 的规则正好等价于"永远传指针,但指针本身是按值传的"(Java 对对象也是如此)。有人叫它 call by sharing。

C 的等价写法
void mutate(List *lst) { lst->data[lst->len++] = 99; }
/* visible to caller */

void rebind(List *lst) { lst = malloc(sizeof(List)); }
/* only the local pointer changes; caller unaffected
   (and this leaks, but you get the idea) */
PYTHON
def mutate(lst):
    lst.append(99)      # caller sees this

def rebind(lst):
    lst = [99]          # local name only

def inc(n):
    n += 1              # int immutable -> rebinding
    return n

a = [1]
mutate(a); assert a == [1, 99]
rebind(a); assert a == [1, 99]
x = 5
inc(x);    assert x == 5
x = inc(x); assert x == 6
print("ok")

面试中的直接后果:回溯(backtracking)时把 path 加入结果,必须加拷贝 res.append(path[:]),否则结果里存的全是同一个后来被清空的 list(见 §9 回溯模板)。

def subsets_wrong(nums):
    res, path = [], []
    def dfs(i):
        if i == len(nums):
            res.append(path)       # BUG: appends the same list object
            return
        dfs(i + 1)
        path.append(nums[i]); dfs(i + 1); path.pop()
    dfs(0)
    return res

def subsets(nums):
    res, path = [], []
    def dfs(i):
        if i == len(nums):
            res.append(path[:])    # snapshot copy
            return
        dfs(i + 1)
        path.append(nums[i]); dfs(i + 1); path.pop()
    dfs(0)
    return res

assert subsets_wrong([1, 2]) == [[], [], [], []]   # all point to the emptied path
assert sorted(subsets([1, 2])) == [[], [1], [1, 2], [2]]
print("ok")
Say it in English

Python is neither pure pass-by-value nor pass-by-reference; it's often called pass-by-object-reference. The function receives a new name bound to the same object. If I mutate that object, for example append to a list, the caller sees it. If I rebind the parameter to a new object, only the local name changes.

追问链
  1. How would you write a function that "swaps" two integers for the caller, like swap(int *a, int *b) in C?
    思路
    做不到原地交换调用者的名字(int 不可变,函数也拿不到调用者的名字)。Python 风格是返回新值:a, b = b, a,或者 def swap(a, b): return b, a,调用 x, y = swap(x, y)。如果是交换 list 里的元素就可以原地:arr[i], arr[j] = arr[j], arr[i]。
  2. If you pass a PyTorch tensor into a function and do t += 1 inside, does the caller see it? What about t = t + 1?
    思路
    Tensor 是可变对象,t += 1 调用 __iadd__,是原地修改,调用者能看到(如果 t 是需要梯度的叶子张量还会报错)。t = t + 1 创建新张量并重新绑定局部名,调用者看不到。这和 list 的规则完全一样。
★

浅拷贝 vs 深拷贝;[[0]*3]*3 陷阱

一句话

浅拷贝只复制最外层容器(里面的元素仍共享);深拷贝递归复制所有层。[[0]*3]*3 是把同一个内层 list 重复了 3 次。

A shallow copy duplicates only the outer container; a deep copy recursively duplicates everything.

写法拷贝深度说明
b = a不拷贝同一个对象
a[:]、list(a)、a.copy()、copy.copy(a)浅新的外层 list,元素是同一批对象
[row[:] for row in grid]两层二维网格最常用的"够用"拷贝
copy.deepcopy(a)深递归复制,能正确处理循环引用;较慢
dict(d)、d.copy()、{**d}浅同上
import copy

grid = [[0] * 3] * 3          # 3 references to ONE inner list
grid[0][0] = 1
assert grid == [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
assert grid[0] is grid[1] is grid[2]

grid = [[0] * 3 for _ in range(3)]   # a new inner list per iteration
grid[0][0] = 1
assert grid == [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

# [0] * 3 itself is fine: ints are immutable, "changing" one rebinds a slot
row = [0] * 3
row[0] = 7
assert row == [7, 0, 0]

a = [[1, 2], [3, 4]]
s = a[:]                      # shallow
d = copy.deepcopy(a)          # deep
a[0].append(99)
assert s[0] == [1, 2, 99]     # shared inner list
assert d[0] == [1, 2]         # independent
print("ok")
直觉[x] * 3 复制的是 3 个引用。当 x 是不可变的 0 时没问题——你"修改"某个格子其实是把那个格子重新指向另一个 int。当 x 是可变的 list 时,三个格子指向同一个 list,原地修改就一改全改。
常见误区dp = [[0] * (m + 1)] * (n + 1) 是 DP 题里最常见的 bug,结果通常"差一点对",很难查。永远写 [[0] * (m + 1) for _ in range(n + 1)]。同理 [[]] * n(邻接表)也是错的,要写 [[] for _ in range(n)]。
Say it in English

Multiplying a list repeats references, not objects. So [[0] * 3] * 3 creates three references to the same inner list, and writing to one row changes all of them. The fix is a list comprehension, which builds a fresh inner list on each iteration. More generally, slicing or list() gives a shallow copy; for nested structures I'd use copy.deepcopy or copy each row.

★

可变默认参数

一句话

默认参数在 def 执行时只求值一次,所有调用共享同一个对象;可变默认值要用 None 哨兵。

Default arguments are evaluated once at definition time, so a mutable default is shared across calls.

def f(acc=[]):            # the list is created ONCE, when def runs
    acc.append(1)
    return acc

assert f() == [1]
assert f() == [1, 1]      # same list again
assert f.__defaults__ == ([1, 1],)   # it's stored on the function object

def g(acc=None):          # correct pattern
    if acc is None:
        acc = []
    acc.append(1)
    return acc

assert g() == [1] and g() == [1]
print("ok")

为什么这样设计?def 是一条在运行时执行的语句,它创建一个函数对象,并在这时把默认值表达式求值、存进 f.__defaults__。调用时不会重新求值。这在 C 里没有对应物(C 没有默认参数;C++ 的默认参数是每次调用时求值的)。

偶尔会被故意利用来做简单的缓存(def fib(n, memo={})),但面试里请用 functools.lru_cache,更清楚。

Say it in English

Default argument values are evaluated once, when the def statement runs, and stored on the function object. If the default is a mutable list, every call that relies on the default shares that same list, so state leaks between calls. The standard fix is to default to None and create a new list inside the function.

☆

+=:list 原地,tuple/int 重新绑定

一句话

a += b 先尝试 a.__iadd__(b)(原地修改,list 有);没有的话退回 a = a + b(新对象,int/str/tuple 是这样)。

+= mutates in place when the type supports it (lists), otherwise it creates a new object and rebinds.

a = [1]; alias = a
a += [2]                 # list.__iadd__ == extend, in place
assert alias == [1, 2] and alias is a

a = [1]; alias = a
a = a + [2]              # new list, rebind
assert alias == [1] and alias is not a

t = (1,); alias = t
t += (2,)                # tuples have no __iadd__: new tuple
assert alias == (1,) and t == (1, 2)

# the famous puzzle: mutate succeeds AND an exception is raised
t = ([1],)
try:
    t[0] += [2]          # step 1: list.__iadd__ mutates in place (ok)
except TypeError:        # step 2: t[0] = result -> tuple item assignment fails
    pass
assert t == ([1, 2],)
print("ok")

最后那个谜题常被当作"Python 冷知识"考:t[0] += [2] 被拆成 tmp = t[0].__iadd__([2])(成功,list 已被修改)和 t[0] = tmp(失败,tuple 不支持赋值)。结果是:抛异常,但 list 确实变了。

另外注意 a += "xy" 当 a 是 list 时会得到 [..., 'x', 'y'](extend 一个可迭代对象),而 a + "xy" 会报 TypeError。

Say it in English

Augmented assignment first tries the in-place method, __iadd__. Lists implement it as an in-place extend, so other references see the change. Immutable types like ints, strings and tuples don't, so Python falls back to computing a new object and rebinding the name.

§2 · NUMBERS, TRUTHINESS, CONTROL FLOW数字、真值与控制流

这一节是 C 程序员最容易"想当然"出错的地方:整数除法和取模的方向、整数不会溢出、什么东西算"假"、for 循环的本质。每一条都可能在算法题里造成 off-by-one 或负数 bug。

★

整数:任意精度;/ vs //;负数的 // 与 %

一句话

/ 永远返回 float;// 向负无穷取整(C 向零截断);% 的结果和除数同号(C 和被除数同号);int 不会溢出。

Python's // floors toward negative infinity and % takes the sign of the divisor, unlike C which truncates toward zero.

表达式PythonC (C99+)说明
7 / 23.53Python 的 / 是真除法
7 // 23—正数时两者一致
-7 // 2 / -7 / 2-4-3floor vs truncate
-7 % 21-1Python 保证 0 ≤ r < 2
7 % -2-11与除数同号
2**100精确的 31 位整数溢出(UB / 回绕)任意精度
int(-3.7)-3(int)-3.7 == -3int() 向零截断,与 C 一致

两种语言都满足恒等式 \( a = (a \,\text{div}\, b)\cdot b + (a \bmod b) \),区别只在 div 往哪边取整。Python 选 floor,所以余数总落在 \([0, b)\)(b>0 时),这对循环下标非常方便:(i - 1) % n 永远是合法下标,C 里却可能得到 −1。

import math
assert 7 / 2 == 3.5 and 7 // 2 == 3
assert -7 // 2 == -4 and -7 % 2 == 1
assert 7 % -2 == -1
for a in range(-10, 11):
    for b in (-3, -2, 2, 3):
        assert a == (a // b) * b + a % b          # identity holds
assert int(-7 / 2) == -3                          # C-style truncation
assert math.fmod(-7, 2) == -1.0                   # C-style remainder (float)
assert divmod(-7, 2) == (-4, 1)
assert (0 - 1) % 5 == 4                           # circular index, never negative
assert 2**100 == 1267650600228229401496703205376
assert (-8) ** (1/3) != -2                        # complex result! use -(8 ** (1/3))
assert isinstance((-8) ** (1/3), complex)
assert pow(3, 200, 10**9 + 7) == pow(3, 200) % (10**9 + 7)   # fast modular power
print("ok")
  • 中点:mid = (lo + hi) // 2 在 Python 中不会溢出(C 要写 lo + (hi - lo) / 2)。习惯上仍可以写 lo + (hi - lo) // 2,面试官会认可你的 C 背景。
  • 向上取整除法:-(-a // b) 或 (a + b - 1) // b(a, b > 0)或 math.ceil(a / b)(a 很大时浮点会不精确,避免)。
  • 位运算:& | ^ ~ << >> 都有;~x == -x - 1;负数右移是算术右移;x.bit_count()(3.10+)数 1 的个数,x.bit_length() 求位宽。因为 int 无限宽,"32 位无符号"要手动 & 0xFFFFFFFF。
  • 幂:pow(a, b, m) 内置快速模幂;** 优先级高于一元负号:-2**2 == -4。
常见误区把 C 的"取个位数"写法照搬到负数:-123 % 10 在 Python 是 7 而不是 -3。反转整数这类题,先取符号 sign = -1 if x < 0 else 1; x = abs(x) 再处理。另外"整数溢出"类题目(如 LeetCode 7 Reverse Integer 要求 32 位范围)在 Python 里需要手动检查范围 -2**31 <= r <= 2**31 - 1。
Say it in English

In Python, integers have arbitrary precision, so there's no overflow. Single slash is true division and always returns a float; double slash is floor division, which rounds toward negative infinity. That's different from C, which truncates toward zero, so minus seven floor-divided by two is minus four in Python but minus three in C. Correspondingly, the modulo result takes the sign of the divisor, which is handy for circular indexing.

追问链
  1. If Python ints never overflow, are big-integer operations still O(1)?
    思路
    不是。CPython 用 30 位一"位"(digit)的数组存大整数,加法是 O(位数),乘法用 Karatsuba 约 O(n^1.585)。在一般算法题中数值都在 64 位内,可视为 O(1);但像"计算 2**(10**6)"或在循环里累乘出天文数字时就要考虑成本,并且常见题会要求 "mod 1e9+7" 来控制大小。
  2. How would you emulate 32-bit unsigned overflow, for example in a hash function?
    思路
    每步运算后 & 0xFFFFFFFF;需要有符号解释时 x - (1 << 32) if x >= 1 << 31 else x。或者用 NumPy 的定宽类型 np.uint32(会回绕)。
☆

float、inf、nan 与 math.isclose

一句话

Python 的 float 就是 C 的 double(IEEE 754 双精度,约 15–17 位有效数字);用 math.inf 做初始最小值;比较浮点用 math.isclose;nan != nan。

Python floats are C doubles; use math.inf as a sentinel and math.isclose for comparisons.

import math
assert 0.1 + 0.2 != 0.3                       # binary floating point
assert math.isclose(0.1 + 0.2, 0.3)           # rel_tol=1e-9 by default
assert math.isclose(1e-12, 0.0, abs_tol=1e-9) # near zero you need abs_tol!
assert not math.isclose(1e-12, 0.0)

best = math.inf                               # == float('inf')
for x in [5, 3, 8]:
    best = min(best, x)
assert best == 3
assert -math.inf < -10**400 < math.inf        # compares with big ints

nan = float('nan')
assert nan != nan and math.isnan(nan)
assert max(1.0, nan) == 1.0 and math.isnan(max(nan, 1.0))   # order-dependent!

assert round(2.5) == 2 and round(3.5) == 4    # banker's rounding (half to even)
assert int(2.9) == 2 and math.floor(-2.5) == -3 and math.ceil(-2.5) == -2
assert 1e308 * 10 == math.inf                 # overflow -> inf, no exception
try:
    1 / 0
except ZeroDivisionError:
    pass                                      # Python raises; C would give inf (float) or UB (int)
print("ok")
  • math.isclose(a, b) 默认只有相对容差 rel_tol=1e-9,和 0 比较时必须给 abs_tol。
  • round() 是"四舍六入五成双"(银行家舍入),和很多人以为的"四舍五入"不同。
  • 浮点除以 0 在 Python 中抛 ZeroDivisionError(不像 C/NumPy 得到 inf)。NumPy 里则是警告 + inf/nan——这对 01 模块的数值稳定性很重要。
  • 需要精确十进制(金额)用 decimal.Decimal;精确有理数用 fractions.Fraction(概率题验算很好用)。
Say it in English

Python floats are IEEE double precision, just like C doubles, so 0.1 plus 0.2 isn't exactly 0.3. I'd compare floats with math.isclose, remembering to pass an absolute tolerance when comparing against zero. For a "minimum so far" sentinel I'd use math.inf.

★

真值(truthiness)与 and/or 短路

一句话

假值:None、False、数值 0(0, 0.0)、空容器("" [] {} set() () range(0));其余都为真。and/or 返回操作数本身。

Empty containers, zero and None are falsy; and/or short-circuit and return one of their operands.

>>> [bool(x) for x in [None, 0, 0.0, "", [], {}, set(), (), "0", [0], " "]]
[False, False, False, False, False, False, False, False, True, True, True]
>>> 0 or "default"        # returns the first truthy operand
'default'
>>> [] and 1 / 0          # short-circuit: right side never evaluated
[]
>>> 3 and 5               # all truthy -> returns the last
5
>>> stack = []
>>> while stack:          # idiomatic "while not empty"
...     stack.pop()
>>> True + True, sum([True, False, True])   # bool is a subclass of int
(2, 2)

自定义类可以用 __bool__(或退而求其次 __len__)控制真值。

常见误区(1) if node.val: 用来判断"节点有值"——当值为 0 时会出错,应该写 if node is not None。(2) x = x or default 当 x 合法地为 0 时被替换。(3) if tensor: 对多元素张量/NumPy 数组会报 "truth value is ambiguous",要写 .any()/.all()。(4) sum(cond for x in xs) 数满足条件的个数是合法且常用的,因为 True 就是 1。
Say it in English

In a boolean context, None, zero and empty containers are false and everything else is true, so I can write while stack instead of checking the length. But I'm careful when zero is a valid value, like a tree node with value zero; there I compare against None explicitly.

★

循环:range / enumerate / zip / reversed;for…else

一句话

Python 的 for 是"遍历一个可迭代对象",不是"初始化-条件-步进";要下标就 enumerate,并行遍历用 zip,倒序用 reversed 或 range(n-1, -1, -1)。

Python's for loop iterates over an iterable; use enumerate, zip and reversed instead of manual index arithmetic.

CPython
for (i = 0; i < n; i++)for i in range(n)
for (i = a; i < b; i += 2)for i in range(a, b, 2)
for (i = n - 1; i >= 0; i--)for i in range(n - 1, -1, -1) 或 for i in reversed(range(n))
for (i = 0; i < n; i++) use(i, a[i])for i, x in enumerate(a)(enumerate(a, start=1) 从 1 计数)
for (i = 0; i < n; i++) f(a[i], b[i])for x, y in zip(a, b)(以最短者为准;3.10+ zip(a, b, strict=True) 长度不同则报错)
相邻对 a[i], a[i+1]for x, y in zip(a, a[1:]) 或 itertools.pairwise(a)(3.10+)
二维 for i… for j…同样两层 for;或 itertools.product(range(n), range(m))

range 是惰性的序列对象,range(10**9) 不占内存,支持 len、下标、in(O(1))。

for…else:else 块在循环没有被 break 正常结束时执行。适合"搜索,找不到时做某事"。可以理解为 "for … no-break"。

def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            break
    else:                 # runs only if the loop did NOT break
        return True
    return False

assert [x for x in range(20) if is_prime(x)] == [2, 3, 5, 7, 11, 13, 17, 19]

a = [3, 1, 4]
assert list(enumerate(a, start=1)) == [(1, 3), (2, 1), (3, 4)]
assert list(zip("abc", [1, 2])) == [('a', 1), ('b', 2)]            # truncates
assert [y - x for x, y in zip(a, a[1:])] == [-2, 3]                # adjacent diffs
assert list(range(5, -1, -2)) == [5, 3, 1]
assert list(reversed(a)) == [4, 1, 3]
rows = [[1, 2, 3], [4, 5, 6]]
assert [list(c) for c in zip(*rows)] == [[1, 4], [2, 5], [3, 6]]  # transpose

# modifying the loop variable does nothing to the iteration (unlike C)
seen = []
for i in range(3):
    seen.append(i)
    i += 10
assert seen == [0, 1, 2]
assert i == 12            # but the name survives the loop (function scope)
print("ok")
常见误区(1) 想在循环里跳过若干元素就 i += 2——在 for 中无效,要改用 while i < n: 手动控制(双指针题常见)。(2) 遍历时删除 list 元素:for x in a: if bad(x): a.remove(x) 会跳过元素,应该生成新 list a = [x for x in a if not bad(x)]。(3) 遍历 dict 时增删键会抛 RuntimeError,要先 list(d)。
Say it in English

Python's for loop iterates directly over the elements of an iterable. When I need the index as well, I use enumerate; to walk two sequences in lockstep I use zip. If I need to control the index manually, like in a two-pointer problem, I switch to a while loop, because reassigning the loop variable inside a for loop doesn't affect the next iteration.

☆

链式比较、解包交换、三元表达式、walrus、match

一句话

0 <= r < n 是合法且推荐的;a, b = b, a 交换无需临时变量;x if c else y 是三元;:= 在表达式中赋值;match 是结构化模式匹配(不是 switch 的简单替身)。

Chained comparisons, tuple-unpacking swaps, conditional expressions, the walrus operator and structural pattern matching.

r, c, n, m = 2, 3, 5, 5
assert 0 <= r < n and 0 <= c < m          # chained: means (0<=r) and (r<n)
assert (1 < 3 > 2) is True                # legal but confusing; avoid

a, b = 1, 2
a, b = b, a                               # RHS tuple is built first, then unpacked
assert (a, b) == (2, 1)
first, *rest = [1, 2, 3, 4]
assert first == 1 and rest == [2, 3, 4]
*init, last = "abc"
assert init == ['a', 'b'] and last == 'c'
(p, q), s = (1, 2), 3                     # nested unpacking
assert (p, q, s) == (1, 2, 3)

sign = "neg" if -5 < 0 else "nonneg"      # value_if_true if cond else value_if_false
assert sign == "neg"

import re
lines = ["a=1", "skip", "b=22"]
vals = [int(mt.group(1)) for ln in lines if (mt := re.search(r"=(\d+)", ln))]
assert vals == [1, 22]                    # walrus: bind inside an expression

def calc(cmd):
    match cmd.split():
        case ["add", x, y]:
            return int(x) + int(y)
        case ["neg", x]:
            return -int(x)
        case ["quit" | "exit"]:
            return None
        case _:
            raise ValueError(cmd)
assert calc("add 2 3") == 5 and calc("neg 4") == -4 and calc("exit") is None

ops = {"+": lambda u, v: u + v, "*": lambda u, v: u * v}   # dict dispatch
assert ops["*"](3, 4) == 12
print("ok")

match 的 case 可以解构序列、映射、类实例,并带守卫 case [x, y] if x > y:。注意:case NAME: 中的裸名字是捕获变量而不是和常量比较(想比较常量要写 case Color.RED: 这样的带点名字或字面量)。面试中写 dict 分发或 if/elif 就够了。

Say it in English

For bounds checks I use chained comparisons like 0 <= r < rows. Swapping is just tuple unpacking, a, b = b, a, because the right-hand side is evaluated into a tuple before assignment. For a switch-like construct I usually use a dictionary that maps keys to functions, though Python 3.10 also added structural pattern matching.

§3 · CORE DATA STRUCTURES & COMPLEXITY核心数据结构与复杂度

算法面试里 80% 的"优化"就是换一个数据结构:O(n) 的 in list 换成 O(1) 的 in set,O(n) 的 pop(0) 换成 O(1) 的 popleft(),每次排序换成堆。这一节给出每个结构的底层实现(用 C 的语言解释)和完整复杂度,最后是一页速查表和"什么模式用什么结构"。

★

list:动态指针数组

一句话

list 底层是 C 的可增长指针数组(类似 PyObject **items + len + capacity):下标、尾部 append/pop 是 O(1)(append 均摊),头部和中间插删、in、index、remove 都是 O(n)。

A list is a dynamic array of pointers: O(1) indexing and amortized O(1) append, but O(n) insertion or deletion at the front.

扩容时 CPython 按约 1.125 倍 + 常数的比例过量分配(over-allocate),所以 n 次 append 总复制量是 O(n),均摊 O(1)。这和你在 C 里自己写 realloc(cap * 2) 的动态数组是同一个思路(倍增因子不同,但只要是几何增长,均摊就是 O(1))。

操作复杂度备注
a[i], a[i] = x, len(a)O(1)负下标 a[-1] 也是 O(1)
a.append(x)O(1) 均摊偶尔触发 O(n) 扩容
a.pop()O(1)弹出末尾 → list 就是现成的栈
a.pop(i), a.insert(i, x), del a[i]O(n − i)pop(0)/insert(0, x) 是 O(n):要 memmove 后面所有指针
x in a, a.index(x), a.count(x), a.remove(x)O(n)线性扫描
a[i:j]O(j − i)切片复制出新 list(浅拷贝)
a[i:j] = bO(len(a) + len(b))
a.extend(b), a += bO(len(b))
a + bO(len(a) + len(b))新 list
a * kO(k · len(a))复制引用(§1 陷阱)
a.sort(), sorted(a)O(n log n)Timsort,稳定;对已近有序的数据接近 O(n)
a.reverse(), a[::-1]O(n)前者原地,后者复制
min(a), max(a), sum(a)O(n)
a.copy(), list(a)O(n)浅拷贝
a == bO(n)逐元素比较
a.clear()O(n)要对每个元素减引用计数

切片语法 a[start:stop:step]:左闭右开;省略即"到头";负数从末尾数;a[::-1] 反转;切片越界不报错(a[5:100] 只是返回到末尾为止)。

a = [0, 1, 2, 3, 4, 5]
assert a[1:4] == [1, 2, 3] and a[:2] == [0, 1] and a[-2:] == [4, 5]
assert a[::2] == [0, 2, 4] and a[::-1] == [5, 4, 3, 2, 1, 0]
assert a[4:100] == [4, 5] and a[100:] == []     # slicing never raises IndexError
b = a[:]                                         # shallow copy
b[0] = 99
assert a[0] == 0
a[1:3] = ["x"]                                   # slice assignment can change length
assert a == [0, "x", 3, 4, 5]
del a[::2]
assert a == ["x", 4]
stack = []
stack.append(1); stack.append(2)
assert stack.pop() == 2 and stack[-1] == 1       # peek with [-1]
print("ok")
常见误区(1) 用 list 当队列 q.pop(0),BFS 退化成 O(V²)。(2) 在循环里 if x in big_list,整体 O(n²),应先 s = set(big_list)。(3) 递归里传 a[1:],每层复制 O(n),总 O(n²);传下标 i 更好。(4) a.sort() 返回 None。
Say it in English

A Python list is a dynamic array of object pointers. Indexing and appending at the end are constant time, with append amortized because of geometric over-allocation. Inserting or popping at the front is linear, since every pointer after it has to shift, so for a queue I'd use collections.deque. Membership testing is also linear, so if I need repeated lookups I convert to a set first.

追问链
  1. Prove that append is amortized O(1) with geometric growth.
    思路
    设容量每次乘以因子 \(g > 1\)。插入 n 个元素时,扩容发生在容量 \(c, cg, cg^2, \dots \le n\),每次扩容复制当前所有元素,总复制量 \(\le n + n/g + n/g^2 + \dots = n \cdot \frac{g}{g-1} = O(n)\)。加上 n 次 O(1) 写入,总 O(n),均摊 O(1)。如果每次只增加常数 k,总复制量是 \(k + 2k + \dots \approx n^2/(2k) = O(n^2)\),均摊 O(n)——这就是必须几何增长的原因。
☆

tuple 与 namedtuple

一句话

tuple 是不可变的定长序列:可哈希(元素都可哈希时)、按字典序比较,适合做坐标 key、堆元素、多返回值;单元素要写逗号 (x,)。

Tuples are immutable, hashable sequences compared lexicographically, ideal for dictionary keys, heap entries and multiple return values.

from collections import namedtuple
t = (3, "a")
assert (1, 9) < (2, 0) < (2, 1)          # lexicographic comparison
assert type((5)) is int and type((5,)) is tuple   # the comma makes the tuple
def divmod2(a, b):
    return a // b, a % b                 # "multiple returns" is just a tuple
q, r = divmod2(17, 5)
assert (q, r) == (3, 2)
dist = {(0, 0): 0}                       # coordinate keys
dist[(1, 2)] = 3
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
assert p.x == 1 and p[1] == 2 and p == (1, 2)
assert p._replace(x=5) == Point(5, 2)    # immutable: returns a new one
print("ok")
Say it in English

Tuples are immutable sequences. Because they're hashable, I use them for grid coordinates in a visited set or as dictionary keys, and because they compare lexicographically, they work well as heap entries like (distance, node).

★

dict:哈希表(保持插入顺序)

一句话

dict 是开放寻址哈希表:查找、插入、删除平均 O(1)(最坏 O(n));3.7 起语言保证保持插入顺序;key 必须可哈希。

A dict is an open-addressing hash table with average O(1) operations, and since 3.7 it preserves insertion order.

实现(C 视角):CPython 的 dict 由两部分组成:一个紧凑的 entries 数组(按插入顺序存 (hash, key, value))和一个稀疏的 indices 数组(哈希表本体,存 entries 的下标)。查找时用 hash(key) 定位 indices 中的槽,冲突时按伪随机探测序列继续找(开放寻址,不是链表)。装载因子超过 2/3 时扩容并重新插入。这种"紧凑 + 索引"的设计让它既省内存又天然保序。

操作平均说明
d[k], d[k] = v, del d[k], k in dO(1)d[k] 不存在时抛 KeyError
d.get(k, default)O(1)不存在时返回 default(默认 None),不插入
d.setdefault(k, v)O(1)不存在则插入 v,返回 d[k]
d.pop(k[, default])O(1)
d.popitem()O(1)弹出最后插入的项(LIFO)
遍历 for k in d / d.items() / d.values()O(n)按插入顺序;视图对象是动态的
d.copy(), dict(d)O(n)浅拷贝
d1 | d2(3.9+), {**d1, **d2}O(n)合并,右边覆盖左边
counts = {}
for w in "the cat the dog the".split():
    counts[w] = counts.get(w, 0) + 1          # classic counting idiom
assert counts == {"the": 3, "cat": 1, "dog": 1}
assert list(counts) == ["the", "cat", "dog"]  # insertion order preserved

groups = {}
for w in ["eat", "tea", "tan"]:
    groups.setdefault("".join(sorted(w)), []).append(w)
assert groups == {"aet": ["eat", "tea"], "ant": ["tan"]}

d = {"a": 1, "b": 2}
for k, v in d.items():
    pass
assert {v: k for k, v in d.items()} == {1: "a", 2: "b"}   # invert
assert d | {"b": 3, "c": 4} == {"a": 1, "b": 3, "c": 4}
best = max(d, key=d.get)                       # key with the max value
assert best == "b"
try:
    for k in d:
        d["new"] = 0                           # mutate during iteration
except RuntimeError:
    pass
for k in list(d):                              # safe: iterate over a snapshot
    if d[k] == 1:
        del d[k]
assert "a" not in d
print("ok")
直觉为什么最坏是 O(n)?如果大量 key 的哈希值冲突(恶意构造,或自定义 __hash__ 写得很差,比如永远 return 1),探测序列会变成线性扫描。CPython 对 str 使用带随机种子的哈希(PYTHONHASHSEED)来防御哈希洪水攻击,所以字符串的 hash() 每次启动解释器都可能不同;小整数的 hash 就是它本身。
常见误区(1) d[k] += 1 当 k 不存在时报 KeyError → 用 get、defaultdict(int) 或 Counter。(2) if d.get(k): 判断存在性,当值为 0 时出错 → 用 k in d。(3) 用 key in d.keys() 没错但多余,key in d 就行;千万别写 key in list(d.keys())(O(n))。
Say it in English

A dict is a hash table, so lookups, inserts and deletes are constant time on average and linear in the worst case with pathological collisions. Since Python 3.7, dicts are guaranteed to keep insertion order. Keys must be hashable. For counting I'd use get with a default, or more idiomatically a Counter or defaultdict.

追问链
  1. What's the contract between __eq__ and __hash__?
    思路
    如果 a == b,必须有 hash(a) == hash(b)(反之不要求)。否则两个"相等"的 key 会落在不同的槽,dict 会把它们当成两个 key。所以 Python 在你定义 __eq__ 但没定义 __hash__ 时,自动把 __hash__ 设成 None(不可哈希),防止你犯错。另外参与哈希的字段在对象放进 dict 后不能再变。
  2. Why is 1 in {1.0: "x"} true?
    思路
    因为 1 == 1.0 == True 且 hash(1) == hash(1.0) == hash(True) == 1,满足上面的约定,所以它们是同一个 key。{1: "a", True: "b"} 结果是 {1: "b"}。
★

set 与 frozenset

一句话

set 是只有 key 的哈希表:成员测试、添加、删除平均 O(1);支持并 |、交 &、差 -、对称差 ^;空集合要写 set()({} 是空 dict)。

A set is a hash table of keys with O(1) average membership tests and built-in set algebra.

操作平均复杂度
x in s, s.add(x), s.discard(x), s.remove(x)O(1)(remove 不存在时抛 KeyError,discard 不抛)
s | t, s.union(t)O(len(s) + len(t))
s & tO(min(len(s), len(t)))
s - tO(len(s))
s <= t(子集)O(len(s))
set(iterable)O(n)
s.pop()O(1),弹出任意元素(无序!)
a, b = {1, 2, 3}, {2, 3, 4}
assert a | b == {1, 2, 3, 4} and a & b == {2, 3} and a - b == {1} and a ^ b == {1, 4}
assert type({}) is dict and set() == set()
nums = [3, 1, 3, 2, 1]
assert len(set(nums)) == 3                       # count distinct
assert list(dict.fromkeys(nums)) == [3, 1, 2]    # dedupe while KEEPING order
fs = frozenset({1, 2})
memo = {fs: "ok"}                                # frozenset is hashable
seen = set()
def first_dup(xs):
    for x in xs:
        if x in seen:
            return x
        seen.add(x)
assert first_dup([5, 2, 7, 2]) == 2
print("ok")
常见误区依赖 set 的遍历顺序。set 是无序的(小整数常常"看起来"有序,这只是哈希值等于自身的巧合)。需要去重且保序时用 dict.fromkeys(xs)。
Say it in English

A set is essentially a dict without values, so membership tests are constant time on average. Whenever I see a nested loop that's really asking "have I seen this before?", I replace the inner loop with a set lookup, which brings the complexity from O(n²) down to O(n).

★

str:不可变序列、join、切片、ord/chr

一句话

str 不可变:拼接 n 段用 ''.join(parts)(O(总长)),而不是循环 +=(可能 O(n²));字符就是长度为 1 的 str;字符运算用 ord/chr。

Strings are immutable; build them with ''.join, and convert characters with ord and chr.

操作复杂度说明
s[i], len(s)O(1)CPython 内部按最宽字符选定 1/2/4 字节定宽存储(PEP 393),所以下标是 O(1)
s[i:j]O(j − i)复制
sub in s, s.find(sub), s.count(sub), s.replace典型 O(n),最坏 O(n·m)CPython 用优化过的搜索算法,面试中按 O(n·m) 保守回答即可
a + bO(len(a) + len(b))新字符串
''.join(parts)O(总长度)先算总长,一次分配
s.split(), s.strip(), s.lower()O(n)全部返回新对象
s1 == s2, s1 < s2O(min 长度)按码点字典序
hash(s)首次 O(n),之后缓存
s = "Hello, World"
assert s[0] == "H" and s[-1] == "d" and s[::-1] == "dlroW ,olleH"
assert s.lower().split(", ") == ["hello", "world"]
assert "  a b  ".strip() == "a b" and "a,b,,c".split(",") == ["a", "b", "", "c"]
assert "a  b".split() == ["a", "b"]            # no-arg split: any whitespace run, drops empties
assert ord("a") == 97 and chr(97 + 2) == "c"
assert ord("c") - ord("a") == 2                # C's  c - 'a'
assert [ord(ch) - ord("a") for ch in "abz"] == [0, 1, 25]
assert "abc".isalpha() and "123".isdigit() and "a1".isalnum() and " ".isspace()
assert "-".join(["a", "b", "c"]) == "a-b-c"
assert "".join(reversed("abc")) == "cba"
parts = []
for i in range(5):
    parts.append(str(i))                       # O(1) amortized each
assert "".join(parts) == "01234"
assert "ab" * 3 == "ababab"
assert sorted("bca") == ["a", "b", "c"] and "".join(sorted("bca")) == "abc"
assert f"{3.14159:.2f}|{42:5d}|{'x':>3}|{255:b}|{255:x}" == "3.14|   42|  x|11111111|ff"
chars = list("hello")                          # need mutation? convert to list
chars[0] = "j"
assert "".join(chars) == "jello"
assert "abc".startswith("ab") and "abc".endswith("bc") and "abc".find("z") == -1
print("ok")
常见误区(1) 循环里 res += ch:CPython 在引用计数为 1 时有原地扩展的优化,所以常常不慢,但这是实现细节(PyPy 等没有),面试时应主动说"I'll collect pieces in a list and join them"。(2) s.index(x) 不存在时抛 ValueError,s.find(x) 返回 −1。(3) 想修改字符就转 list,改完再 join。
Say it in English

Strings are immutable in Python, so every concatenation creates a new string. Repeated concatenation in a loop can be quadratic, so I collect the pieces in a list and call join once at the end, which is linear. For character arithmetic, like mapping letters to indices, I use ord(c) - ord('a').

★

collections:deque、defaultdict、Counter、OrderedDict

一句话

deque:两端 O(1) 的队列/栈(BFS 必用);defaultdict:自动初始化缺失 key;Counter:计数 + most_common;OrderedDict:move_to_end + popitem(last=False) 实现 LRU。

deque for O(1) operations at both ends, defaultdict for auto-initialized values, Counter for counting, OrderedDict for LRU-style ordering.

deque(double-ended queue)

底层是由定长块(每块 64 个指针)组成的双向链表。两端 append/appendleft/pop/popleft 都是 O(1);但下标访问 dq[i] 是 O(n)(两端附近快,中间慢)。deque(maxlen=k) 是定长环形缓冲区,满了会自动从另一端挤出元素(滑动窗口、最近 k 条记录)。

defaultdict

defaultdict(factory):访问不存在的 key 时调用 factory() 生成默认值并插入。常用 defaultdict(int)(计数)、defaultdict(list)(邻接表、分组)、defaultdict(set)。注意:仅仅读 d[k] 也会插入 key;只想查询用 k in d 或 d.get(k)。

Counter

dict 的子类,值是计数。缺失 key 读出 0(且不插入)。most_common(k) 返回前 k 个 (elem, count),内部用 heapq.nlargest,O(n log k);不带参数则全排序 O(n log n)。支持 + - & |(多重集运算,结果丢弃 ≤0 的计数)。两个 Counter 可以直接 == 比较(判断变位词)。

OrderedDict

普通 dict 已保序,OrderedDict 仍有两个独特操作:move_to_end(k, last=True) 和 popitem(last=False)(弹出最早的),都是 O(1)。这正好是 LRU 缓存需要的(见 练习 LRU)。另外 OrderedDict 的 == 比较考虑顺序。

from collections import deque, defaultdict, Counter, OrderedDict

q = deque([1, 2, 3])
q.append(4); q.appendleft(0)
assert q.popleft() == 0 and q.pop() == 4 and list(q) == [1, 2, 3]
q.rotate(1)                       # [3, 1, 2]
assert list(q) == [3, 1, 2] and q[0] == 3 and q[-1] == 2
last3 = deque(maxlen=3)
for i in range(5):
    last3.append(i)
assert list(last3) == [2, 3, 4]   # oldest items fell off the left

adj = defaultdict(list)
for u, v in [(1, 2), (1, 3), (2, 3)]:
    adj[u].append(v); adj[v].append(u)
assert adj[1] == [2, 3] and adj[3] == [1, 2]
_ = adj[99]                       # reading a missing key INSERTS it
assert 99 in adj and adj[99] == []

c = Counter("abracadabra")
assert c["a"] == 5 and c["z"] == 0 and "z" not in c   # missing -> 0, not inserted
assert c.most_common(2) == [("a", 5), ("b", 2)] or c.most_common(2) == [("a", 5), ("r", 2)]
assert Counter("listen") == Counter("silent")         # anagram check
assert Counter(a=3, b=1) - Counter(a=1, b=2) == Counter(a=2)   # non-positive dropped
c2 = Counter()
c2.update(["x", "y", "x"])
assert c2 == {"x": 2, "y": 1}
assert sum(c.values()) == len("abracadabra")

od = OrderedDict.fromkeys("abc")
od.move_to_end("a")               # b, c, a
assert list(od) == ["b", "c", "a"]
assert od.popitem(last=False)[0] == "b"   # pop the OLDEST
print("ok")
常见误区Counter.most_common 在计数相同时按首次出现顺序返回,不按字母序;题目要求"计数相同按字典序"时要自己排序:sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))。
Say it in English

For BFS I always use collections.deque, since popleft is constant time while list.pop(0) is linear. For grouping or adjacency lists I use defaultdict(list), and for frequency counting I use Counter, which also gives me most_common. If I need an LRU cache, OrderedDict with move_to_end and popitem(last=False) does it in constant time per operation.

★

heapq:最小堆、最大堆、tie-break、top-k

一句话

heapq 在普通 list 上维护最小二叉堆:push/pop O(log n),heap[0] 取最小 O(1),heapify O(n);最大堆存负数;复合元素用 (priority, counter, item)。

heapq maintains a binary min-heap inside a list; negate keys for a max-heap and add a counter as a tie-breaker.

和你在 C 里写的数组堆完全一样:下标 i 的孩子是 2i+1 和 2i+2,父亲是 (i-1)//2,满足 heap[k] <= heap[2k+1] 和 heap[k] <= heap[2k+2]。heapq 只是一组函数,作用在你自己的 list 上,没有 Heap 类。

函数复杂度作用
heapq.heappush(h, x)O(log n)插入(上浮 sift-up)
heapq.heappop(h)O(log n)弹出最小(末元素放到根,下沉)
h[0]O(1)查看最小,不弹出
heapq.heapify(lst)O(n)原地建堆(自底向上下沉)
heapq.heappushpop(h, x)O(log n)先 push 再 pop,比分开调用快
heapq.heapreplace(h, x)O(log n)先 pop 再 push(堆不能为空)
heapq.nlargest(k, it, key=) / nsmallestO(n log k)top-k
heapq.merge(*sorted_iters)O(N log k)惰性合并 k 个有序序列

为什么 heapify 是 O(n) 而不是 O(n log n)?自底向上:高度为 h 的节点最多 \( \lceil n/2^{h+1} \rceil \) 个,每个下沉代价 O(h),总和 \( \sum_h \frac{n}{2^{h+1}} h = O(n) \)(因为 \( \sum_h h/2^h = 2 \))。

最大堆:push -x,pop 后取负。(Python 3.14 新增了公开的 heapq.heappush_max 等最大堆函数,但面试环境多为旧版本,负数技巧最保险。)

tie-break:tuple 按字典序比较。若 (priority, item) 中 priority 相同,Python 会去比较 item;如果 item 是不可比较的对象(如自定义节点、dict),就会抛 TypeError。解决:插入一个单调递增的计数器 (priority, next(counter), item),它保证唯一,比较到它就停下,同时让相同优先级按 FIFO 出堆。

import heapq, itertools

h = []
for x in [5, 1, 4, 2]:
    heapq.heappush(h, x)
assert h[0] == 1
assert [heapq.heappop(h) for _ in range(4)] == [1, 2, 4, 5]

nums = [3, 9, 1, 7]
mx = [-x for x in nums]; heapq.heapify(mx)          # max-heap via negation
assert -heapq.heappop(mx) == 9

class Task:                                         # NOT comparable
    def __init__(self, name): self.name = name
tasks = []
cnt = itertools.count()
heapq.heappush(tasks, (2, next(cnt), Task("b")))
heapq.heappush(tasks, (1, next(cnt), Task("a")))
heapq.heappush(tasks, (2, next(cnt), Task("c")))    # same priority as "b": counter decides
assert [heapq.heappop(tasks)[2].name for _ in range(3)] == ["a", "b", "c"]
try:
    bad = []
    heapq.heappush(bad, (1, Task("x"))); heapq.heappush(bad, (1, Task("y")))
except TypeError:
    pass                                            # '<' not supported between Task objects

def top_k_largest(nums, k):                         # size-k MIN-heap: O(n log k)
    h = []
    for x in nums:
        if len(h) < k:
            heapq.heappush(h, x)
        elif x > h[0]:
            heapq.heapreplace(h, x)                 # drop current min, add x
    return sorted(h, reverse=True)

data = [5, 1, 9, 3, 7, 9, 2]
assert top_k_largest(data, 3) == [9, 9, 7] == heapq.nlargest(3, data)
assert heapq.nsmallest(2, ["bb", "a", "ccc"], key=len) == ["a", "bb"]
assert list(heapq.merge([1, 4], [2, 3], [0])) == [0, 1, 2, 3, 4]
print("ok")
直觉求最大的 k 个要用最小堆:堆顶是"当前 k 个候选里最弱的一个",新元素只需和它比较——比它强就把它踢掉。这样堆大小始终是 k,每步 O(log k)。反过来,求最小的 k 个用(取负的)最大堆。

"删除任意元素/更新优先级":heapq 不支持 decrease-key。标准做法是惰性删除:直接 push 新条目,pop 出来时检查是否过期(Dijkstra 里 if d > dist[u]: continue)。

常见误区(1) 以为 h 整体有序——只保证 h[0] 最小,h[1] 不一定是第二小。(2) 对已有 list 直接 heappop 而忘了 heapify。(3) 最大堆取负后忘了再取负回来。(4) 用 heapq.heappush(h, (prio, node)) 而 node 是不可比较的 TreeNode。
Say it in English

Python's heapq is a binary min-heap stored in a plain list. Push and pop are logarithmic, peeking at heap[0] is constant, and heapify is linear. For a max-heap I push negated values. When entries are tuples, I add a monotonically increasing counter as the second field so that ties never fall through to comparing objects that aren't orderable. For top-k largest I keep a min-heap of size k, which is O(n log k).

追问链
  1. Top-k: when would you use a heap vs sorting vs quickselect?
    思路
    排序 O(n log n),最简单,k 接近 n 时也不差。大小为 k 的堆 O(n log k),空间 O(k),适合流式数据和 k ≪ n。Quickselect 平均 O(n)、最坏 O(n²)(随机化 pivot 缓解),但需要能原地修改整个数组、不适合流。如果值域小,计数/桶排序 O(n + 值域)(Top K Frequent 用桶)。
  2. How do you find the running median of a stream?
    思路
    两个堆:左半部分用最大堆(存负数),右半部分用最小堆;保持 len(left) == len(right) 或多 1。插入后平衡,中位数是 -left[0] 或两个堆顶的均值。每次插入 O(log n),查询 O(1)。
★

bisect:有序数组上的二分

一句话

bisect_left(a, x) = 第一个 ≥ x 的位置(lower_bound);bisect_right(a, x) = 第一个 > x 的位置(upper_bound);查找 O(log n),但 insort 插入是 O(n)。

bisect_left is lower_bound, bisect_right is upper_bound; searching is O(log n) but inserting into a list is O(n).

from bisect import bisect_left, bisect_right, insort

a = [1, 2, 4, 4, 4, 7]
assert bisect_left(a, 4) == 2        # first index with a[i] >= 4
assert bisect_right(a, 4) == 5       # first index with a[i] > 4
assert bisect_right(a, 4) - bisect_left(a, 4) == 3   # count of 4s
assert bisect_left(a, 5) == bisect_right(a, 5) == 5  # absent: both = insertion point
assert bisect_left(a, 0) == 0 and bisect_left(a, 100) == len(a)

def contains(a, x):
    i = bisect_left(a, x)
    return i < len(a) and a[i] == x
assert contains(a, 7) and not contains(a, 3)

# count elements in [lo, hi]
assert bisect_right(a, 4) - bisect_left(a, 2) == 4   # 2,4,4,4

# key= (Python 3.10+): search a list of records sorted by a field
recs = [("a", 1), ("b", 3), ("c", 5)]
assert bisect_left(recs, 3, key=lambda r: r[1]) == 1

b = [1, 3]
insort(b, 2)                         # O(n): binary search + list.insert
assert b == [1, 2, 3]

# grade lookup table: classic bisect idiom
def grade(score, cuts=[60, 70, 80, 90], letters="FDCBA"):
    return letters[bisect_right(cuts, score)]
assert [grade(s) for s in [33, 60, 75, 89, 90, 100]] == list("FDCBAA")
print("ok")

记忆方式:bisect_left 返回的 i 满足 all(v < x for v in a[:i]) 且 all(v >= x for v in a[i:]);bisect_right 把 < 换成 <=。手写版本见 §9 二分模板(面试官经常要求不用库手写)。

Say it in English

bisect_left returns the first position where the element is greater than or equal to the target, which is the lower bound; bisect_right returns the first position strictly greater. Their difference gives the count of the target. Lookup is logarithmic, but note that insort is linear because inserting into a Python list shifts elements.

★

一页复杂度速查表 + "什么模式用什么结构"

一句话

查存在用 set、计数用 Counter、分组用 defaultdict(list)、队列用 deque、动态最值用 heapq、有序查找用 bisect、栈用 list。

Set for membership, Counter for counts, defaultdict for grouping, deque for queues, heapq for dynamic min/max, bisect for sorted lookups, list for stacks.

结构访问查找 in插入删除备注
listO(1)O(n)尾 O(1)* / 头 O(n)尾 O(1) / 头 O(n)排序 O(n log n)
tupleO(1)O(n)——可哈希
dictO(1)†O(1)†O(1)†O(1)†保序
set—O(1)†O(1)†O(1)†集合运算
deque两端 O(1),中间 O(n)O(n)两端 O(1)两端 O(1)maxlen 环形缓冲
heapq (list)最小 O(1)O(n)O(log n)最小 O(log n)heapify O(n)
sorted list + bisectO(1)O(log n)O(n)O(n)需要平衡树时可提 sortedcontainers(非标准库)
strO(1)O(n·m) 最坏—(不可变)—join O(n)

* 均摊;† 平均情况,最坏 O(n)。

面试信号 / 模式首选结构例子
"是否见过"、去重、O(1) 判存在setContains Duplicate、Longest Consecutive Sequence
"补数"查找、值 → 下标dictTwo Sum
频率统计、变位词CounterTop K Frequent、Valid Anagram
按某个签名分组defaultdict(list)Group Anagrams
图的邻接表defaultdict(list) 或 [[] for _ in range(n)]Course Schedule
BFS、层序遍历、最短步数(无权)dequeNumber of Islands、Rotting Oranges
滑动窗口最大/最小值deque(单调队列)Sliding Window Maximum
括号匹配、"下一个更大元素"、撤销list 当栈(单调栈)Valid Parentheses、Daily Temperatures
动态取最值、top-k、合并 k 路、调度heapqKth Largest、Merge k Sorted Lists、Dijkstra
有序数组查找、"第一个满足条件的位置"bisect / 手写二分Search Insert Position、LIS O(n log n)
前缀和 + "之前出现过多少次"dict(prefix → count)Subarray Sum Equals K
LRU / 最近使用顺序OrderedDict(或 dict + 双向链表)LRU Cache
连通性、动态合并集合并查集(list 实现)Redundant Connection、Accounts Merge
前缀匹配、单词搜索Trie(嵌套 dict)Implement Trie、Word Search II
Say it in English

My first move when optimizing is usually to ask which operation dominates and pick a data structure that makes it cheap: a set or dict for constant-time lookup, a deque for queue operations at both ends, a heap when I repeatedly need the current minimum or maximum, and binary search when the data is sorted.

§4 · IDIOMS惯用写法:写得短、写得对、写得像 Python

面试官读你的代码时,"Pythonic" 的写法会传达"这个人熟练"的信号;更重要的是,惯用写法通常更短、更不容易错(没有手动下标就没有 off-by-one)。这一节是你从 C 风格切换到 Python 风格的核心清单。

★

推导式与生成器表达式

一句话

[f(x) for x in xs if p(x)] 立即生成 list;(f(x) for x in xs) 是惰性生成器,O(1) 内存、只能遍历一次;dict/set 推导式同理 {k: v for …}、{x for …}。

Comprehensions build collections eagerly; generator expressions produce values lazily with constant memory.

C 风格(在 Python 里也能跑,但啰嗦)
squares = []
for x in range(10):
    if x % 2 == 0:
        squares.append(x * x)

total = 0
for x in nums:
    total += x * x
PYTHONIC
squares = [x * x for x in range(10) if x % 2 == 0]

total = sum(x * x for x in nums)   # no brackets needed
                                    # when it's the only arg
nums = [3, -1, 4, -1, 5]
assert [x * x for x in range(10) if x % 2 == 0] == [0, 4, 16, 36, 64]
assert [x if x > 0 else 0 for x in nums] == [3, 0, 4, 0, 5]   # if-ELSE goes BEFORE for
assert {x for x in nums} == {3, -1, 4, 5}
assert {w: len(w) for w in ["a", "bb"]} == {"a": 1, "bb": 2}
# nested: order of `for` clauses = order of nested loops
pairs = [(i, j) for i in range(3) for j in range(i)]
assert pairs == [(1, 0), (2, 0), (2, 1)]
matrix = [[1, 2], [3, 4]]
assert [x for row in matrix for x in row] == [1, 2, 3, 4]      # flatten
assert [[row[c] for row in matrix] for c in range(2)] == [[1, 3], [2, 4]]

gen = (x * x for x in range(5))
assert next(gen) == 0
assert list(gen) == [1, 4, 9, 16]
assert list(gen) == []                    # exhausted: single pass only!
assert sum(x * x for x in range(10**6)) == 333332833333500000   # O(1) memory
assert any(x < 0 for x in nums) and not all(x > 0 for x in nums)
print("ok")

推导式有自己的作用域(循环变量不会泄漏到外面),而且通常比等价的 for+append 快一些(少了属性查找 .append 和函数调用开销)。

常见误区(1) 条件表达式的位置:过滤用 [x for x in xs if c](if 在后面),映射分支用 [a if c else b for x in xs](if-else 在前面)。(2) 生成器只能遍历一次,第二次是空的——把生成器传给两个函数是常见 bug。(3) 嵌套超过两层的推导式可读性很差,面试时宁可写普通循环。
Say it in English

A list comprehension builds the whole list eagerly, while a generator expression yields items lazily, so it uses constant memory but can only be iterated once. When I just need to feed values into sum, any or max, I use a generator expression.

★

排序:key、多关键字、稳定性、cmp_to_key

一句话

a.sort() 原地、返回 None;sorted(it) 返回新 list;用 key= 指定排序依据,多关键字返回 tuple,降序数值字段取负;Timsort 稳定、O(n log n);自定义比较函数用 functools.cmp_to_key。

Sort with a key function returning a tuple for multiple criteria; Python's sort is stable, and cmp_to_key adapts a C-style comparator.

C 的 qsort 需要一个比较函数 int cmp(const void*, const void*)。Python 3 去掉了 cmp= 参数,改用 key:对每个元素调用一次 key(x)(共 n 次,而比较函数要调 O(n log n) 次),然后比较 key 的值。

from functools import cmp_to_key
from operator import itemgetter

words = ["banana", "Apple", "cherry", "fig"]
assert sorted(words) == ["Apple", "banana", "cherry", "fig"]          # uppercase < lowercase
assert sorted(words, key=str.lower) == ["Apple", "banana", "cherry", "fig"]
assert sorted(words, key=len) == ["fig", "Apple", "banana", "cherry"] # stable among ties
assert sorted(words, key=len, reverse=True) == ["banana", "cherry", "Apple", "fig"]

pairs = [(1, "b"), (3, "a"), (2, "b"), (1, "a")]
# by 2nd field ascending, then 1st field DESCENDING (numeric -> negate)
assert sorted(pairs, key=lambda p: (p[1], -p[0])) == [(3, "a"), (1, "a"), (2, "b"), (1, "b")]
assert sorted(pairs, key=itemgetter(1, 0)) == [(1, "a"), (3, "a"), (1, "b"), (2, "b")]

# Descending on a STRING field can't be negated: use stability, two passes
people = [("bob", 25), ("amy", 30), ("cat", 25)]
tmp = sorted(people, key=lambda p: p[0], reverse=True)     # secondary first
res = sorted(tmp, key=lambda p: p[1])                      # primary last
assert res == [("cat", 25), ("bob", 25), ("amy", 30)]      # age asc, name desc

# Comparator: "Largest Number" -- order strings so that concatenation is max
def cmp(a, b):
    return -1 if a + b > b + a else (1 if a + b < b + a else 0)
nums = [3, 30, 34, 5, 9]
s = "".join(sorted(map(str, nums), key=cmp_to_key(cmp)))
assert s == "9534330"

a = [3, 1, 2]
assert a.sort() is None and a == [1, 2, 3]                 # in place, returns None
assert sorted({"b": 1, "a": 2}) == ["a", "b"]              # any iterable
d = {"x": 3, "y": 1}
assert sorted(d.items(), key=lambda kv: kv[1]) == [("y", 1), ("x", 3)]
print("ok")
直觉稳定:key 相等的元素保持原来的相对顺序。这让"先按次要关键字排、再按主要关键字排"得到多关键字排序成立——第二次排序不会打乱第一次已经排好的次序。Timsort 是归并排序 + 插入排序的混合,利用数据中已有的有序片段(runs),对部分有序数据很快。
常见误区(1) a = a.sort()。(2) 降序字符串字段不能取负 → 用两次稳定排序或 cmp_to_key。(3) 比较函数必须返回负/零/正的整数,不是 bool(返回 a < b 会出错)。(4) 混合类型([1, "a"])排序会抛 TypeError。
Say it in English

I'd use sorted with a key function. For multiple criteria the key returns a tuple, and for a descending numeric field I negate it. Python's sort is Timsort, which is stable and O(n log n), so I can also do multi-pass sorting from the least significant key to the most significant. If the ordering is genuinely pairwise, like in the "largest number" problem, I wrap a comparator with functools.cmp_to_key.

★

解包、*args/**kwargs、关键字参数、lambda

一句话

定义时 *args 收集多余位置参数为 tuple、**kwargs 收集多余关键字参数为 dict;调用时 f(*lst, **d) 把容器展开成参数;lambda 是只含一个表达式的匿名函数。

*args and **kwargs collect extra arguments; * and ** at a call site unpack them.

def f(a, b=2, *args, scale=1, **kwargs):     # scale is keyword-only (after *args)
    return a, b, args, scale, kwargs

assert f(1) == (1, 2, (), 1, {})
assert f(1, 3, 4, 5, scale=10, mode="x") == (1, 3, (4, 5), 10, {"mode": "x"})

def g(x, /, y, *, z):      # x positional-only, z keyword-only
    return x + y + z
assert g(1, y=2, z=3) == 6

def wrapper(*args, **kwargs):                # forward everything (decorators, nn.Module)
    return f(*args, **kwargs)
assert wrapper(1, scale=5) == (1, 2, (), 5, {})

pt = (3, 4)
import math
assert math.hypot(*pt) == 5.0               # unpack tuple into positional args
cfg = {"b": 9, "scale": 2}
assert f(0, **cfg) == (0, 9, (), 2, {})
assert [*range(3), *"ab"] == [0, 1, 2, "a", "b"]
assert {**{"a": 1}, "b": 2} == {"a": 1, "b": 2}
assert max([], default=0) == 0               # keyword args with defaults

add = lambda x, y: x + y                    # same as def add(x, y): return x + y
assert add(2, 3) == 5
assert sorted([(1, "b"), (0, "c")], key=lambda t: t[1])[0] == (1, "b")
print("ok")

和 PyTorch 的联系:nn.Module.__call__(self, *args, **kwargs) 把所有参数原样转发给你的 forward;配置对象常用 Model(**config) 展开构造。

常见误区lambda 闭包的延迟绑定:fs = [lambda: i for i in range(3)],调用全部返回 2,因为 lambda 捕获的是变量 i(名字),调用时才查值。修正:lambda i=i: i(用默认参数在定义时绑定当前值)。
Say it in English

In a function definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. At a call site, the same stars unpack a sequence or a mapping into arguments. That's the standard way to write wrappers that forward everything, which is exactly what nn.Module.__call__ does with forward.

★

作用域、闭包与 nonlocal(DFS 计数器)

一句话

名字查找顺序 LEGB;内层函数可以读外层变量,但对外层变量赋值(包括 +=)会让它变成内层的局部变量,除非声明 nonlocal(外层函数)或 global(模块级)。

Inner functions can read enclosing variables, but rebinding them requires nonlocal; mutating a container does not.

Python 在编译函数时决定每个名字的作用域:只要函数体中任何地方对名字赋值,它在整个函数里都是局部变量。所以下面的 count += 1 会报 UnboundLocalError——它被认为是局部变量,但读的时候还没赋值。

def count_nodes_wrong(tree):
    count = 0
    def dfs(node):
        if node is None:
            return
        count += 1               # UnboundLocalError: count is local to dfs
        dfs(node[1]); dfs(node[2])
    dfs(tree)
    return count

def count_nodes(tree):
    count = 0
    def dfs(node):
        nonlocal count           # rebind the ENCLOSING variable
        if node is None:
            return
        count += 1
        dfs(node[1]); dfs(node[2])
    dfs(tree)
    return count

def collect(tree):
    out = []                     # mutation needs no nonlocal
    def dfs(node):
        if node:
            dfs(node[1]); out.append(node[0]); dfs(node[2])
    dfs(tree)
    return out

tree = (2, (1, None, None), (3, None, None))    # (val, left, right)
try:
    count_nodes_wrong(tree)
    raise AssertionError
except UnboundLocalError:
    pass
assert count_nodes(tree) == 3
assert collect(tree) == [1, 2, 3]

def make_counter():              # closure: inner function keeps `n` alive
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc
c1, c2 = make_counter(), make_counter()
assert (c1(), c1(), c2()) == (1, 2, 1)
assert c1.__closure__[0].cell_contents == 2

fs = [lambda: i for i in range(3)]
assert [f() for f in fs] == [2, 2, 2]           # late binding
fs = [lambda i=i: i for i in range(3)]
assert [f() for f in fs] == [0, 1, 2]
print("ok")

面试中 DFS 维护全局最优值(如 Binary Tree Maximum Path Sum、Diameter)有三种写法:nonlocal best;用可变容器 best = [0] 再改 best[0];或写成类的属性 self.best(LeetCode 风格)。第一种最清楚。

Say it in English

Python decides a variable's scope at compile time: if a function assigns to a name anywhere, that name is local to the function. So inside a nested DFS helper, incrementing a counter from the outer function raises UnboundLocalError unless I declare it nonlocal. Mutating an outer list, like appending to it, is fine without the declaration because it doesn't rebind the name.

★

lru_cache/cache 记忆化与递归深度

一句话

@functools.cache(3.9+,等于 lru_cache(maxsize=None))把函数变成带记忆的版本,参数必须可哈希;默认递归上限约 1000,深递归要 sys.setrecursionlimit 或改迭代。

functools.cache memoizes a function on hashable arguments; Python's default recursion limit is about 1000.

import sys
from functools import cache, lru_cache

@cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
assert fib(90) == 2880067194370816120            # instant; exponential without cache
assert fib.cache_info().hits > 0

@lru_cache(maxsize=None)
def grid_paths(r, c):                            # top-down DP: unique paths
    if r == 0 or c == 0:
        return 1
    return grid_paths(r - 1, c) + grid_paths(r, c - 1)
assert grid_paths(2, 2) == 6
grid_paths.cache_clear()                          # reset between test cases!

def edit_distance(a, b):
    @cache
    def dp(i, j):                                 # cache a closure: fresh per call
        if i == len(a): return len(b) - j
        if j == len(b): return len(a) - i
        if a[i] == b[j]: return dp(i + 1, j + 1)
        return 1 + min(dp(i + 1, j), dp(i, j + 1), dp(i + 1, j + 1))
    return dp(0, 0)
assert edit_distance("horse", "ros") == 3

@cache
def bad(xs):
    return len(xs)
try:
    bad([1, 2])                                   # lists are unhashable
except TypeError:
    pass
assert bad((1, 2)) == 2                           # pass tuples instead

assert sys.getrecursionlimit() >= 1000
def depth(n):
    return 0 if n == 0 else 1 + depth(n - 1)
try:
    depth(10**5)
except RecursionError:
    pass
sys.setrecursionlimit(20000)
assert depth(15000) == 15000                      # works now (C stack permitting)
print("ok")
  • @cache 在函数对象上保存一个以参数为 key 的 dict,所以参数必须可哈希(list → tuple,set → frozenset)。
  • 把 @cache 写在外层函数的内部(如上面的 edit_distance),每次调用外层函数都有一个新缓存,避免不同测试用例之间串数据,也避免内存一直增长。
  • 递归 + 记忆化的空间:缓存 O(状态数) + 栈 O(递归深度)。深度上万时,setrecursionlimit 只是提高 Python 的检查阈值,真正的 C 栈仍可能溢出导致进程崩溃(segfault)。稳妥的做法是改成自底向上的表格 DP(见 §9 DP 模板)。
Say it in English

For top-down dynamic programming I write the recursive function and decorate it with functools.cache, which memoizes results keyed on the arguments, so they must be hashable. The caveat is Python's recursion limit of about a thousand frames; if the depth could be large, I'd either raise the limit or, more robustly, convert it to a bottom-up table.

☆

any/all/min/max(key)、f-string、itertools 精选

一句话

熟练使用内置函数能把 5 行循环变成 1 行:max(xs, key=f)、any(...)、sum(...);itertools 里 accumulate、product、permutations、combinations、groupby、chain、pairwise 最常用。

Built-ins and itertools replace many hand-written loops: max with key, any/all, accumulate, product, combinations, groupby.

from itertools import (accumulate, product, permutations, combinations,
                       combinations_with_replacement, groupby, chain, islice, count, pairwise)
import operator

words = ["aa", "b", "cccc", "dd"]
assert max(words, key=len) == "cccc" and min(words, key=len) == "b"
assert max(range(5), key=lambda i: -abs(i - 2)) == 2       # argmax idiom
arr = [4, 9, 2]
assert max(range(len(arr)), key=arr.__getitem__) == 1      # index of max
assert min([], default=None) is None
assert any(w.startswith("c") for w in words) and all(len(w) >= 1 for w in words)

assert list(accumulate([1, 2, 3, 4])) == [1, 3, 6, 10]                # prefix sums
assert list(accumulate([1, 2, 3, 4], initial=0)) == [0, 1, 3, 6, 10]
assert list(accumulate([3, 1, 4, 1], max)) == [3, 3, 4, 4]           # running max
assert list(accumulate([1, 2, 3], operator.mul)) == [1, 2, 6]
assert list(product([0, 1], repeat=2)) == [(0, 0), (0, 1), (1, 0), (1, 1)]
assert len(list(permutations("abc"))) == 6
assert list(combinations([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)]
assert len(list(combinations_with_replacement("ab", 2))) == 3
assert [(k, len(list(g))) for k, g in groupby("aaabccaa")] == [("a", 3), ("b", 1), ("c", 2), ("a", 2)]
# ^ groupby groups CONSECUTIVE equal keys only -> sort first for global grouping
assert list(chain([1], [2, 3], (4,))) == [1, 2, 3, 4]
assert list(chain.from_iterable([[1], [2, 3]])) == [1, 2, 3]
assert list(islice(count(10, 5), 3)) == [10, 15, 20]
assert list(pairwise([1, 4, 9])) == [(1, 4), (4, 9)]

x, name = 3.14159, "loss"
assert f"{name}={x:.3f}" == "loss=3.142"
assert f"{x=:.2f}" == "x=3.14"                       # self-documenting (3.8+)
assert f"{1234567:,}" == "1,234,567" and f"{0.25:.1%}" == "25.0%"
assert f"{7:03d}|{'ab':<4}|{'ab':^6}|" == "007|ab  |  ab  |"
assert f"{1e-5:.2e}" == "1.00e-05"
print("ok")
itertools用途注意
accumulate前缀和、前缀最大值initial=0 得到长度 n+1 的前缀和
product笛卡尔积、多重循环、四方向repeat=k
permutations / combinations暴力枚举、对拍面试中被要求"自己实现"时要会回溯写法
groupby游程编码、连续段只合并相邻相同元素
chain拼接多个可迭代对象惰性
islice、count截取无限迭代器
pairwise相邻对3.10+
Say it in English

I lean on built-ins where they make the intent clearer: max with a key for argmax, any and all with generator expressions for short-circuit checks, and itertools.accumulate for prefix sums. For brute-force verification I'll use itertools.permutations or combinations, but I can also write the backtracking version if you'd like.

§5 · CLASSES类:从 struct 到 nn.Module

算法面试里类用得不多(LRU Cache、Trie、MinStack 这类"设计题"会用到),但 ML coding 和读 PyTorch 代码时处处都是类:class MyModel(nn.Module)、super().__init__()、model(x) 调用 forward。这一节用 C 的 struct + 函数指针来解释 Python 的类,并把每个知识点直接连到 PyTorch。

★

class vs struct;self;实例属性 vs 类属性陷阱

一句话

类 ≈ "struct + 绑定在上面的函数";self 就是 C 里你手动传的 struct Foo *this;在 __init__ 里 self.x = … 创建实例属性;写在类体里的变量是所有实例共享的类属性——可变类属性是经典 bug。

A class bundles data and functions; self is the explicit instance pointer, and mutable class attributes are shared by all instances.

C
#include <stdio.h>

typedef struct { double balance; } Account;

void account_init(Account *self, double b) { self->balance = b; }
void account_deposit(Account *self, double x) { self->balance += x; }

int main(void) {
    Account a;
    account_init(&a, 100);
    account_deposit(&a, 50);
    printf("%.1f\n", a.balance);
    return 0;
}
PYTHON
class Account:
    def __init__(self, balance):   # constructor (initializer)
        self.balance = balance     # instance attribute

    def deposit(self, x):          # self passed implicitly
        self.balance += x

a = Account(100)
a.deposit(50)          # == Account.deposit(a, 50)
assert a.balance == 150
assert Account.deposit(a, 1) is None and a.balance == 151
print("ok")

a.deposit(50) 本质上就是 Account.deposit(a, 50):Python 在属性查找时把函数和实例"绑定"成一个 bound method,调用时自动把 a 作为第一个参数。self 不是关键字,只是约定的名字。

属性查找顺序:先找实例自己的 __dict__,找不到再去类(以及父类,按 MRO 顺序)找。赋值 obj.x = … 永远写到实例的 __dict__。

class Bad:
    items = []                     # CLASS attribute: one list shared by all instances
    def add(self, x):
        self.items.append(x)       # finds Bad.items via lookup, then MUTATES it

a, b = Bad(), Bad()
a.add(1)
assert b.items == [1]              # surprise!

class Good:
    count = 0                      # class attribute used intentionally (shared counter)
    def __init__(self):
        self.items = []            # instance attribute: one per object
        Good.count += 1            # must write via the CLASS name
a, b = Good(), Good()
a.items.append(1)
assert b.items == [] and Good.count == 2

class Shadow:
    n = 0
s = Shadow()
s.n += 1                           # reads Shadow.n (0), WRITES instance attr s.n = 1
assert s.n == 1 and Shadow.n == 0 and "n" in s.__dict__
print("ok")
常见误区把可变默认状态写在类体里(class Node: children = []),所有节点共享同一个 children 列表——Trie 题的经典 bug。所有可变的每实例状态都要放在 __init__ 里。
Say it in English

A method is just a function whose first parameter is the instance, conventionally called self, much like passing a struct pointer explicitly in C. Attributes assigned in __init__ belong to each instance, while variables defined in the class body are class attributes shared by every instance, so a mutable class attribute like a list is a classic bug.

★

dunder 方法:__repr__ __eq__ __hash__ __lt__ __len__ __getitem__ __iter__ __call__

一句话

双下划线方法是 Python 的"运算符重载/协议":len(x) 调 x.__len__(),x[i] 调 __getitem__,x < y 调 __lt__,x(...) 调 __call__——model(x) 能跑 forward 正是因为 nn.Module 实现了 __call__。

Dunder methods implement Python's protocols; model(x) works because nn.Module.__call__ invokes forward plus hooks.

方法触发面试/ML 场景
__init__Cls(...)初始化(真正分配对象的是 __new__,很少需要碰)
__repr__ / __str__repr(x)、REPL 显示 / print(x)调试;__str__ 缺省时用 __repr__
__eq__==定义后若没定义 __hash__,实例变为不可哈希
__hash__hash(x)、dict key、set相等对象必须同哈希
__lt__<、sorted、heapq让节点能直接进堆(如 ListNode 合并 k 路)
__len__len(x)、真值Dataset.__len__
__getitem__x[i]、切片、(无 __iter__ 时)迭代Dataset.__getitem__(idx)
__iter__ / __next__for v in xDataLoader 是可迭代对象(§6)
__contains__v in x
__call__x(...)nn.Module:model(x) → hooks + forward(x)
__enter__ / __exit__with x:torch.no_grad()(§6)
__add__, __mul__, __matmul__…+ * @Tensor 运算、micrograd 的 Value 类(见 01)
import heapq

class Vec:
    def __init__(self, *xs):
        self.xs = list(xs)
    def __repr__(self):
        return f"Vec({', '.join(map(str, self.xs))})"
    def __len__(self):
        return len(self.xs)
    def __getitem__(self, i):            # supports v[0], v[-1], v[1:], and iteration
        return self.xs[i]
    def __eq__(self, other):
        return isinstance(other, Vec) and self.xs == other.xs
    def __hash__(self):                  # must be consistent with __eq__
        return hash(tuple(self.xs))
    def __add__(self, other):
        return Vec(*(a + b for a, b in zip(self.xs, other.xs)))
    def __lt__(self, other):             # enables sorted() and heapq
        return sum(self.xs) < sum(other.xs)

v, w = Vec(1, 2), Vec(3, 4)
assert repr(v + w) == "Vec(4, 6)" and len(v) == 2 and v[-1] == 2 and list(w) == [3, 4]
assert {Vec(1, 2): "a"}[Vec(1, 2)] == "a"            # hashable + equal
assert min([w, v]) is v and sorted([w, v])[0] is v

class ListNode:
    def __init__(self, val, nxt=None):
        self.val, self.next = val, nxt
    def __lt__(self, other):                         # so nodes can go straight into heapq
        return self.val < other.val
h = [ListNode(3), ListNode(1), ListNode(2)]
heapq.heapify(h)
assert heapq.heappop(h).val == 1

class OnlyEq:
    def __eq__(self, other): return True
try:
    hash(OnlyEq())                                   # __hash__ was set to None
except TypeError:
    pass

class Module:                                        # a toy nn.Module
    def __call__(self, *args, **kwargs):
        # real PyTorch: run forward pre-hooks, then forward, then forward hooks
        return self.forward(*args, **kwargs)
class Double(Module):
    def forward(self, x):
        return 2 * x
m = Double()
assert m(21) == 42                                   # model(x), never model.forward(x)
print("ok")
常见误区在 PyTorch 里直接调用 model.forward(x) 而不是 model(x):会绕过 __call__ 中注册的 hooks(比如某些分析工具、FSDP 等依赖 hook 的封装),行为可能不同。永远写 model(x)。
Say it in English

Dunder methods are how a class plugs into Python's built-in protocols. len calls __len__, indexing calls __getitem__, comparisons call __lt__ and friends, and calling an object like a function invokes __call__. That's why we write model(x) in PyTorch: nn.Module.__call__ runs any registered hooks and then dispatches to forward.

☆

@dataclass(order=True, frozen=True)

一句话

@dataclass 根据带类型注解的字段自动生成 __init__、__repr__、__eq__;order=True 加上按字段顺序比较的 < 等;frozen=True 使实例不可变且可哈希。最接近 C struct 的写法。

dataclass generates boilerplate from annotated fields; order=True adds comparisons and frozen=True makes instances immutable and hashable.

from dataclasses import dataclass, field
import heapq

@dataclass
class Config:
    d_model: int = 512
    n_layers: int = 6
    dropout: float = 0.1
    tags: list = field(default_factory=list)   # mutable default must use a factory

c = Config(n_layers=12)
assert c == Config(512, 12, 0.1, [])
assert repr(c) == "Config(d_model=512, n_layers=12, dropout=0.1, tags=[])"

@dataclass(order=True)
class Job:
    priority: int
    name: str = field(compare=False)           # excluded from ordering/eq
h = []
heapq.heappush(h, Job(2, "b")); heapq.heappush(h, Job(1, "a"))
assert heapq.heappop(h).name == "a"

@dataclass(frozen=True)
class Point:
    x: int
    y: int
p = Point(1, 2)
assert {p: "ok"}[Point(1, 2)] == "ok"          # frozen + eq -> hashable
try:
    p.x = 5
except Exception as e:
    assert type(e).__name__ == "FrozenInstanceError"
try:
    @dataclass
    class Bad:
        xs: list = []                          # rejected at class creation
except ValueError:
    pass
print("ok")
Say it in English

A dataclass is the closest thing to a C struct: I list typed fields and Python generates the initializer, repr and equality. With order=True instances compare field by field, which is handy for heap entries, and frozen=True makes them immutable and hashable. It also refuses a bare mutable default, forcing default_factory.

★

继承与 super().__init__()(为什么 nn.Module 必须先调它)

一句话

子类 class B(A) 继承 A 的方法,可以覆盖;子类定义 __init__ 后父类的 __init__ 不会自动调用,要显式 super().__init__();nn.Module.__init__ 创建参数/子模块注册表,必须在给 self 赋子模块之前调用。

A subclass __init__ doesn't call the parent's automatically; nn.Module.__init__ sets up the registries that __setattr__ relies on.

和 C++ 不同,Python 不会自动调用父类构造函数。PyTorch 的 nn.Module 重写了 __setattr__:当你写 self.fc = nn.Linear(…) 时,它检查值的类型,若是 Parameter 就放进 self._parameters,若是 Module 就放进 self._modules。这些 dict 是在 nn.Module.__init__ 中创建的——不先调用它,赋值就会报错("cannot assign module before Module.__init__() call")。

class Param:
    def __init__(self, v): self.v = v

class Module:                               # a minimal imitation of torch.nn.Module
    def __init__(self):
        object.__setattr__(self, "_params", {})
        object.__setattr__(self, "_modules", {})
    def __setattr__(self, name, value):
        if isinstance(value, Param):
            if "_params" not in self.__dict__:
                raise AttributeError("cannot assign parameters before Module.__init__() call")
            self._params[name] = value
        elif isinstance(value, Module):
            if "_modules" not in self.__dict__:
                raise AttributeError("cannot assign module before Module.__init__() call")
            self._modules[name] = value
        object.__setattr__(self, name, value)
    def parameters(self):                   # recursive, like the real one
        yield from self._params.values()
        for m in self._modules.values():
            yield from m.parameters()
    def __call__(self, *a, **k):
        return self.forward(*a, **k)

class Linear(Module):
    def __init__(self, w, b):
        super().__init__()                  # MUST come first
        self.w, self.b = Param(w), Param(b)
    def forward(self, x):
        return self.w.v * x + self.b.v

class MLP(Module):
    def __init__(self):
        super().__init__()
        self.l1 = Linear(2.0, 1.0)
        self.l2 = Linear(3.0, 0.0)
    def forward(self, x):
        return self.l2(self.l1(x))

m = MLP()
assert m(1.0) == 9.0 and len(list(m.parameters())) == 4

class Forgot(Module):
    def __init__(self):
        self.l1 = Linear(1.0, 0.0)          # no super().__init__()
try:
    Forgot()
    raise AssertionError
except AttributeError as e:
    assert "before Module.__init__" in str(e)

class A:
    def hi(self): return "A"
class B(A):
    def hi(self): return "B+" + super().hi()   # extend, not replace
assert B().hi() == "B+A" and isinstance(B(), A) and issubclass(B, A)
assert [c.__name__ for c in B.__mro__] == ["B", "A", "object"]
print("ok")

super() 按 MRO(方法解析顺序,C3 线性化)找"下一个"类,而不是简单地找直接父类,这在多重继承时才有区别。面试中只需要知道:单继承时 super().method() 就是调用父类版本。

Say it in English

In Python, defining __init__ in a subclass replaces the parent's, so I have to call super().__init__() explicitly. For nn.Module it must come first, because the base initializer creates the internal dictionaries for parameters, buffers and submodules. nn.Module overrides __setattr__ so that assigning a layer to self registers it; without those dictionaries, the assignment fails, and the parameters would never show up in model.parameters().

☆

@property、@staticmethod、@classmethod

一句话

@property 让方法像属性一样读取(可加 setter 做校验);@staticmethod 是放在类命名空间里的普通函数(无 self);@classmethod 第一个参数是类 cls,常用作替代构造函数(如 from_pretrained)。

property for computed attributes, staticmethod for plain helpers, classmethod for alternative constructors like from_pretrained.

class Temperature:
    def __init__(self, c):
        self.celsius = c                  # goes through the setter below
    @property
    def celsius(self):
        return self._c
    @celsius.setter
    def celsius(self, v):
        if v < -273.15:
            raise ValueError("below absolute zero")
        self._c = v
    @property
    def fahrenheit(self):                 # computed, read-only
        return self._c * 9 / 5 + 32
    @staticmethod
    def c_to_k(c):                        # no self, no cls
        return c + 273.15
    @classmethod
    def from_fahrenheit(cls, f):          # alternative constructor; works for subclasses
        return cls((f - 32) * 5 / 9)

t = Temperature(100)
assert t.fahrenheit == 212.0              # no parentheses
assert Temperature.c_to_k(0) == 273.15
assert abs(Temperature.from_fahrenheit(212).celsius - 100) < 1e-9
try:
    t.celsius = -300
except ValueError:
    pass
try:
    t.fahrenheit = 0                      # no setter -> read-only
except AttributeError:
    pass
print("ok")

在 HuggingFace 中,AutoModel.from_pretrained(name) 就是 classmethod 替代构造函数;PyTorch 的 tensor.shape、module.training 等读起来像字段,shape 实际是 property。

Say it in English

A property lets me expose a computed or validated value with plain attribute syntax. A static method is just a function namespaced in the class, with no access to the instance. A class method receives the class itself, so it's the idiomatic way to write alternative constructors, like from_pretrained in Hugging Face.

§6 · ITERATORS, GENERATORS, DECORATORS, CONTEXT MANAGERS迭代器、生成器、装饰器、上下文管理器

这四个机制是读懂 ML 代码的钥匙:for batch in dataloader(迭代器协议)、流式读数据(生成器)、@torch.no_grad()(装饰器)、with torch.autocast(...)(上下文管理器)。面试中也常被问"yield 做了什么""写一个计时装饰器"。

☆

迭代器协议:iterable vs iterator

一句话

可迭代对象(iterable)有 __iter__,返回一个迭代器;迭代器有 __next__,每次返回下一个值,耗尽时抛 StopIteration。for x in obj 就是 it = iter(obj) 然后反复 next(it)。

An iterable produces an iterator via __iter__; an iterator yields values via __next__ until it raises StopIteration.

class Countdown:                       # iterable: can be looped over many times
    def __init__(self, n): self.n = n
    def __iter__(self):
        return CountdownIter(self.n)   # fresh iterator each time

class CountdownIter:                   # iterator: single pass, keeps position
    def __init__(self, n): self.cur = n
    def __iter__(self): return self
    def __next__(self):
        if self.cur <= 0:
            raise StopIteration
        self.cur -= 1
        return self.cur + 1

c = Countdown(3)
assert list(c) == [3, 2, 1] and list(c) == [3, 2, 1]   # reusable
it = iter(c)
assert next(it) == 3 and next(it) == 2 and next(it) == 1
assert next(it, "done") == "done"                     # default instead of exception

# what a for loop really does
it, out = iter([10, 20]), []
while True:
    try:
        x = next(it)
    except StopIteration:
        break
    out.append(x)
assert out == [10, 20]

# zip/map/filter/enumerate/reversed return ITERATORS: single pass
z = zip([1, 2], "ab")
assert list(z) == [(1, "a"), (2, "b")] and list(z) == []
print("ok")

联系 PyTorch:DataLoader 是 iterable,每个 epoch for batch in loader 都会调用 iter(loader) 创建新的迭代器(重新打乱、重新启动 worker)。next(iter(loader)) 是取一个 batch 来调试的惯用写法。

Say it in English

An iterable is anything with __iter__, which returns an iterator; an iterator implements __next__ and raises StopIteration when it's exhausted. A for loop just calls iter once and then next repeatedly. Containers are reusable iterables, but objects like zip or a generator are single-pass iterators.

★

生成器与 yield

一句话

含 yield 的函数调用后返回生成器对象,不执行函数体;每次 next() 运行到下一个 yield 交出一个值并暂停(保存局部变量和执行位置),下次从暂停处继续。是写迭代器最简单的方式,惰性、O(1) 内存。

A generator function pauses at each yield, preserving its local state, and resumes on the next next() call.

C 里没有直接对应物;最接近的是"带 static 局部变量和状态机的函数",或者协程。生成器的帧(局部变量 + 指令指针)保存在堆上,所以可以暂停和恢复。

import io

def countdown(n):
    print_log.append("start")          # runs only on the first next()
    while n > 0:
        yield n
        n -= 1
    print_log.append("end")

print_log = []
g = countdown(2)
assert print_log == []                 # calling it ran NOTHING yet
assert next(g) == 2 and print_log == ["start"]
assert next(g) == 1
assert next(g, None) is None and print_log == ["start", "end"]

def read_batches(f, batch_size):       # streaming: never loads the whole file
    batch = []
    for line in f:                     # file objects are line iterators
        batch.append(line.rstrip("\n"))
        if len(batch) == batch_size:
            yield batch
            batch = []
    if batch:
        yield batch

fake_file = io.StringIO("a\nb\nc\nd\ne\n")
assert list(read_batches(fake_file, 2)) == [["a", "b"], ["c", "d"], ["e"]]

def flatten(nested):                   # yield from: delegate to a sub-generator
    for x in nested:
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x
assert list(flatten([1, [2, [3, 4]], 5])) == [1, 2, 3, 4, 5]

def fib():                             # infinite generator
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
from itertools import islice
assert list(islice(fib(), 8)) == [0, 1, 1, 2, 3, 5, 8, 13]

def tokens(text):                      # pipeline of lazy stages
    return (w.lower() for w in text.split())
def no_stop(ws, stop=frozenset({"the", "a"})):
    return (w for w in ws if w not in stop)
assert list(no_stop(tokens("The cat saw a dog"))) == ["cat", "saw", "dog"]
print("ok")
  • 生成器函数里的 return value 会变成 StopIteration.value(yield from 表达式的值),日常很少用。
  • 生成器还能 send() 值进去(协程的前身),面试基本不考;asyncio 的 async/await 在概念上就源自这里。
常见误区(1) 以为调用生成器函数就执行了函数体——其实什么都没执行(包括参数检查),错误会延迟到第一次 next 才出现。(2) 生成器只能遍历一次。(3) 在生成器里用到的外部资源(打开的文件)要用 with 管理,否则可能在生成器没被耗尽时一直不关闭。
Say it in English

Calling a generator function doesn't run its body; it returns a generator object. Each call to next runs until the next yield, hands back a value, and suspends with all local state preserved. That makes generators a concise way to write lazy iterators, for example streaming a large dataset in batches without loading it all into memory.

追问链
  1. How would you implement a simple DataLoader-like batching generator with shuffling?
    思路
    import random
    def batches(data, bs, shuffle=True, seed=0):
        idx = list(range(len(data)))
        if shuffle:
            random.Random(seed).shuffle(idx)
        for i in range(0, len(idx), bs):
            yield [data[j] for j in idx[i:i + bs]]
    
    out = list(batches(list(range(10)), 4))
    assert [len(b) for b in out] == [4, 4, 2]
    assert sorted(x for b in out for x in b) == list(range(10))
    print("ok")
    每个 epoch 重新调用一次(相当于 DataLoader 每个 epoch 重新 iter()),最后一个不满的 batch 可以按需丢弃(drop_last)。
★

装饰器(含带参数装饰器与 functools.wraps)

一句话

装饰器是"接收函数、返回新函数"的高阶函数,@d 写在 def f 上等价于 f = d(f);包装函数要用 @functools.wraps(func) 保留原函数的名字和文档。

A decorator takes a function and returns a replacement; @d above def f means f = d(f), and functools.wraps preserves metadata.

import time, functools

def timed(func):
    @functools.wraps(func)               # copy __name__, __doc__, __wrapped__ ...
    def wrapper(*args, **kwargs):        # accept ANY signature
        t0 = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:                         # report even if func raises
            wrapper.last_seconds = time.perf_counter() - t0
    return wrapper

@timed                                   # same as: slow_sum = timed(slow_sum)
def slow_sum(n):
    """Sum 0..n-1."""
    return sum(range(n))

assert slow_sum(10**5) == 4999950000
assert slow_sum.__name__ == "slow_sum" and slow_sum.__doc__ == "Sum 0..n-1."
assert slow_sum.last_seconds >= 0

def retry(times):                        # decorator WITH arguments: one extra layer
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(times):
                try:
                    return func(*args, **kwargs)
                except ValueError:
                    if attempt == times - 1:
                        raise
        return wrapper
    return deco

calls = {"n": 0}
@retry(times=3)                          # == flaky = retry(3)(flaky)
def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise ValueError("transient")
    return "ok"
assert flaky() == "ok" and calls["n"] == 3

def no_wraps(func):
    def wrapper(*a, **k): return func(*a, **k)
    return wrapper
@no_wraps
def named(): pass
assert named.__name__ == "wrapper"       # metadata lost without functools.wraps

def counted(func):                       # stacking: applied bottom-up
    @functools.wraps(func)
    def wrapper(*a, **k):
        wrapper.calls += 1
        return func(*a, **k)
    wrapper.calls = 0
    return wrapper
@counted
@timed
def f(x): return x
f(1); f(2)
assert f.calls == 2
print("ok")

在 ML 代码里见到的装饰器:@torch.no_grad()(关闭梯度)、@torch.compile、@functools.cache、@dataclass(类装饰器)、@property、@staticmethod、@pytest.mark.parametrize。

常见误区@torch.no_grad 和 @torch.no_grad():标准写法是带括号的(它是一个类,括号创建实例,实例再作为装饰器使用);新版 PyTorch 也接受不带括号的写法,但面试中写带括号的版本最安全。同理,带参数装饰器 @retry(3) 忘写括号会把被装饰函数当成 times 传进去。
Say it in English

A decorator is a higher-order function: it takes a function and returns a new one, and the @ syntax is just sugar for reassigning the name. The wrapper typically accepts *args and **kwargs so it works with any signature, and I use functools.wraps so the wrapped function keeps its name and docstring. A decorator with arguments needs one more level of nesting, a function that returns the actual decorator.

☆

上下文管理器:with、__enter__/__exit__、@contextmanager、torch.no_grad

一句话

with 保证"进入时做准备、退出时一定清理"(即使抛异常),相当于 C 里成对的 fopen/fclose、lock/unlock 加上 goto cleanup;torch.no_grad() 和 torch.autocast() 都是上下文管理器:进入时修改全局(线程局部)状态,退出时恢复。

with guarantees setup and teardown even on exceptions; torch.no_grad and autocast toggle state on entry and restore it on exit.

from contextlib import contextmanager
import time

GRAD_ENABLED = [True]                    # stand-in for torch's grad mode flag

class no_grad:                           # class-based context manager
    def __enter__(self):
        self.prev = GRAD_ENABLED[0]
        GRAD_ENABLED[0] = False
        return self                      # bound to the name after `as`
    def __exit__(self, exc_type, exc, tb):
        GRAD_ENABLED[0] = self.prev      # restore, even if an exception happened
        return False                     # False/None: don't swallow the exception

with no_grad():
    assert GRAD_ENABLED[0] is False
    with no_grad():                      # nesting works because we restore `prev`
        pass
    assert GRAD_ENABLED[0] is False
assert GRAD_ENABLED[0] is True

try:
    with no_grad():
        raise RuntimeError("boom")
except RuntimeError:
    pass
assert GRAD_ENABLED[0] is True           # restored despite the exception

@contextmanager                          # generator-based: code before yield = __enter__
def timer(log, label):
    t0 = time.perf_counter()
    try:
        yield                            # body of the with-block runs here
    finally:                             # = __exit__
        log.append((label, time.perf_counter() - t0))

log = []
with timer(log, "step"):
    sum(range(1000))
assert log[0][0] == "step" and log[0][1] >= 0

import tempfile, os
path = os.path.join(tempfile.mkdtemp(), "x.txt")
with open(path, "w") as f:               # file closed automatically
    f.write("hi")
assert f.closed
with open(path) as f:
    assert f.read() == "hi"
print("ok")

真实的 PyTorch 用法(未在本页执行,需要 torch):

model.eval()                         # switches dropout/BN behavior (NOT related to grads)
with torch.no_grad():                # no graph is recorded -> less memory, faster
    logits = model(x)

with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
    loss = model(x, y)               # matmuls run in bf16 inside the block
loss.backward()                      # backward outside autocast is the recommended pattern

@torch.no_grad()                     # the same object used as a decorator
def evaluate(model, loader): ...

torch.no_grad 能同时当上下文管理器和装饰器,是因为它继承了一个同时实现 __enter__/__exit__ 和 __call__ 的基类(标准库里也有类似的 contextlib.ContextDecorator)。

常见误区model.eval() 和 torch.no_grad() 是两回事:前者切换 Dropout/BatchNorm 的行为(模块的 training 标志),后者关闭 autograd 记录。评估时通常两个都要。
Say it in English

A context manager guarantees that cleanup runs when the with-block exits, even if an exception is raised, so it replaces manual try/finally around resources like files or locks. torch.no_grad() is a context manager that disables gradient tracking on entry and restores the previous mode on exit; it's also usable as a decorator. Note that it's independent of model.eval(), which changes the behavior of dropout and batch norm.

§7 · TYPES & ENGINEERING HABITS类型提示与工程习惯

这些不太会被单独考,但会影响面试官对你"工程成熟度"的印象:函数签名有类型提示、知道 if __name__ == "__main__" 的作用、会读 traceback 快速定位 bug。

○

类型提示(type hints)

一句话

类型提示只是注解,运行时不检查;它服务于读者、IDE 和静态检查器(mypy/pyright)。面试中给函数签名加上类型(def f(nums: list[int], k: int) -> list[int]:)是加分的好习惯。

Type hints are not enforced at runtime; they document intent and enable static checkers.

from typing import Optional, Callable, Iterator

def top_k(nums: list[int], k: int) -> list[int]:        # built-in generics (3.9+)
    return sorted(nums, reverse=True)[:k]

def find(xs: list[str], target: str) -> Optional[int]:  # same as: int | None (3.10+)
    return xs.index(target) if target in xs else None

def apply(f: Callable[[int], int], xs: list[int]) -> list[int]:
    return [f(x) for x in xs]

def gen(n: int) -> Iterator[int]:
    yield from range(n)

Grid = list[list[int]]                                  # type alias
def rows(g: Grid) -> int:
    return len(g)

assert top_k([3, 1, 2], 2) == [3, 2] and find(["a"], "b") is None
assert apply(lambda x: x + 1, [1]) == [2] and list(gen(2)) == [0, 1]
assert top_k("not a list", 1) == ["t"]     # NOT enforced at runtime!
assert top_k.__annotations__["return"] == list[int]
print("ok")
Say it in English

I'll add type hints to the signature to make the interface clear. They aren't enforced at runtime, but they document intent and let tools like mypy catch mistakes before the code runs.

○

__main__、模块 vs 头文件、venv/pip

一句话

每个 .py 文件就是一个模块;import 时执行一次并缓存;直接运行时 __name__ == "__main__",被 import 时等于模块名——所以用这个守卫包住"只在直接运行时执行"的代码。依赖装在虚拟环境里(python -m venv .venv + pip install)。

Every file is a module executed once on import; the __main__ guard separates script behavior from importable definitions.

CPython
foo.h 声明 + foo.c 定义只有 foo.py;没有前向声明(函数在调用时才需要已定义)
#include 文本粘贴import 执行模块,得到模块对象;重复 import 直接从 sys.modules 返回
static 函数(文件私有)约定:下划线开头 _helper 表示内部使用(不强制)
链接器、-I 路径sys.path(当前目录、site-packages…)
Makefile / 系统包pip + requirements.txt / pyproject.toml;每个项目一个 venv(或 conda / uv)
目录组织包(package)= 含 __init__.py 的目录;from pkg.sub import f
# train.py
import argparse

def main(lr: float) -> None:
    print(f"training with lr={lr}")

if __name__ == "__main__":          # skipped when another file does `import train`
    p = argparse.ArgumentParser()
    p.add_argument("--lr", type=float, default=3e-4)
    main(p.parse_args().lr)

常用命令:python -m venv .venv && source .venv/bin/activate;pip install numpy;python -m pip(确保 pip 属于当前解释器);python -m pytest;python -i script.py(运行后进入交互模式检查变量);python -m pdb script.py 或在代码里写 breakpoint() 进入调试器。

常见误区把自己的文件命名为 random.py、torch.py、queue.py:当前目录在 sys.path 最前面,import random 会导入你的文件而不是标准库,出现莫名其妙的 AttributeError。
Say it in English

Each Python file is a module; importing it executes it once and caches the module object. The if __name__ == "__main__" guard lets the same file act as both a script and an importable library. For dependencies I use a virtual environment per project so package versions don't conflict.

☆

读 traceback 与常见异常

一句话

traceback 从下往上读:最后一行是异常类型和信息,倒数第二帧是出错的那一行代码;往上是调用链。认识 10 种常见异常就能秒定位 90% 的 bug。

Read a traceback from the bottom: the last line is the exception, the frame above it is where it happened.

Traceback (most recent call last):
  File "solve.py", line 12, in <module>
    print(two_sum([2, 7], 9))
  File "solve.py", line 6, in two_sum
    return [seen[target - x], i]
            ~~~~^^^^^^^^^^^^
KeyError: 7

读法:异常是 KeyError: 7(dict 里没有 key 7)→ 发生在 two_sum 第 6 行 → 由第 12 行调用。Python 3.11+ 还会用 ~~~^^^ 标出具体是表达式的哪一部分出错。

异常典型原因
IndexError: list index out of range越界(C 里是静默 UB);空 list 上 a[0] / pop()
KeyErrordict 缺 key → get / defaultdict / 先检查 in
TypeError: unhashable type: 'list'list 做了 dict key / set 元素 / @cache 参数
TypeError: '<' not supported between instances堆/排序里比较了不可比较对象 → 加计数器 tie-break
TypeError: 'NoneType' object is not subscriptable用了返回 None 的方法的结果(a = a.sort())或函数忘记 return
AttributeError: 'NoneType' object has no attribute 'val'链表/树走到 None 了还访问 .val/.next
UnboundLocalError内层函数给外层变量赋值没写 nonlocal
RecursionError递归无出口或太深
ValueErrorint("a")、list.index/remove 找不到、解包个数不匹配
RuntimeError: dictionary changed size during iteration遍历 dict 时增删
ZeroDivisionError除以 0(包括 float)
IndentationError缩进不一致 / tab 与空格混用
Say it in English

I read tracebacks from the bottom up: the last line tells me the exception type and message, and the frame just above it shows the exact line that failed. Then I walk up the call chain to see how we got there.

§8 · HOW CPYTHON RUNS运行机制:字节码、内存回收、GIL

RS 面试偶尔会问"为什么 Python 慢""GIL 是什么、对训练有什么影响""为什么显存没释放"。这些问题的答案都来自 CPython 的三个实现事实:解释执行字节码、引用计数、全局解释器锁。理解它们也直接告诉你为什么 ML 代码必须向量化、DataLoader 为什么用多进程。

☆

字节码与"为什么循环慢 → 向量化"

一句话

CPython 把源码编译成字节码,再由一个 C 写的解释器循环逐条执行;每条指令都要做动态类型检查、对象分配和引用计数,所以纯 Python 循环比 C 慢几十到上百倍。办法:把循环下推到 NumPy/PyTorch 的 C/CUDA 内核里(向量化)。

CPython interprets bytecode with per-operation dynamic dispatch and boxing, so the fix for slow loops is to vectorize them into native kernels.

import dis
def add(a, b):
    return a + b
ops = [ins.opname for ins in dis.get_instructions(add)]
assert "BINARY_OP" in ops or "BINARY_ADD" in ops      # name differs across versions
# dis.dis(add) prints something like:
#   RESUME 0
#   LOAD_FAST_LOAD_FAST (a, b)
#   BINARY_OP 0 (+)
#   RETURN_VALUE
print(ops)

一次 a + b 在 C 里是一条机器指令;在 CPython 里大致要:从帧里取出两个 PyObject* → 查它们的类型 → 找到 int 的加法实现 → 处理任意精度 → 在堆上分配一个新的 int 对象(小整数除外)→ 增减引用计数 → 把结果压栈。这就是"解释器开销"。(Python 3.11 起有"自适应特化"——会把热点指令特化成针对 int/float 的快速版本,3.13 还有实验性 JIT,但数量级差距仍在。)

import time
import numpy as np

n = 10**6
xs = list(range(n))
arr = np.arange(n, dtype=np.int64)

t0 = time.perf_counter(); s1 = 0
for x in xs:
    s1 += x * x                         # interpreter loop: ~n bytecode round-trips
t1 = time.perf_counter()
s2 = int((arr * arr).sum())             # one call into a C loop over raw int64s
t2 = time.perf_counter()
assert s1 == s2
print(f"python loop {t1 - t0:.4f}s   numpy {t2 - t1:.4f}s   speedup ~{(t1 - t0) / (t2 - t1):.0f}x")

在本机上这个例子 NumPy 快约一两个数量级(具体倍数取决于机器)。除了避免解释器开销,NumPy 还拿到了连续内存(cache 友好)和 SIMD;GPU 上的 PyTorch 更是把一次调用变成成千上万个并行线程。

直觉把 Python 当成"指挥官":每条 Python 语句都有固定的调度成本(微秒级),所以要让每条语句做尽量多的工作。一条 x @ W 处理一百万个乘加,调度成本可以忽略;一个百万次的 Python for 循环则全是调度成本。这就是 ML 面试中"不要对 batch 维写 Python 循环"的根源。
Say it in English

CPython compiles source to bytecode and runs it in an interpreter loop. Every operation involves dynamic type dispatch, reference counting and often a heap allocation for the result, so a simple addition costs dozens of times more than in C. The remedy is vectorization: express the computation as whole-array operations so the loop runs inside optimized C or CUDA kernels, with contiguous memory and SIMD.

☆

引用计数 + 循环垃圾回收(联系 GPU 显存)

一句话

每个对象有引用计数,归零立即释放(确定性);引用计数处理不了循环引用,所以还有一个分代的循环垃圾回收器定期清理。PyTorch 显存不释放,几乎总是因为还有名字引用着张量(或它的计算图)。

CPython frees objects as soon as their refcount hits zero, with a cyclic GC as backup; leaked GPU memory almost always means something still references the tensor.

import sys, gc, weakref

class Blob:
    pass

b = Blob()
r = weakref.ref(b)                     # weak ref doesn't keep the object alive
alias = b
assert sys.getrefcount(b) >= 3         # b, alias, and the temporary argument
del b                                  # 'del' removes a NAME, not the object
assert r() is not None                 # still alive through `alias`
del alias
assert r() is None                     # refcount hit 0 -> freed immediately

x, y = Blob(), Blob()
x.other, y.other = y, x                # reference cycle
rx = weakref.ref(x)
del x, y
assert rx() is not None                # refcounts never reach 0 on their own
gc.collect()                           # cycle collector finds unreachable cycles
assert rx() is None
print("ok")

和 GPU 显存的联系(PyTorch 行为,概念说明,未在本页执行):

  • losses.append(loss):loss 张量带着整张计算图,图里引用着前向的中间激活 → 每一步的激活都无法释放,显存一路上涨。应写 losses.append(loss.item()) 或 loss.detach()。
  • 变量在循环结束后仍然存在(函数作用域):最后一个 batch 的 out/loss 会一直占着显存,直到被覆盖或 del。
  • del t 只是删除名字;张量真正释放后,PyTorch 的缓存分配器仍会保留这块显存以备复用,所以 nvidia-smi 看到的占用不降;torch.cuda.memory_allocated() 才反映真实占用,torch.cuda.empty_cache() 把缓存还给驱动(一般不需要)。
  • 异常 traceback 会引用出错帧的局部变量(例如 OOM 后在 notebook 里),也会让张量"活着"。
Say it in English

CPython primarily uses reference counting, so an object is freed the moment its last reference disappears, plus a generational cycle collector for reference cycles. In PyTorch, that explains most "memory leaks": if I keep a reference to a loss tensor, for example by appending it to a list, I keep its whole autograd graph and all saved activations alive. Logging loss.item() instead fixes it.

☆

GIL;threading vs multiprocessing vs asyncio;free-threaded Python

一句话

GIL 使同一进程中同一时刻只有一个线程执行 Python 字节码:CPU 密集的纯 Python 代码用多线程无法并行,要用多进程;I/O 密集用线程或 asyncio。NumPy/PyTorch 的重计算在 C/CUDA 里会释放 GIL。3.13 起有可选的 free-threaded(无 GIL)构建,3.14 起官方支持但仍非默认。

The GIL lets only one thread run Python bytecode at a time; use processes for CPU-bound Python, threads or asyncio for I/O, and note that native libraries release the GIL.

为什么有 GIL?引用计数要在每次赋值时修改对象头部的计数器;如果多个线程同时改,没有锁就会出错(计数丢失 → 提前释放或泄漏)。给每个对象加细粒度锁代价太高,于是 CPython 用一把全局锁保护解释器状态,简单且单线程性能好。

方案并行性适用代价
threading受 GIL 限制,Python 代码不能并行;阻塞 I/O 和释放 GIL 的 C 代码期间可以网络请求、文件 I/O、调用释放 GIL 的库线程安全问题(GIL 不保证你的复合操作是原子的)
multiprocessing / concurrent.futures.ProcessPoolExecutor真并行(每个进程有自己的解释器和 GIL)CPU 密集的纯 Python(数据预处理、tokenization)进程启动开销,数据要 pickle 序列化传递,内存翻倍
asyncio单线程协作式并发大量并发 I/O(成千上万个 API 请求、agent 并发调用 LLM)需要 async 生态;一个阻塞调用会卡住整个事件循环

和 ML 的联系:

  • PyTorch 的算子在 C++/CUDA 中执行并释放 GIL,CUDA kernel 还是异步发射的,所以训练主循环基本不受 GIL 影响。
  • DataLoader(num_workers=k) 用多进程做数据加载和增强,正是为了绕开 GIL。
  • 多卡训练(DDP)每张卡一个进程,也避开了 GIL。
  • 调用 LLM API 做评估/数据生成时,用 asyncio 或线程池并发请求。

Free-threaded Python(截至 2026 年的状态):PEP 703 在 3.13 引入了可选的无 GIL 构建(python3.13t,实验性)。PEP 779(2025 年 6 月被接受)让它在 3.14 进入"官方支持但可选"的第二阶段,并为单线程性能开销设定了约 15% 以内的目标;是否成为默认留给未来的 PEP 决定。实际可用性还取决于 C 扩展(NumPy、PyTorch 等)对无 GIL 构建的适配。面试中说清楚"标准 CPython 仍有 GIL,无 GIL 构建已官方支持但需单独安装、尚非默认"就够了。

import threading, sys
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

counter = 0
lock = threading.Lock()
def work(n):
    global counter
    for _ in range(n):
        with lock:                       # += is read-modify-write: NOT atomic even with the GIL
            counter += 1
threads = [threading.Thread(target=work, args=(10000,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
assert counter == 40000

def cpu_task(n):
    return sum(i * i for i in range(n))

if __name__ == "__main__":               # required for process pools on spawn-based platforms
    with ProcessPoolExecutor(max_workers=2) as ex:
        assert list(ex.map(cpu_task, [10**4, 10**4])) == [cpu_task(10**4)] * 2
    with ThreadPoolExecutor(max_workers=4) as ex:   # good for I/O-bound jobs
        assert list(ex.map(len, ["a", "bb"])) == [1, 2]
    gil = getattr(sys, "_is_gil_enabled", lambda: True)()
    print("GIL enabled:", gil)
import asyncio, time

async def fake_api_call(i):
    await asyncio.sleep(0.05)            # stands in for network latency
    return i * i

async def main():
    t0 = time.perf_counter()
    results = await asyncio.gather(*(fake_api_call(i) for i in range(20)))
    return results, time.perf_counter() - t0

results, dt = asyncio.run(main())
assert results == [i * i for i in range(20)]
assert dt < 0.5                          # concurrent: ~0.05s total, not 20 * 0.05s
print(f"{dt:.3f}s")
常见误区(1) 以为"有 GIL 就不需要锁":GIL 只保证单条字节码的原子性,counter += 1 是"读-加-写"多条字节码,线程可能在中间切换。(2) 以为"Python 多线程完全没用":I/O 密集任务用线程能显著提速。(3) 以为 GIL 会拖慢 GPU 训练:重计算不在 Python 里。
Say it in English

The Global Interpreter Lock means only one thread executes Python bytecode at a time in a process. It exists mainly to keep reference counting safe and cheap. So threads don't speed up CPU-bound pure-Python code; for that I'd use multiple processes, which is exactly why PyTorch's DataLoader uses worker processes. Threads and asyncio are still great for I/O-bound work like concurrent API calls. Heavy numerical work in NumPy or PyTorch runs in native code that releases the GIL. Recent CPython versions also offer an optional free-threaded build without the GIL, officially supported since 3.14 but not the default.

追问链
  1. Your tokenization preprocessing over 100 GB of text is slow. How would you parallelize it in Python?
    思路
    CPU 密集 → 多进程:把文件分片,用 multiprocessing.Pool/ProcessPoolExecutor 或 HuggingFace datasets.map(num_proc=k) 每个进程处理一片,结果写到各自的分片文件(避免把大对象 pickle 回主进程)。tokenizer 本身用 Rust 实现的快速 tokenizer(释放 GIL,支持 batch)。更大规模就上分布式(多机 + 对象存储)。
  2. Why does DataLoader with num_workers > 0 sometimes use a lot of RAM?
    思路
    每个 worker 是独立进程,会拿到一份 Dataset 对象(fork 时写时复制;但 Python 的引用计数会修改对象头,触摸即复制,导致大的 Python list/dict 数据集被逐渐复制到每个 worker)。缓解:把数据存成 NumPy 数组 / memory-mapped 文件 / Arrow 格式,而不是大量 Python 对象。

§9 · ALGORITHM TEMPLATES算法模板速查(可直接默写)

每个模板都是"面试时从空白文件 3–5 分钟内写出来"的标准形态,并附上断言测试(全部实际运行通过)。练法:先读懂 → 遮住代码自己默写 → 跑测试 → 两天后再默写一次。按题型的完整题单在 15 算法题。

★

BFS:网格与图(无权最短路)

一句话

deque + visited,入队时标记访问;按层处理时用 for _ in range(len(q));无权图中 BFS 首次到达即最短距离。O(V + E)。

BFS with a deque, marking nodes visited when enqueued, gives shortest paths in unweighted graphs in O(V + E).

from collections import deque

DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))

def bfs_grid(grid, start, target):
    """Shortest number of steps from start to target through '.' cells, or -1."""
    R, C = len(grid), len(grid[0])
    q = deque([start])
    dist = {start: 0}                        # doubles as the visited set
    while q:
        r, c = q.popleft()
        if (r, c) == target:
            return dist[(r, c)]
        for dr, dc in DIRS:
            nr, nc = r + dr, c + dc
            if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == "." and (nr, nc) not in dist:
                dist[(nr, nc)] = dist[(r, c)] + 1   # mark when ENQUEUING
                q.append((nr, nc))
    return -1

def bfs_levels(adj, src):
    """Level-order BFS on an adjacency list; returns nodes grouped by distance."""
    seen, q, levels = {src}, deque([src]), []
    while q:
        level = []
        for _ in range(len(q)):              # exactly the nodes of the current level
            u = q.popleft()
            level.append(u)
            for v in adj[u]:
                if v not in seen:
                    seen.add(v)
                    q.append(v)
        levels.append(level)
    return levels

def multi_source_bfs(grid):
    """Distance from every cell to the nearest 0 (e.g. '01 Matrix', 'Rotting Oranges')."""
    R, C = len(grid), len(grid[0])
    dist = [[-1] * C for _ in range(R)]
    q = deque()
    for r in range(R):
        for c in range(C):
            if grid[r][c] == 0:
                dist[r][c] = 0
                q.append((r, c))             # all sources start in the queue
    while q:
        r, c = q.popleft()
        for dr, dc in DIRS:
            nr, nc = r + dr, c + dc
            if 0 <= nr < R and 0 <= nc < C and dist[nr][nc] == -1:
                dist[nr][nc] = dist[r][c] + 1
                q.append((nr, nc))
    return dist

g = ["..#",
     ".##",
     "..."]
assert bfs_grid(g, (0, 0), (2, 2)) == 4
assert bfs_grid(g, (0, 0), (0, 0)) == 0
assert bfs_grid([".#", "#."], (0, 0), (1, 1)) == -1
adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
assert bfs_levels(adj, 0) == [[0], [1, 2], [3]]
assert multi_source_bfs([[0, 1, 1], [1, 1, 1]]) == [[0, 1, 2], [1, 2, 3]]
print("ok")
常见误区(1) 出队时才标记 visited:同一个节点会被多次入队,最坏变成指数级/O(E) 重复。(2) 用 list.pop(0)。(3) 网格边界检查写错顺序:grid[nr][nc] 必须在 0 <= nr < R 之后(Python 的负下标不会报错,会悄悄访问最后一行!)。
Say it in English

Since the graph is unweighted, BFS gives shortest paths. I'll use a deque as the queue and mark cells visited as soon as I enqueue them, so each cell is processed once. That's O(rows times columns) time and space.

★

DFS:递归与显式栈(岛屿、连通分量、环检测)

一句话

递归 DFS 最短最清楚,但深度受递归限制;显式栈的迭代版没有深度问题。有向图判环用三色标记(白/灰/黑):遇到灰色节点 = 有环。

Recursive DFS is concise; an explicit stack avoids recursion limits; three-color marking detects cycles in directed graphs.

import sys
sys.setrecursionlimit(10000)

def num_islands(grid):
    grid = [list(row) for row in grid]            # don't mutate the caller's input
    R, C = len(grid), len(grid[0]) if grid else 0
    def dfs(r, c):
        if not (0 <= r < R and 0 <= c < C) or grid[r][c] != "1":
            return
        grid[r][c] = "0"                          # mark visited by sinking the land
        dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1)
    count = 0
    for r in range(R):
        for c in range(C):
            if grid[r][c] == "1":
                dfs(r, c)
                count += 1
    return count

def num_islands_iter(grid):
    R, C = len(grid), len(grid[0]) if grid else 0
    seen, count = set(), 0
    for sr in range(R):
        for sc in range(C):
            if grid[sr][sc] == "1" and (sr, sc) not in seen:
                count += 1
                stack = [(sr, sc)]
                seen.add((sr, sc))
                while stack:
                    r, c = stack.pop()
                    for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                        if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == "1" and (nr, nc) not in seen:
                            seen.add((nr, nc))
                            stack.append((nr, nc))
    return count

def has_cycle_directed(n, edges):
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GRAY, BLACK = 0, 1, 2
    color = [WHITE] * n
    def dfs(u):
        color[u] = GRAY                           # on the current recursion path
        for v in adj[u]:
            if color[v] == GRAY:                  # back edge -> cycle
                return True
            if color[v] == WHITE and dfs(v):
                return True
        color[u] = BLACK                          # fully explored
        return False
    return any(color[u] == WHITE and dfs(u) for u in range(n))

def preorder_iter(root):                          # tree DFS with a stack; node = (val, left, right)
    out, stack = [], [root] if root else []
    while stack:
        val, left, right = stack.pop()
        out.append(val)
        if right: stack.append(right)             # push right first so left is processed first
        if left: stack.append(left)
    return out

g = ["11000",
     "11000",
     "00100",
     "00011"]
assert num_islands(g) == 3 == num_islands_iter(g)
assert num_islands(["0"]) == 0 and num_islands_iter([]) == 0
assert has_cycle_directed(3, [(0, 1), (1, 2), (2, 0)])
assert not has_cycle_directed(3, [(0, 1), (0, 2), (1, 2)])
t = (1, (2, (4, None, None), None), (3, None, None))
assert preorder_iter(t) == [1, 2, 4, 3]
big = ["1" * 3000]                                # deep path: iterative version is safe
assert num_islands_iter(big) == 1
print("ok")
常见误区无向图判环不能用"遇到已访问节点就是环"(父节点会被误判),要记录 parent 或用并查集。修改输入网格标记访问很方便,但要先问面试官是否允许修改输入。
Say it in English

I'll run a DFS from every unvisited land cell and sink the cells as I visit them; each DFS call discovers exactly one island. The recursion depth could reach rows times columns in the worst case, so for very large grids I'd switch to an explicit stack.

★

拓扑排序(Kahn 算法)

一句话

统计入度,把入度为 0 的节点入队;每弹出一个节点就把它的出边"删掉"(邻居入度减 1,变 0 则入队)。输出节点数 < n 说明有环。O(V + E)。

Kahn's algorithm repeatedly removes zero in-degree nodes; if not all nodes get removed, the graph has a cycle.

from collections import deque

def topo_sort(n, edges):
    """edges: (u, v) means u must come before v. Returns an order, or [] if a cycle exists."""
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:
        adj[u].append(v)
        indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []

def can_finish(num_courses, prerequisites):      # LeetCode 207: pair [a, b] means b -> a
    return len(topo_sort(num_courses, [(b, a) for a, b in prerequisites])) == num_courses

order = topo_sort(4, [(0, 1), (0, 2), (1, 3), (2, 3)])
pos = {v: i for i, v in enumerate(order)}
assert all(pos[u] < pos[v] for u, v in [(0, 1), (0, 2), (1, 3), (2, 3)])
assert topo_sort(2, [(0, 1), (1, 0)]) == []
assert can_finish(2, [[1, 0]]) and not can_finish(2, [[1, 0], [0, 1]])
assert topo_sort(3, []) == [0, 1, 2]
print("ok")
Say it in English

I'll use Kahn's algorithm: compute in-degrees, start a queue with all nodes of in-degree zero, and each time I pop a node, decrement its neighbors' in-degrees. If I output fewer than n nodes, there's a cycle. It's linear in nodes plus edges.

★

Dijkstra(堆 + 惰性删除)

一句话

非负权图单源最短路:最小堆存 (dist, node),弹出后若 d > dist[u] 就跳过(过期条目),否则松弛邻居。O((V + E) log V)。

Dijkstra with a min-heap and lazy deletion runs in O((V + E) log V) for non-negative weights.

import heapq, math

def dijkstra(n, edges, src):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    dist = [math.inf] * n
    dist[src] = 0
    pq = [(0, src)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]:                    # stale entry: a shorter path was already found
            continue
        for v, w in adj[u]:
            nd = d + w
            if nd < dist[v]:
                dist[v] = nd
                heapq.heappush(pq, (nd, v))   # no decrease-key: just push a new entry
    return dist

def network_delay(times, n, k):           # LeetCode 743 (nodes 1..n)
    dist = dijkstra(n + 1, times, k)[1:]
    ans = max(dist)
    return -1 if ans == math.inf else ans

edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
assert dijkstra(4, edges, 0) == [0, 3, 1, 4]
assert network_delay([[2, 1, 1], [2, 3, 1], [3, 4, 1]], 4, 2) == 2
assert network_delay([[1, 2, 1]], 2, 2) == -1
print("ok")
常见误区(1) 负权边下 Dijkstra 不正确(用 Bellman-Ford)。(2) 忘记 stale 检查不会出错但会变慢。(3) "最多 K 站"这类带约束的最短路(Cheapest Flights Within K Stops)不能直接用标准 Dijkstra 的 dist 剪枝,要把 (节点, 已用站数) 作为状态,或用 K+1 轮 Bellman-Ford。
Say it in English

With non-negative weights I'd use Dijkstra with a binary heap. Python's heapq has no decrease-key, so I push a new entry whenever I find a shorter distance and skip stale entries when I pop them. The complexity is O((V + E) log V).

★

并查集(Union-Find / DSU)

一句话

parent 数组 + 路径压缩 + 按大小(或秩)合并,单次操作均摊近似 O(1)(准确说 O(α(n)),α 是反阿克曼函数)。用于动态连通性、合并账户、Kruskal、判无向图环。

Union-Find with path compression and union by size gives near-constant amortized operations.

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.components = n

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:          # path compression (iterative: no recursion limit)
            self.parent[x], x = root, self.parent[x]
        return root

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                       # already connected -> this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra                   # attach smaller tree under larger
        self.size[ra] += self.size[rb]
        self.components -= 1
        return True

def redundant_connection(edges):               # LeetCode 684 (nodes 1..n)
    dsu = DSU(len(edges) + 1)
    for u, v in edges:
        if not dsu.union(u, v):
            return [u, v]

d = DSU(5)
d.union(0, 1); d.union(3, 4)
assert d.find(0) == d.find(1) and d.find(0) != d.find(3) and d.components == 3
d.union(1, 4)
assert d.find(0) == d.find(3) and d.components == 2
assert redundant_connection([[1, 2], [1, 3], [2, 3]]) == [2, 3]
chain = DSU(10**5)
for i in range(10**5 - 1):
    chain.union(i, i + 1)
assert chain.components == 1 and chain.find(0) == chain.find(10**5 - 1)
print("ok")
Say it in English

I'll maintain a union-find structure with path compression and union by size, which makes each operation effectively constant amortized time, inverse Ackermann to be precise. An edge whose endpoints already share a root is exactly the edge that creates a cycle.

★

二分:lower_bound 与"在答案上二分"

一句话

统一用左闭右开 [lo, hi) 找"第一个让 pred 为真的位置",要求 pred 单调(F…FT…T);循环 while lo < hi,真则 hi = mid,假则 lo = mid + 1。答案二分:对"答案 x 可行吗"这个单调谓词二分。

Binary search for the first index where a monotone predicate becomes true, using a half-open interval; the same template searches over the answer space.

from bisect import bisect_left, bisect_right
import random

def first_true(lo, hi, pred):
    """Smallest x in [lo, hi) with pred(x) True, assuming pred is F...F T...T; returns hi if none."""
    while lo < hi:
        mid = (lo + hi) // 2              # lo <= mid < hi, so the range always shrinks
        if pred(mid):
            hi = mid                      # mid might be the answer: keep it
        else:
            lo = mid + 1                  # mid is definitely not the answer
    return lo

def lower_bound(a, x):                    # == bisect_left
    return first_true(0, len(a), lambda i: a[i] >= x)

def upper_bound(a, x):                    # == bisect_right
    return first_true(0, len(a), lambda i: a[i] > x)

def search(a, x):                         # classic "find index or -1"
    i = lower_bound(a, x)
    return i if i < len(a) and a[i] == x else -1

def min_eating_speed(piles, h):           # Koko Eating Bananas: binary search on the ANSWER
    def can(k):                           # monotone: if speed k works, any k' > k works
        return sum((p + k - 1) // k for p in piles) <= h
    return first_true(1, max(piles) + 1, can)

def isqrt(n):                             # largest r with r*r <= n  ==  first r with r*r > n, minus 1
    return first_true(0, n + 2, lambda r: r * r > n) - 1

rng = random.Random(0)
for _ in range(500):
    a = sorted(rng.randint(0, 10) for _ in range(rng.randint(0, 8)))
    x = rng.randint(-1, 11)
    assert lower_bound(a, x) == bisect_left(a, x)
    assert upper_bound(a, x) == bisect_right(a, x)
assert search([1, 3, 5], 3) == 1 and search([1, 3, 5], 4) == -1 and search([], 1) == -1
assert min_eating_speed([3, 6, 7, 11], 8) == 4
assert min_eating_speed([30, 11, 23, 4, 20], 5) == 30
assert [isqrt(n) for n in [0, 1, 3, 4, 15, 16, 17]] == [0, 1, 1, 2, 3, 4, 4]
print("ok")
直觉二分的所有变体都可以归结为"找单调谓词的分界点"。只记一个模板 first_true,其余(最后一个 ≤ x、最大可行值)都通过改写谓词或"结果 − 1"得到,就不会再纠结 <= 还是 <、mid+1 还是 mid-1。不变式:答案始终在 [lo, hi] 中;lo 左边全是 F,hi 及右边全是 T。
常见误区(1) hi = mid 与 while lo <= hi 混用 → 死循环。(2) 答案二分的上界设小了(应确保 pred(hi-1) 或 hi 本身覆盖可行解)。(3) 浮点二分要用固定迭代次数(如 100 次)而不是 lo < hi。
Say it in English

I like to frame every binary search as finding the first position where a monotone predicate becomes true. I keep a half-open interval: if the predicate holds at mid, the answer is at mid or to its left, so hi becomes mid; otherwise lo becomes mid plus one. Searching on the answer uses the same template, with the predicate being "is this candidate value feasible?".

★

滑动窗口(可变长度)

一句话

右指针每步扩张一次,窗口"不合法"时用 while 收缩左指针,每个元素最多进出窗口各一次,O(n)。适用于"最长/最短的满足某条件的连续子数组/子串",前提是条件对窗口单调。

Expand the right pointer every step and shrink the left pointer while the window is invalid; each element enters and leaves once, so it's O(n).

from collections import Counter, defaultdict

def longest_unique_substring(s):                  # LeetCode 3
    last = {}                                     # char -> last index seen
    best = lo = 0
    for hi, ch in enumerate(s):
        if ch in last and last[ch] >= lo:
            lo = last[ch] + 1                     # jump left past the duplicate
        last[ch] = hi
        best = max(best, hi - lo + 1)
    return best

def min_window(s, t):                             # LeetCode 76: shortest window covering t
    need = Counter(t)
    missing = len(t)                              # how many chars of t are still missing
    lo = 0
    best = (float("inf"), 0, 0)
    for hi, ch in enumerate(s):
        if need[ch] > 0:
            missing -= 1
        need[ch] -= 1                             # negative = surplus in window
        while missing == 0:                       # window valid: try to shrink
            if hi - lo + 1 < best[0]:
                best = (hi - lo + 1, lo, hi + 1)
            need[s[lo]] += 1
            if need[s[lo]] > 0:
                missing += 1
            lo += 1
    return s[best[1]:best[2]] if best[0] != float("inf") else ""

def longest_at_most_k_distinct(s, k):             # generic shrink-while-invalid template
    cnt = defaultdict(int)
    lo = best = 0
    for hi, ch in enumerate(s):
        cnt[ch] += 1
        while len(cnt) > k:                       # invalid -> shrink
            cnt[s[lo]] -= 1
            if cnt[s[lo]] == 0:
                del cnt[s[lo]]
            lo += 1
        best = max(best, hi - lo + 1)
    return best

assert longest_unique_substring("abcabcbb") == 3
assert longest_unique_substring("bbbbb") == 1 and longest_unique_substring("") == 0
assert longest_unique_substring("abba") == 2
assert min_window("ADOBECODEBANC", "ABC") == "BANC"
assert min_window("a", "aa") == "" and min_window("aa", "aa") == "aa"
assert longest_at_most_k_distinct("eceba", 2) == 3
print("ok")
常见误区数组里有负数时"和 ≥ K 的最短子数组"不能用滑动窗口(扩张不再单调增加和),要用前缀和 + 单调队列。
Say it in English

This is a sliding-window problem: I extend the right end one step at a time, and whenever the window violates the constraint, I advance the left end until it's valid again. Each index is added and removed at most once, so the total time is linear.

★

单调栈与单调队列

一句话

"下一个更大/更小元素"类问题:栈里存下标,保持对应值单调;新元素破坏单调性时弹栈,被弹出的元素的答案就是当前元素。每个下标进出栈一次,O(n)。单调队列(deque)求滑动窗口最值。

A monotonic stack of indices answers next-greater-element queries in O(n); a monotonic deque gives sliding-window maxima.

from collections import deque

def daily_temperatures(T):                       # LeetCode 739: days until a warmer day
    ans = [0] * len(T)
    stack = []                                   # indices with DECREASING temperatures
    for i, t in enumerate(T):
        while stack and T[stack[-1]] < t:
            j = stack.pop()
            ans[j] = i - j                       # i is j's next greater element
        stack.append(i)
    return ans

def largest_rectangle(heights):                  # LeetCode 84
    stack, best = [], 0                          # indices with INCREASING heights
    for i, h in enumerate(heights + [0]):        # sentinel 0 flushes the stack
        while stack and heights[stack[-1]] >= h:
            height = heights[stack.pop()]
            left = stack[-1] + 1 if stack else 0 # first index where bar >= height
            best = max(best, height * (i - left))
        stack.append(i)
    return best

def max_sliding_window(nums, k):                 # LeetCode 239
    dq, out = deque(), []                        # indices; values DECREASING front->back
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()                             # smaller elements can never be a max again
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()                         # front fell out of the window
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

assert daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
assert largest_rectangle([2, 1, 5, 6, 2, 3]) == 10
assert largest_rectangle([2, 4]) == 4 and largest_rectangle([]) == 0
assert max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
assert max_sliding_window([4], 1) == [4]
print("ok")
Say it in English

I'll keep a stack of indices whose values are decreasing. When a new value is larger than the top, the top has just found its next greater element, so I pop it and record the answer. Each index is pushed and popped at most once, giving O(n) overall.

★

前缀和(一维、二维、哈希计数)

一句话

P[i] = a[0] + … + a[i-1](长度 n+1,P[0] = 0),区间和 sum(a[l:r]) = P[r] − P[l];"和为 k 的子数组个数"= 遍历时查 count[P − k]。

Prefix sums turn range sums into O(1) differences; combined with a hash map they count subarrays with a given sum.

from itertools import accumulate
from collections import defaultdict

def prefix(a):
    return list(accumulate(a, initial=0))       # P[0] = 0, len n + 1

def subarray_sum_k(nums, k):                    # LeetCode 560 (works with negatives)
    count = defaultdict(int)
    count[0] = 1                                # empty prefix
    s = ans = 0
    for x in nums:
        s += x
        ans += count[s - k]                     # earlier prefixes P with s - P == k
        count[s] += 1
    return ans

class Matrix2D:                                 # LeetCode 304
    def __init__(self, M):
        R, C = len(M), len(M[0])
        self.P = [[0] * (C + 1) for _ in range(R + 1)]
        for r in range(R):
            for c in range(C):
                self.P[r + 1][c + 1] = M[r][c] + self.P[r][c + 1] + self.P[r + 1][c] - self.P[r][c]
    def sum_region(self, r1, c1, r2, c2):       # inclusive corners
        P = self.P
        return P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1]

a = [3, -1, 4, 1, 5]
P = prefix(a)
assert all(P[r] - P[l] == sum(a[l:r]) for l in range(6) for r in range(l, 6))
assert subarray_sum_k([1, 1, 1], 2) == 2 and subarray_sum_k([1, -1, 0], 0) == 3
m = Matrix2D([[3, 0, 1], [5, 6, 3], [1, 2, 0]])
assert m.sum_region(1, 1, 2, 2) == 11 and m.sum_region(0, 0, 2, 2) == 21
print("ok")
Say it in English

A subarray sum equals the difference of two prefix sums. So as I scan, I keep a hash map from prefix-sum value to how many times it has occurred; for the current prefix s, the number of subarrays ending here with sum k is the count of s minus k. That's O(n) time, and it works with negative numbers, unlike a sliding window.

★

回溯(子集、排列、组合、剪枝)

一句话

"选择 → 递归 → 撤销";到达叶子时拷贝 path[:] 加入结果;用 start 下标避免重复组合、用 used 数组生成排列、排序后跳过相同元素去重。

Backtracking: choose, recurse, un-choose; snapshot the path at the leaves, and sort plus skip equal neighbors to avoid duplicates.

from itertools import permutations as it_perm

def subsets(nums):
    res, path = [], []
    def bt(start):
        res.append(path[:])                       # every node is a subset
        for i in range(start, len(nums)):
            path.append(nums[i])
            bt(i + 1)
            path.pop()
    bt(0)
    return res

def permutations(nums):
    res, path, used = [], [], [False] * len(nums)
    def bt():
        if len(path) == len(nums):
            res.append(path[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue
            used[i] = True; path.append(nums[i])
            bt()
            path.pop(); used[i] = False
    bt()
    return res

def combination_sum(cands, target):               # reuse allowed (LeetCode 39)
    cands = sorted(cands)
    res, path = [], []
    def bt(start, remain):
        if remain == 0:
            res.append(path[:])
            return
        for i in range(start, len(cands)):
            if cands[i] > remain:
                break                             # pruning thanks to sorting
            path.append(cands[i])
            bt(i, remain - cands[i])              # i, not i + 1: reuse allowed
            path.pop()
    bt(0, target)
    return res

def subsets_with_dup(nums):                       # LeetCode 90
    nums = sorted(nums)
    res, path = [], []
    def bt(start):
        res.append(path[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue                          # skip duplicate choices at the same depth
            path.append(nums[i]); bt(i + 1); path.pop()
    bt(0)
    return res

def solve_n_queens(n):
    cols, d1, d2, res, board = set(), set(), set(), [], []
    def bt(r):
        if r == n:
            res.append(["." * c + "Q" + "." * (n - c - 1) for c in board])
            return
        for c in range(n):
            if c in cols or r - c in d1 or r + c in d2:
                continue
            cols.add(c); d1.add(r - c); d2.add(r + c); board.append(c)
            bt(r + 1)
            cols.remove(c); d1.remove(r - c); d2.remove(r + c); board.pop()
    bt(0)
    return res

assert sorted(subsets([1, 2, 3])) == sorted([[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]])
assert sorted(map(tuple, permutations([1, 2, 3]))) == sorted(it_perm([1, 2, 3]))
assert combination_sum([2, 3, 6, 7], 7) == [[2, 2, 3], [7]]
assert sorted(subsets_with_dup([1, 2, 2])) == [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
assert len(solve_n_queens(4)) == 2 and len(solve_n_queens(8)) == 92
print("ok")
常见误区res.append(path) 不拷贝(§1 的经典后果);去重时 i > start 写成 i > 0 会错误地剪掉 [2, 2] 这样的合法组合。
Say it in English

I'll use backtracking: at each step I make a choice, recurse, and then undo the choice. When I reach a complete solution I append a copy of the current path, because the path list keeps being mutated. To avoid duplicate combinations I sort first and skip an element if it equals the previous one at the same recursion depth.

★

动态规划:记忆化递归 vs 自底向上表格

一句话

先写出"状态 + 转移 + 边界";记忆化(@cache)最接近数学定义、只算到达的状态,但有递归深度限制;表格 DP 无递归、可做滚动数组省空间。两者复杂度都是 O(状态数 × 每个状态的转移数)。

Define state, transition and base cases; top-down memoization mirrors the recurrence, bottom-up tables avoid recursion and allow space optimization.

from functools import cache
from bisect import bisect_left
import math

# Coin Change (LeetCode 322): fewest coins summing to amount
def coin_change_memo(coins, amount):
    @cache
    def f(a):                                   # state: remaining amount
        if a == 0: return 0
        if a < 0: return math.inf
        return 1 + min(f(a - c) for c in coins)
    ans = f(amount)
    return -1 if ans == math.inf else ans

def coin_change_table(coins, amount):
    dp = [0] + [math.inf] * amount              # dp[a] = fewest coins for amount a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return -1 if dp[amount] == math.inf else dp[amount]

# LCS (2D table) with a rolling 1D array
def lcs(a, b):
    prev = [0] * (len(b) + 1)
    for i in range(1, len(a) + 1):
        cur = [0] * (len(b) + 1)
        for j in range(1, len(b) + 1):
            cur[j] = prev[j - 1] + 1 if a[i - 1] == b[j - 1] else max(prev[j], cur[j - 1])
        prev = cur
    return prev[-1]

# 0/1 knapsack style: Partition Equal Subset Sum (LeetCode 416)
def can_partition(nums):
    total = sum(nums)
    if total % 2: return False
    target = total // 2
    dp = [True] + [False] * target              # dp[s] = some subset sums to s
    for x in nums:
        for s in range(target, x - 1, -1):      # iterate DOWNWARD so each item is used once
            dp[s] = dp[s] or dp[s - x]
    return dp[target]

# LIS in O(n log n): tails[k] = smallest tail of an increasing subsequence of length k+1
def lis(nums):
    tails = []
    for x in nums:
        i = bisect_left(tails, x)
        if i == len(tails): tails.append(x)
        else: tails[i] = x
    return len(tails)

# House Robber with O(1) space
def rob(nums):
    take, skip = 0, 0
    for x in nums:
        take, skip = skip + x, max(take, skip)
    return max(take, skip)

for coins, amt, exp in [([1, 2, 5], 11, 3), ([2], 3, -1), ([1], 0, 0), ([186, 419, 83, 408], 6249, 20)]:
    assert coin_change_table(coins, amt) == exp
assert coin_change_memo((1, 2, 5), 11) == 3
assert lcs("abcde", "ace") == 3 and lcs("abc", "def") == 0
assert can_partition([1, 5, 11, 5]) and not can_partition([1, 2, 3, 5])
assert lis([10, 9, 2, 5, 3, 7, 101, 18]) == 4 and lis([]) == 0 and lis([7, 7, 7]) == 1
assert rob([2, 7, 9, 3, 1]) == 12
print("ok")
记忆化递归 (top-down)表格 (bottom-up)
写法直接翻译递推式,加 @cache需要确定计算顺序(依赖先算)
计算的状态只算可达状态算全部状态
风险递归深度(~1000)、函数调用开销下标边界
空间优化难滚动数组(如 LCS 只保留上一行、背包倒序遍历)
Say it in English

Let me define the state first: dp of a is the fewest coins that make amount a. The transition is one plus the minimum over coins of dp of a minus that coin, with dp of zero equal to zero. I can implement it top-down with memoization, which mirrors the recurrence, or bottom-up with a table, which avoids recursion depth limits. Either way it's O(amount times number of coins).

☆

Trie(前缀树)

一句话

每个节点是 {字符: 子节点} 的 dict 加一个"是否单词结尾"标记;插入/查找 O(单词长度)。

A trie stores strings character by character in nested nodes, giving O(length) insert and lookup.

class TrieNode:
    __slots__ = ("children", "end")             # saves memory per node
    def __init__(self):
        self.children = {}                      # per-instance dict (NOT a class attribute!)
        self.end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()
    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.end = True
    def _walk(self, s):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node
    def search(self, word):
        node = self._walk(word)
        return node is not None and node.end
    def starts_with(self, prefix):
        return self._walk(prefix) is not None

t = Trie()
for w in ["apple", "app", "bat"]:
    t.insert(w)
assert t.search("app") and t.search("apple") and not t.search("ap")
assert t.starts_with("ap") and not t.starts_with("c")

# minimalist variant: nested dicts with a sentinel key
root = {}
for w in ["to", "tea"]:
    node = root
    for ch in w:
        node = node.setdefault(ch, {})
    node["$"] = True
assert "$" in root["t"]["o"] and "$" not in root["t"]["e"]
print("ok")
Say it in English

I'll build a trie where each node maps characters to child nodes and has a flag marking the end of a word. Insert and search are both linear in the length of the word, independent of how many words are stored.

☆

快速读入(OJ / HackerRank 风格)

一句话

输入量大时不要逐行 input():一次性 sys.stdin.buffer.read().split() 再用迭代器取数;输出用 '\n'.join(...) 一次写出。

For large input, read everything at once with sys.stdin.buffer.read().split() and write output in one join.

import io, sys

def solve(data_bytes):
    data = data_bytes.split()                  # all whitespace-separated tokens (bytes)
    it = iter(data)
    t = int(next(it))                          # number of test cases
    out = []
    for _ in range(t):
        n = int(next(it))
        arr = [int(next(it)) for _ in range(n)]
        out.append(str(sum(arr)))
    return "\n".join(out)

def main():
    sys.stdout.write(solve(sys.stdin.buffer.read()) + "\n")

# simulate stdin for testing
fake = io.BytesIO(b"2\n3\n1 2 3\n2\n10 -4\n")
assert solve(fake.read()) == "6\n6"

# line-oriented alternative
lines = io.StringIO("3\n4 5 6\n")
readline = lines.readline                      # sys.stdin.readline in real code
n = int(readline())
arr = list(map(int, readline().split()))
assert n == 3 and arr == [4, 5, 6]
print("ok")
Say it in English

Since the input can be large, I'll read all of standard input at once and split it into tokens, then pull values from an iterator. I'll also collect the outputs and write them in a single call, which avoids per-line I/O overhead.

§10 · EXERCISES练习(C→Python 翻译 + 高频题)

规则:关掉补全,计时,先用英文说出思路和复杂度,再写代码,写完自己补 2–3 个断言。参考答案全部运行通过。难度:★ 热身(5–10 分钟)、★★ 面试标准(15–20 分钟)、★★★ 偏难(25+ 分钟)。

练习 10.1 · 难度 ★ · C→Python 翻译

把下面的 C 函数翻译成地道的 Python(不要逐行照搬下标循环):

int count_positive_even(const int *a, int n) {
    int cnt = 0;
    for (int i = 0; i < n; i++)
        if (a[i] > 0 && a[i] % 2 == 0) cnt++;
    return cnt;
}
提示
True 等于 1;生成器表达式传给 sum。
参考答案
def count_positive_even(a):
    return sum(1 for x in a if x > 0 and x % 2 == 0)
    # or: sum(x > 0 and x % 2 == 0 for x in a)

assert count_positive_even([1, 2, -4, 6, 0]) == 2
assert count_positive_even([]) == 0
print("ok")

O(n) 时间,O(1) 额外空间。注意 Python 里负偶数 -4 % 2 == 0 同样成立(C 里也是 0),但负奇数 -3 % 2 在 Python 是 1、C 是 −1——所以判断奇数写 x % 2 != 0 或 x % 2 == 1 在 Python 都对,但在 C 里只有前者对。

练习 10.2 · 难度 ★ · C→Python 翻译(二维数组与结构体)

C 代码用 int mat[R][C] 存矩阵,用 struct {int r, c, v;} 返回最大元素的位置和值。用 Python 写 argmax2d(mat) 返回 (r, c, v);再写 transpose(mat) 和 make_zero(R, C)(注意 §1 陷阱)。

提示
max 带 key;转置用 zip(*mat);零矩阵用推导式。
参考答案
def argmax2d(mat):
    return max(((r, c, v) for r, row in enumerate(mat) for c, v in enumerate(row)),
               key=lambda t: t[2])

def transpose(mat):
    return [list(col) for col in zip(*mat)]

def make_zero(R, C):
    return [[0] * C for _ in range(R)]       # NOT [[0] * C] * R

m = [[1, 9, 3], [4, 5, 6]]
assert argmax2d(m) == (0, 1, 9)
assert transpose(m) == [[1, 4], [9, 5], [3, 6]]
z = make_zero(2, 3); z[0][0] = 1
assert z == [[1, 0, 0], [0, 0, 0]]
print("ok")

O(R·C)。max 在有多个最大值时返回第一个遇到的,和 C 里用 > 更新的行为一致。

练习 10.3 · 难度 ★ · C→Python 翻译(字符串处理)

C 程序员会用 char buf[] 原地反转单词。用 Python 写 reverse_words(s):把句子中的单词顺序反转,多个空格压缩成一个,去掉首尾空格(LeetCode 151)。再写 caesar(s, k):小写字母循环右移 k 位,其他字符不变(处理负数 k)。

提示
split() 无参数会处理任意空白;(ord(c) - ord('a') + k) % 26 在 Python 中对负数也正确。
参考答案
def reverse_words(s):
    return " ".join(reversed(s.split()))

def caesar(s, k):
    out = []
    for ch in s:
        if "a" <= ch <= "z":
            out.append(chr((ord(ch) - ord("a") + k) % 26 + ord("a")))
        else:
            out.append(ch)
    return "".join(out)

assert reverse_words("  the sky   is blue ") == "blue is sky the"
assert reverse_words("") == ""
assert caesar("xyz, abc", 3) == "abc, def"
assert caesar("abc", -1) == "zab"          # Python % keeps it in [0, 26)
assert caesar(caesar("hello", 7), -7) == "hello"
print("ok")

两者都是 O(n)。在 C 里 (c - 'a' + k) % 26 遇到负 k 会得到负数,需要 ((x % 26) + 26) % 26;Python 的取模直接满足需要。

练习 10.4 · 难度 ★ · Two Sum

给定整数数组和目标值,返回和为目标值的两个元素的下标(保证恰好一个解,同一元素不能用两次)。先说暴力解,再给 O(n) 解。

提示
一边扫描一边用 dict 记录"值 → 下标";对每个 x 查 target − x 是否出现过。先查再存,避免把自己用两次。
参考答案
def two_sum(nums, target):
    seen = {}                                   # value -> index
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i                             # store AFTER checking
    return []

assert two_sum([2, 7, 11, 15], 9) == [0, 1]
assert two_sum([3, 3], 6) == [0, 1]
assert two_sum([3, 2, 4], 6) == [1, 2]          # must not reuse index 0
print("ok")

时间 O(n),空间 O(n)。暴力双重循环 O(n²);排序 + 双指针 O(n log n) 但会丢失原下标(需要排序下标数组)。

练习 10.5 · 难度 ★ · Valid Parentheses

判断只含 ()[]{} 的字符串是否括号匹配。

提示
list 当栈;dict 把右括号映射到左括号;最后栈必须为空。
参考答案
def is_valid(s):
    pair = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in pair:
            if not stack or stack.pop() != pair[ch]:
                return False
        else:
            stack.append(ch)
    return not stack

assert is_valid("()[]{}") and is_valid("{[()]}") and is_valid("")
assert not is_valid("(]") and not is_valid("([)]") and not is_valid("((") and not is_valid(")")
print("ok")

O(n) 时间,O(n) 空间。常见错误:忘记最后检查栈为空("((" 会被判为合法);对空栈 pop 抛 IndexError。

练习 10.6 · 难度 ★★ · Top K Frequent Elements

返回数组中出现频率最高的 k 个元素(任意顺序)。给出 O(n log k) 和 O(n) 两种解法。

提示
Counter + 堆(heapq.nlargest(k, cnt, key=cnt.get));或者桶:频率最多为 n,buckets[f] 存频率为 f 的元素,从高到低收集。
参考答案
from collections import Counter
import heapq

def top_k_heap(nums, k):                        # O(n log k)
    cnt = Counter(nums)
    return heapq.nlargest(k, cnt.keys(), key=cnt.get)

def top_k_bucket(nums, k):                      # O(n)
    cnt = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]
    for x, f in cnt.items():
        buckets[f].append(x)
    out = []
    for f in range(len(buckets) - 1, 0, -1):
        for x in buckets[f]:
            out.append(x)
            if len(out) == k:
                return out
    return out

for fn in (top_k_heap, top_k_bucket):
    assert sorted(fn([1, 1, 1, 2, 2, 3], 2)) == [1, 2]
    assert fn([7], 1) == [7]
print("ok")

堆:计数 O(n),选 top-k O(m log k)(m 为不同元素数)。桶:O(n) 时间和空间。面试中先给 Counter + 堆,再提桶作为优化。

练习 10.7 · 难度 ★★ · Group Anagrams

把字符串数组按"变位词"分组。

提示
key 必须可哈希:排序后的字符串 "".join(sorted(s))(O(L log L)),或 26 维计数的 tuple(O(L))。
参考答案
from collections import defaultdict

def group_anagrams(strs):
    groups = defaultdict(list)
    for s in strs:
        key = [0] * 26
        for ch in s:
            key[ord(ch) - ord("a")] += 1
        groups[tuple(key)].append(s)            # list is unhashable -> tuple
    return list(groups.values())

def group_anagrams_sorted(strs):
    groups = defaultdict(list)
    for s in strs:
        groups["".join(sorted(s))].append(s)
    return list(groups.values())

def canon(gs):
    return sorted(sorted(g) for g in gs)
inp = ["eat", "tea", "tan", "ate", "nat", "bat"]
expected = [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
assert canon(group_anagrams(inp)) == expected == canon(group_anagrams_sorted(inp))
assert group_anagrams([""]) == [[""]]
print("ok")

计数 key:O(N·L);排序 key:O(N·L log L)。N 为字符串个数,L 为最大长度。

练习 10.8 · 难度 ★★ · Merge Intervals

合并所有重叠区间 [[1,3],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]]。端点相接([1,4],[4,5])也算重叠。

提示
按起点排序;当前区间起点 ≤ 结果中最后一个区间的终点就合并(更新终点为 max)。
参考答案
def merge(intervals):
    out = []
    for s, e in sorted(intervals):              # tuples/lists sort by start, then end
        if out and s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)     # max: [1,10] absorbs [2,3]
        else:
            out.append([s, e])
    return out

assert merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
assert merge([[1, 4], [4, 5]]) == [[1, 5]]
assert merge([[1, 10], [2, 3]]) == [[1, 10]]
assert merge([]) == []
print("ok")

O(n log n) 排序 + O(n) 扫描。常见 bug:直接 out[-1][1] = e 而不取 max(被包含的区间会把终点缩短)。另一个 bug:out.append(interval) 直接放入原列表对象,之后修改 out[-1][1] 会改动调用者的输入——上面用 [s, e] 新建列表避免了这个问题。

练习 10.9 · 难度 ★★ · Rotting Oranges(多源 BFS)

网格中 0 空、1 新鲜橘子、2 腐烂橘子;每分钟腐烂橘子会感染上下左右的新鲜橘子。求全部腐烂所需分钟数,不可能则返回 −1。

提示
所有腐烂橘子同时作为 BFS 起点;按层 BFS,层数就是分钟数;记录新鲜橘子数量,最后检查是否归零。
参考答案
from collections import deque

def oranges_rotting(grid):
    grid = [row[:] for row in grid]
    R, C = len(grid), len(grid[0])
    q = deque()
    fresh = 0
    for r in range(R):
        for c in range(C):
            if grid[r][c] == 2:
                q.append((r, c))
            elif grid[r][c] == 1:
                fresh += 1
    minutes = 0
    while q and fresh:
        for _ in range(len(q)):                 # one minute = one BFS level
            r, c = q.popleft()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 1:
                    grid[nr][nc] = 2
                    fresh -= 1
                    q.append((nr, nc))
        minutes += 1
    return minutes if fresh == 0 else -1

assert oranges_rotting([[2, 1, 1], [1, 1, 0], [0, 1, 1]]) == 4
assert oranges_rotting([[2, 1, 1], [0, 1, 1], [1, 0, 1]]) == -1
assert oranges_rotting([[0, 2]]) == 0
assert oranges_rotting([[0]]) == 0
print("ok")

O(R·C) 时间和空间。while q and fresh 中的 fresh 条件避免了"最后一层没有感染任何橘子却多算一分钟"。

练习 10.10 · 难度 ★★ · Max Area of Island(DFS + nonlocal 或返回值)

网格中 1 为陆地,求最大岛屿面积。要求写两种:递归 DFS 返回面积;迭代栈版本。

提示
递归函数返回 1 + 四个方向的面积之和,访问后置 0。
参考答案
def max_area_rec(grid):
    g = [row[:] for row in grid]
    R, C = len(g), len(g[0])
    def area(r, c):
        if not (0 <= r < R and 0 <= c < C) or g[r][c] != 1:
            return 0
        g[r][c] = 0
        return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)
    return max((area(r, c) for r in range(R) for c in range(C)), default=0)

def max_area_iter(grid):
    g = [row[:] for row in grid]
    R, C = len(g), len(g[0])
    best = 0
    for sr in range(R):
        for sc in range(C):
            if g[sr][sc] != 1:
                continue
            g[sr][sc] = 0
            stack, size = [(sr, sc)], 0
            while stack:
                r, c = stack.pop()
                size += 1
                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= nr < R and 0 <= nc < C and g[nr][nc] == 1:
                        g[nr][nc] = 0          # mark when pushing
                        stack.append((nr, nc))
            best = max(best, size)
    return best

g = [[0, 0, 1, 0, 0],
     [0, 1, 1, 0, 1],
     [0, 1, 0, 0, 1],
     [0, 0, 0, 1, 1]]
assert max_area_rec(g) == 4 == max_area_iter(g)
assert max_area_rec([[0]]) == 0 == max_area_iter([[0]])
print("ok")

O(R·C)。迭代版"压栈时标记"保证每个格子只入栈一次。

练习 10.11 · 难度 ★★ · LRU Cache(OrderedDict 版 + 手写双向链表版)

实现 LRUCache(capacity),支持 get(key)(不存在返回 −1)和 put(key, value),均 O(1);超过容量时淘汰最久未使用的 key。面试官常追问:"不用 OrderedDict 怎么写?"

提示
OrderedDict:访问时 move_to_end,淘汰时 popitem(last=False)。手写:dict 存 key → 节点,双向链表维护顺序,用头尾哨兵节点避免边界判断。
参考答案
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.od = OrderedDict()
    def get(self, key):
        if key not in self.od:
            return -1
        self.od.move_to_end(key)                # mark as most recently used
        return self.od[key]
    def put(self, key, value):
        if key in self.od:
            self.od.move_to_end(key)
        self.od[key] = value
        if len(self.od) > self.cap:
            self.od.popitem(last=False)         # evict least recently used

class Node:
    __slots__ = ("key", "val", "prev", "next")
    def __init__(self, key=0, val=0):
        self.key, self.val, self.prev, self.next = key, val, None, None

class LRUCacheManual:
    def __init__(self, capacity):
        self.cap, self.map = capacity, {}
        self.head, self.tail = Node(), Node()   # sentinels: head <-> ... <-> tail
        self.head.next, self.tail.prev = self.tail, self.head
    def _remove(self, node):
        node.prev.next, node.next.prev = node.next, node.prev
    def _push_front(self, node):                # front = most recent
        node.prev, node.next = self.head, self.head.next
        self.head.next.prev = node
        self.head.next = node
    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return -1
        self._remove(node); self._push_front(node)
        return node.val
    def put(self, key, value):
        if key in self.map:
            node = self.map[key]
            node.val = value
            self._remove(node); self._push_front(node)
            return
        node = Node(key, value)
        self.map[key] = node
        self._push_front(node)
        if len(self.map) > self.cap:
            lru = self.tail.prev                # least recent is just before tail
            self._remove(lru)
            del self.map[lru.key]               # that's why nodes store their key

for Cls in (LRUCache, LRUCacheManual):
    c = Cls(2)
    c.put(1, 1); c.put(2, 2)
    assert c.get(1) == 1                        # order now: 2 (old), 1 (new)
    c.put(3, 3)                                 # evicts 2
    assert c.get(2) == -1
    c.put(4, 4)                                 # evicts 1
    assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
    c.put(3, 30)                                # update existing key
    assert c.get(3) == 30
print("ok")

两种实现所有操作都是 O(1),空间 O(capacity)。手写版的关键:节点里存 key(淘汰时要从 dict 删除);哨兵节点消除空链表的特判。这正是 C 里你会写的双向链表,只是指针换成了对象引用。

练习 10.12 · 难度 ★ · Min Stack

设计一个栈,支持 push、pop、top、get_min,全部 O(1)。

提示
每个元素同时存"入栈时的当前最小值":栈元素是 (x, min_so_far)。
参考答案
class MinStack:
    def __init__(self):
        self.st = []                            # (value, min of stack up to here)
    def push(self, x):
        m = min(x, self.st[-1][1]) if self.st else x
        self.st.append((x, m))
    def pop(self):
        return self.st.pop()[0]
    def top(self):
        return self.st[-1][0]
    def get_min(self):
        return self.st[-1][1]

s = MinStack()
for x in [5, 3, 7, 3, 1]:
    s.push(x)
assert s.get_min() == 1
s.pop(); assert s.get_min() == 3
s.pop(); assert s.get_min() == 3                # duplicate 3 handled
s.pop(); assert s.top() == 3 and s.get_min() == 3
s.pop(); assert s.get_min() == 5
print("ok")

所有操作 O(1),空间 O(n)。只在"新最小值"时压入辅助栈的优化版本要注意重复最小值(用 <=)。

练习 10.13 · 难度 ★★ · 生成器流水线:大文件词频统计

给一个"可能很大、无法一次读进内存"的文本流,写生成器流水线:逐行读 → 切分并小写化 → 去掉标点 → 统计词频,返回前 k 个 (word, count),计数相同按字典序。要求内存只与不同单词数有关。

提示
文件对象本身就是逐行的迭代器;每个阶段写成一个生成器函数;最后用 Counter.update(generator);排序 key (-count, word)。
参考答案
import io, re, heapq
from collections import Counter

WORD = re.compile(r"[a-z0-9']+")

def lines(f):
    for line in f:                              # lazily, one line at a time
        yield line

def words(line_iter):
    for line in line_iter:
        yield from WORD.findall(line.lower())   # strips punctuation

def top_k_words(f, k):
    cnt = Counter()
    cnt.update(words(lines(f)))                 # consumes the pipeline lazily
    return heapq.nsmallest(k, cnt.items(), key=lambda kv: (-kv[1], kv[0]))

text = io.StringIO("The cat. The dog!\nthe CAT and a bird\n")
assert top_k_words(text, 2) == [("the", 3), ("cat", 2)]
assert top_k_words(io.StringIO(""), 3) == []
tie = io.StringIO("b a c a b")
assert top_k_words(tie, 3) == [("a", 2), ("b", 2), ("c", 1)]   # ties: alphabetical
print("ok")

时间 O(N + U log k),N 为总词数,U 为不同词数;内存 O(U)(加一行文本)。真实场景中文件用 with open(path) as f:;数据大到 U 也装不下时,要按 hash 分片写到多个文件,再分别统计(MapReduce 思路)。

练习 10.14 · 难度 ★★ · Merge k Sorted Lists(堆 + tie-break)

合并 k 个有序链表。节点类 ListNode 没有定义 __lt__。

提示
堆元素 (node.val, i, node),i 是链表编号或全局计数器,避免值相同时比较节点。
参考答案
import heapq, itertools

class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next

def build(xs):
    dummy = cur = ListNode()
    for x in xs:
        cur.next = ListNode(x); cur = cur.next
    return dummy.next

def to_list(node):
    out = []
    while node:
        out.append(node.val); node = node.next
    return out

def merge_k(lists):
    cnt = itertools.count()
    heap = [(n.val, next(cnt), n) for n in lists if n]
    heapq.heapify(heap)
    dummy = tail = ListNode()
    while heap:
        _, _, node = heapq.heappop(heap)
        tail.next = node; tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, next(cnt), node.next))
    return dummy.next

ls = [build([1, 4, 5]), build([1, 3, 4]), build([2, 6])]
assert to_list(merge_k(ls)) == [1, 1, 2, 3, 4, 4, 5, 6]
assert merge_k([]) is None and merge_k([None]) is None
print("ok")

O(N log k),N 为总节点数;堆大小 O(k)。哑节点(dummy head)技巧免去对结果链表头的特判。

练习 10.15 · 难度 ★★ · Longest Consecutive Sequence(O(n))

未排序整数数组,求最长连续整数序列的长度,要求 O(n)。

提示
放进 set;只从"序列起点"(x − 1 不在集合中)开始往上数。
参考答案
def longest_consecutive(nums):
    s = set(nums)
    best = 0
    for x in s:                                 # iterate the set: duplicates skipped
        if x - 1 not in s:                      # x starts a run
            y = x
            while y + 1 in s:
                y += 1
            best = max(best, y - x + 1)
    return best

assert longest_consecutive([100, 4, 200, 1, 3, 2]) == 4
assert longest_consecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9
assert longest_consecutive([]) == 0
print("ok")

每个数最多在 while 中被访问一次(只有起点才会进入 while),总 O(n)。遍历 s 而不是 nums,避免大量重复元素时重复从同一起点数。

练习 10.16 · 难度 ★★ · 找 bug:Python 对象模型综合

下面的代码想构建图的邻接表、BFS 求每个节点的层号,并把每层节点收集起来。找出所有 bug(至少 4 个)。

def levels(n, edges, src, out=[]):
    adj = [[]] * n
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)
    q, seen = [src], {src}
    while q:
        level = q
        out.append(level)
        q = []
        for u in level:
            for v in adj[u]:
                if v not in seen:
                    q.append(v)
            seen.add(u)
    return out
提示
检查:默认参数、列表乘法、标记 visited 的时机。
参考答案
  1. out=[] 可变默认参数:多次调用结果会累积 → out=None。
  2. [[]] * n:n 个引用指向同一个 list,所有节点共享邻接表 → [[] for _ in range(n)]。
  3. seen.add(u) 在处理完 u 之后才标记(且标记的是 u 而不是 v):同一层的多个节点会把同一个 v 重复入队 → 在入队时 seen.add(v)。
  4. (较隐蔽)因为 bug 3,同一个 v 也可能出现在后续层中。修好后 level = q; q = [] 这种重新绑定本身是正确的(没有原地修改 level)。
def levels(n, edges, src, out=None):
    if out is None:
        out = []
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)
    q, seen = [src], {src}
    while q:
        out.append(q)
        nxt = []
        for u in q:
            for v in adj[u]:
                if v not in seen:
                    seen.add(v)                 # mark when enqueuing
                    nxt.append(v)
        q = nxt
    return out

E = [(0, 1), (0, 2), (1, 3), (2, 3)]
assert levels(4, E, 0) == [[0], [1, 2], [3]]
assert levels(4, E, 0) == [[0], [1, 2], [3]]    # no accumulation across calls
assert levels(1, [], 0) == [[0]]
print("ok")

这里用 list 作为"每层的队列",按层整体替换,不需要 popleft,所以也是 O(V + E)。

练习 10.17 · 难度 ★★★ · 网格最小代价路径(Dijkstra on grid)

网格每格有非负代价,从左上走到右下(四方向),路径代价 = 经过格子代价之和(含起点和终点)。求最小代价。并说明为什么不能用普通 BFS、什么时候可以用 DP。

提示
边权不等 → Dijkstra;如果只能向右/向下走,则是 DAG,可以直接 DP。
参考答案
import heapq

def min_path_cost(grid):
    R, C = len(grid), len(grid[0])
    INF = float("inf")
    dist = [[INF] * C for _ in range(R)]
    dist[0][0] = grid[0][0]
    pq = [(grid[0][0], 0, 0)]
    while pq:
        d, r, c = heapq.heappop(pq)
        if (r, c) == (R - 1, C - 1):
            return d                            # first pop of the target is optimal
        if d > dist[r][c]:
            continue
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < R and 0 <= nc < C:
                nd = d + grid[nr][nc]
                if nd < dist[nr][nc]:
                    dist[nr][nc] = nd
                    heapq.heappush(pq, (nd, nr, nc))

def min_path_right_down(grid):                  # LeetCode 64: DAG -> DP
    R, C = len(grid), len(grid[0])
    dp = [0] * C
    for r in range(R):
        for c in range(C):
            if r == 0 and c == 0:
                dp[c] = grid[0][0]
            elif r == 0:
                dp[c] = dp[c - 1] + grid[r][c]
            elif c == 0:
                dp[c] = dp[c] + grid[r][c]
            else:
                dp[c] = min(dp[c], dp[c - 1]) + grid[r][c]
    return dp[-1]

g = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
assert min_path_cost(g) == 7 == min_path_right_down(g)
snake = [[1, 1, 1], [9, 9, 1], [1, 1, 1], [1, 9, 9], [1, 1, 1]]
assert min_path_cost(snake) == 11               # needs left/up moves
assert min_path_right_down(snake) == 15          # right/down only is worse
print("ok")

Dijkstra:O(RC log(RC))。普通 BFS 只在边权都相同时给出最短路;边权只有 0/1 时可用 0-1 BFS(deque,权 0 放队头)。只能右/下时状态图无环,按行列顺序 DP 即可 O(RC)。

练习 10.18 · 难度 ★★ · 类与 dunder:可哈希、可排序的分数类

实现 Frac(num, den):自动约分、分母为正;支持 +、==、<(从而能 sorted)、能做 dict key、repr 显示为 Frac(1, 2)。用标准库 fractions.Fraction 做对拍。

提示
math.gcd;__hash__ 返回 hash((num, den)),因为约分后相等的分数表示唯一;或者用 @dataclass(frozen=True, order=False) 加 __post_init__。
参考答案
import math, random
from fractions import Fraction

class Frac:
    __slots__ = ("num", "den")
    def __init__(self, num, den=1):
        if den == 0:
            raise ZeroDivisionError("zero denominator")
        if den < 0:
            num, den = -num, -den
        g = math.gcd(num, den)                  # gcd is always >= 0
        self.num, self.den = num // g, den // g
    def __add__(self, other):
        return Frac(self.num * other.den + other.num * self.den, self.den * other.den)
    def __eq__(self, other):
        return isinstance(other, Frac) and (self.num, self.den) == (other.num, other.den)
    def __hash__(self):                         # canonical form -> equal objects hash equally
        return hash((self.num, self.den))
    def __lt__(self, other):                    # dens positive, so cross-multiply safely
        return self.num * other.den < other.num * self.den
    def __repr__(self):
        return f"Frac({self.num}, {self.den})"

assert Frac(2, -4) == Frac(-1, 2) and repr(Frac(2, -4)) == "Frac(-1, 2)"
assert Frac(1, 2) + Frac(1, 3) == Frac(5, 6)
assert {Frac(1, 2): "half"}[Frac(3, 6)] == "half"
assert sorted([Frac(1, 2), Frac(-1, 3), Frac(1, 4)]) == [Frac(-1, 3), Frac(1, 4), Frac(1, 2)]
rng = random.Random(1)
for _ in range(300):
    a, b = rng.randint(-9, 9), rng.choice([i for i in range(-9, 10) if i])
    c, d = rng.randint(-9, 9), rng.choice([i for i in range(-9, 10) if i])
    s = Frac(a, b) + Frac(c, d)
    ref = Fraction(a, b) + Fraction(c, d)
    assert (s.num, s.den) == (ref.numerator, ref.denominator)
    assert (Frac(a, b) < Frac(c, d)) == (Fraction(a, b) < Fraction(c, d))
print("ok")

要点:规范化(约分 + 分母为正)让"相等 ⇔ 字段相同",从而 __hash__ 可以直接对字段求哈希,满足"相等则哈希相等"。只定义 __lt__ 就足以让 sorted/min/heapq 工作;需要全部比较运算符可用 functools.total_ordering。

练习 10.19 · 难度 ★★ · 装饰器:带调用次数与缓存统计的 memoize

不用 functools.cache,写一个装饰器 memoize:缓存位置参数的结果,提供 f.hits、f.misses 属性,保留函数名;用它装饰递归的 fib,验证 fib(30) 的 misses 恰为 31。

提示
闭包里的 dict;把计数器挂在 wrapper 函数对象上;递归调用会经过被装饰后的名字,所以子调用也会被缓存。
参考答案
import functools

def memoize(func):
    cache = {}
    @functools.wraps(func)
    def wrapper(*args):
        if args in cache:
            wrapper.hits += 1
            return cache[args]
        wrapper.misses += 1
        result = cache[args] = func(*args)
        return result
    wrapper.hits = wrapper.misses = 0
    wrapper.cache = cache
    return wrapper

@memoize
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)   # `fib` here is the WRAPPER

assert fib(30) == 832040
assert fib.misses == 31                     # n = 0..30, each computed once
assert fib.hits == 28                       # see explanation below
assert fib.__name__ == "fib"
print("ok")

解释 hits = 28:计算 fib(n) 时先递归 fib(n-1)(miss,一路向下到 fib(1)),回溯时每个 fib(n-2) 都已经算过(hit)。n 从 2 到 30 共有 29 次 fib(n-2) 调用,其中 fib(2) 调用的 fib(0) 是第一次出现(miss),所以 hits = 28,misses = 31。复杂度从 O(φ^n) 降为 O(n)。

练习 10.20 · 难度 ★★ · Product of Array Except Self

返回 out[i] = 除 nums[i] 外所有元素的乘积,不能用除法,O(n) 时间,除输出外 O(1) 额外空间。

提示
先从左到右写入前缀积,再从右到左乘上后缀积(用一个变量)。
参考答案
def product_except_self(nums):
    n = len(nums)
    out = [1] * n
    for i in range(1, n):
        out[i] = out[i - 1] * nums[i - 1]       # product of everything left of i
    suffix = 1
    for i in range(n - 1, -1, -1):
        out[i] *= suffix                        # times product of everything right of i
        suffix *= nums[i]
    return out

assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6]
assert product_except_self([-1, 1, 0, -3, 3]) == [0, 0, 9, 0, 0]
print("ok")

O(n) 时间,O(1) 额外空间(输出数组不计)。Python 的大整数保证没有溢出问题;C/Java 实现中题目会保证结果在 32 位范围内。

§ · CHEAT SHEET一页速查(面试前一晚)

只看这一节也能把本章的关键点过一遍。每一行都在上文有完整解释和测试。

对象模型 10 条

规则一句话
赋值绑定名字,从不拷贝;b = a 后两者是同一对象
is vs ==身份 vs 值;is 只用于 None/True/False
不可变int float bool str tuple frozenset bytes None
可哈希dict key / set 元素 / @cache 参数必须可哈希;list → tuple
传参传对象引用:原地修改外部可见,重新绑定不可见
二维初始化[[0] * m for _ in range(n)],永远不要 [[0] * m] * n
默认参数只求值一次 → def f(x=None): if x is None: x = []
回溯res.append(path[:])(拷贝!)
+=list 原地 extend;int/str/tuple 新对象
原地方法返回 Nonesort reverse append extend 等;不要 a = a.sort()

数字与控制流

  • / 永远 float;// 向 −∞ 取整:-7 // 2 == -4(C 为 −3);-7 % 2 == 1(C 为 −1);C 风格截断 int(a / b)。
  • int 不溢出;math.inf 做哨兵;math.isclose(a, b, abs_tol=…);round(2.5) == 2。
  • 假值:None False 0 0.0 "" [] {} set() ();and/or 返回操作数。
  • enumerate / zip / reversed / range(n-1, -1, -1);for 里改 i 无效 → 用 while;for…else = no-break。
  • 0 <= r < R;a, b = b, a;x if c else y。

复杂度(必须背)

O(1)O(log n)O(n)O(n log n)
list 下标、append*、pop();dict/set 查改删†;deque 两端;h[0];lenheappush/heappop;bisect_*x in list;pop(0)/insert(0);切片复制;heapify;''.join;Counter(xs);insortsort/sorted(稳定 Timsort);most_common() 无参数

* 均摊 † 平均(最坏 O(n)) nlargest(k) / most_common(k):O(n log k)

标准库 API 速记

from collections import deque, defaultdict, Counter, OrderedDict
import heapq, bisect, math, itertools, functools, sys

q = deque(); q.append(x); q.appendleft(x); q.pop(); q.popleft(); deque(maxlen=k)
d = defaultdict(list); d[k].append(v)          # reading d[k] inserts!
c = Counter(xs); c[x]; c.most_common(k); c1 == c2; c.update(ys)
od = OrderedDict(); od.move_to_end(k); od.popitem(last=False)
heapq.heappush(h, (prio, next(cnt), item)); heapq.heappop(h); h[0]
heapq.heapify(lst); heapq.heapreplace(h, x); heapq.nlargest(k, xs, key=f)
# max-heap: push -x, negate again after popping
bisect.bisect_left(a, x)  # first >= x     bisect.bisect_right(a, x)  # first > x
sorted(xs, key=lambda t: (t[1], -t[0]), reverse=False); functools.cmp_to_key(cmp)
@functools.cache   /   @functools.lru_cache(maxsize=None);  f.cache_clear()
sys.setrecursionlimit(10**6);  data = sys.stdin.buffer.read().split()
itertools.accumulate(a, initial=0) / product / permutations / combinations / groupby / pairwise
math.inf, math.gcd, math.isqrt, math.comb, pow(a, b, mod)
ord('a') == 97, chr(97) == 'a', ''.join(parts), s.split(), s[::-1]

语言机制一句话

问题回答要点
为什么 Python 慢?解释字节码 + 动态类型派发 + 每个值都是堆对象(装箱)→ 向量化到 C/CUDA
内存怎么回收?引用计数(归零立即释放)+ 分代循环 GC;显存泄漏 = 还有引用(losses.append(loss))
GIL?同一时刻一个线程执行字节码;CPU 密集用多进程,I/O 用线程/asyncio;C 扩展释放 GIL;3.13 起有可选 free-threaded 构建(3.14 官方支持,非默认)
model(x) 为什么能跑?nn.Module.__call__ → hooks + forward
为什么要 super().__init__()?创建 _parameters/_modules/_buffers,__setattr__ 靠它注册子模块
装饰器?@d def f ≡ f = d(f);wrapper 用 *args, **kwargs + functools.wraps
yield?生成器:暂停/恢复,保留局部状态,惰性 O(1) 内存,只能遍历一次
with torch.no_grad()?上下文管理器:进入关梯度记录,退出恢复;与 model.eval() 无关
nonlocal?内层函数重新绑定外层变量时需要;原地修改不需要

模板关键行

模板关键复杂度
BFSdeque;入队时标记 visited;按层 for _ in range(len(q))O(V+E)
DFS递归简洁;深了用显式栈;有向图判环三色O(V+E)
拓扑入度为 0 入队;输出数 < n 有环O(V+E)
Dijkstra(d, u) 堆;if d > dist[u]: continueO((V+E) log V)
并查集路径压缩 + 按大小合并;union 返回 False = 成环≈O(1) 均摊
二分while lo < hi: mid; pred → hi = mid else lo = mid + 1O(log n)
滑动窗口右扩一步;while 不合法左缩O(n)
单调栈栈存下标;弹出时记录答案;哨兵 0O(n)
前缀和count[0] = 1;ans += count[s - k]O(n)
回溯选择-递归-撤销;path[:];排序 + i > start 去重指数
DP状态/转移/边界;@cache 或表格;0/1 背包倒序状态 × 转移

高频面试题清单

  1. What's the difference between is and ==? → §1 id/is/==
  2. Is Python pass-by-value or pass-by-reference? → §1 传参
  3. Mutable vs immutable types; why can't a list be a dict key? → §1 可变性, §3 dict
  4. Shallow vs deep copy; what's wrong with [[0]*3]*3? → §1 拷贝
  5. Why is a mutable default argument dangerous? → §1 默认参数
  6. What does -7 // 2 return and why? → §2 整数
  7. Time complexity of list operations (append, pop(0), insert, in)? → §3 list
  8. How is a dict implemented? Average/worst case? Why does order persist? → §3 dict
  9. Why use deque for BFS? → §3 collections
  10. How do you get a max-heap with heapq? How to handle ties? → §3 heapq
  11. Find the top-k largest elements; complexity? → §3 heapq, 练习 10.6
  12. bisect_left vs bisect_right? → §3 bisect
  13. Why is string concatenation in a loop slow? → §3 str
  14. List comprehension vs generator expression? → §4 推导式
  15. Sort by multiple keys / descending on one field; is the sort stable? → §4 排序
  16. What do *args and **kwargs do? → §4 参数
  17. What is a closure? When do you need nonlocal? → §4 闭包
  18. How do you memoize a recursive function? Recursion limit? → §4 lru_cache
  19. Instance vs class attributes? → §5 类
  20. What are dunder methods? How does model(x) call forward? → §5 dunder
  21. Why must you call super().__init__() in an nn.Module? → §5 继承
  22. What does yield do? Generator vs list? → §6 生成器
  23. Write a timing decorator. → §6 装饰器
  24. What is a context manager? How does torch.no_grad() work? → §6 上下文管理器
  25. Why are Python loops slow? → §8 字节码
  26. How does Python manage memory? Why isn't my GPU memory freed? → §8 内存
  27. What is the GIL? Threads vs processes vs asyncio? → §8 GIL
  28. Implement an LRU cache. → 练习 10.11

§ · RECALL自测卡片

先自己说出答案(最好用英文出声),再点开对照并打分。