目录
正在加载目录…
正在阅读专栏 Algorithms:CLRS + MIT 6.006 第 2 篇 · 共 24 篇 · 8%

Models of Computation:RAM、Python Cost Model 与 Document Distance

发布于 2026-09-18 17:25 · 最后编辑于 2026-09-18 17:25 · 版本 v1 · 字数 5,001 · 预计阅读 11 分钟 👁 23 次阅读

Algorithms:Models of Computation and Document Distance

本文逐段翻译 MIT 6.006 Fall 2011 Lecture 2《Models of Computation and Document Distance》,建立 algorithm、model of computation、RAM、pointer machine 与 Python cost model 的关系,并用 document distance 说明数据结构选择如何改变复杂度和实际运行时间。

TL;DR

  • 算法不是脱离机器的代码:algorithm 是解决问题的 computational procedure;model of computation 规定允许哪些 operations,以及每个 operation 的 cost。
  • RAM 与 pointer machine:RAM 适合 array/index/register 操作;pointer machine 适合动态对象和 references。
  • Python 代码也要计成本:list 接近 RAM array,object attributes 接近 pointer machine;dict、heapq、long integer arithmetic 各有不同复杂度。
  • Document distance:把 document 表示成 word-frequency vector,用 normalized dot product 或夹角表示相似程度。
  • 算法优化路径:从排序后双重查找,到双指针 merge,再到 dictionary counting,示例从 228.1 秒降到 0.2 秒。

目录

章节说明
Lecture 2:Models of Computation本讲的问题与历史背景
什么是 algorithmalgorithm 与 model of computation
Random Access Machine(RAM)word、register 与 constant-time operations
Pointer machine动态对象与 references
Python cost model常见 Python operations 的复杂度
Document distance problemword vector 与 normalized distance
Document distance algorithmssorting、merge 与 dictionary approaches
实际运行时间优化路径的 measurement

Lecture 2:Models of Computation

上一讲通过 peak finding 介绍了 algorithmic thinking。本讲先退一步,讨论什么是 algorithm、algorithm 可以做什么,以及 time 和 running time 应该如何定义;随后用 document distance 作为贯穿示例。

“algorithm” 一词来自 Muhammad ibn Musa al-Khwarizmi(约 780–850)。他被称为 algebra 的“父亲”之一,所著的《The Compendious Book on Calculation by Completion & Balancing》讨论了 linear 和 quadratic equations 的求解,是早期系统描述 algorithmic procedures 的著作之一。

什么是 algorithm

algorithm 是 computer program 的一种 mathematical abstraction,也就是用于解决某个 problem 的 computational procedure。

text
programming language     pseudocode
          │                  │
          ▼                  ▼
       program            algorithm
          │                  │
          └──── built on top ┘
                 of
        model of computation

model of computation 规定:

  • algorithm 被允许执行哪些 operations;
  • 每个 operation 的 cost 是多少,例如 time、space 或其他 resource;
  • algorithm 的总 cost 是所有 operations 的 cost 之和。

因此,复杂度分析不能只看 pseudocode 的行数;必须先明确每一行在什么 machine model 下执行。

Random Access Machine(RAM)

Random Access Machine(RAM)把 Random Access Memory 建模成一个很大的 array。machine 还有 Θ(1) 个 registers,每个 register 能存放一个 word。

text
memory:
address  0   1   2   3   4   5   ...
          │   │   │   │   │   │
          └── random access ──────┘

registers: r0, r1, ...        (Θ(1) 个)

在 Θ(1) time 内,RAM 可以 load 某个 address 的 word、对 registers 执行 +、-、*、/、&、|、^ 等 operations,并把 register value store 回 memory。

一个 word 至少包含 lg(memory size) bits:

text
w ≥ lg(memory size)

我们假定基本 objects(例如普通 int)可以放入一个 word。需要多个 words 表示的 big numbers 不能继续把 arithmetic 当作 constant-time;课程 Unit 4 会专门讨论这一点。

Pointer machine

pointer machine 以 dynamically allocated objects 为核心。对象可以有 O(1) 个 fields,每个 field 要么是 word,要么是 pointer/reference,或者是 null。

text
object A                 object B
┌───────────────┐        ┌───────────────┐
│ val: 5        │        │ val: -1       │
│ prev: null    │        │ prev: ────────┼──► A
│ next: ────────┼───────►│ next: null    │
└───────────────┘        └───────────────┘

pointer machine 比 RAM 弱,但可以在 RAM 上实现。它直接表达 linked structures、动态对象和 references;沿着 pointer 找下一个 object 是 constant-time,但访问任意第 i 个 object 通常不能像 RAM array 那样直接跳转。

Python cost model

Python 允许我们用两种方式思考:某些 objects 接近 RAM array,另一些接近 pointer machine。分析 Python operation 的 cost 时,可以想象它如何由这两种模型实现。

list、tuple 和 string

Python list 可以看作 array:

python
L[i] = L[j] + 5       # Θ(1)

L.append(x) 的 amortized cost 是 Θ(1);容量不足时通过 table doubling 扩容。连接两个 lists 需要复制内容:

python
L = L1 + L2           # Θ(1 + |L1| + |L2|)
L1.extend(L2)         # Θ(1 + |L2|)
L2 = L1[i:j]           # Θ(j - i + 1)
x in L                # 最坏 Θ(|L|)
len(L)                # Θ(1),length 保存在 field 中
L.sort()              # Θ(|L| log |L|)

tuple 和 string 可以近似看作 immutable lists,因此许多 indexing、slice 和 traversal costs 类似,但不能原地修改。

dict、set、heapq 和 long

dict 通常通过 hashing 实现:

python
D[key] = value
value = D[key]        # Θ(1) w.h.p.,假设 hash table 状态良好

set 可以看作没有 values 的 dict。heapq.heappush 和 heapq.heappop 基于 heaps,实现为 Θ(log n)。

Python long integer 可能占用多个 words。若 |x| 表示表示 x 所需的 words 数量:

text
x + y       O(|x| + |y|)
x * y       O((|x| + |y|)^log₂3)
            ≈ O((|x| + |y|)^1.58)

这里的 multiplication 上界来自 Karatsuba algorithm,而不是单 word multiplication 的 Θ(1)。

Document distance problem

document distance 用于查找相似 documents、检测 duplicates 和 plagiarism,也可用于 web search,其中 query 可以看作一个 document。

定义:

  • word:由 alphanumeric characters 组成的 sequence;
  • document:由 words 组成的 sequence,忽略 spaces、punctuation 等。

将 document D 表示为 vector:

text
D[w] = word w 在 document D 中出现的次数

例如:

text
D1 = "the cat"
D2 = "the dog"

Dot product 与 normalization

最初可以定义:

text
d′(D1, D2) = D1 · D2
             = Σw D1[w] · D2[w]

但这个定义不是 scale invariant:长 documents 即使比例相同,也会因为包含更多 words 而产生更大的数值。可以按 document sizes normalization:

text
d′′(D1, D2) =              D1 · D2
                ─────────────────────────
                |D1| · |D2|

其中 |D_i| 是 document i 中 words 的数量。从 geometric interpretation 看,可以把 distance 定义成 vectors 的夹角:

text
d(D1, D2) = arccos(d′′(D1, D2))

角度 0° 表示两个 documents 相同;角度 90° 表示没有共同 words。这种方法由 Salton、Wong 和 Yang 在 1975 年提出。

Document distance algorithms

计算 document distance 可以分成三步:

  1. 把每个 document split 成 words;
  2. 统计每个 word 的 frequency,构造 document vectors;
  3. 计算 dot product,并除以 normalization factor。

可以尝试:

python
re.findall(r"\w+", doc)

但一般 regular expression engine 可能有 exponential-time behavior。只识别 alphanumeric words 时,可以逐字符扫描:

python
words = []
word = ""
for char in doc:
    if char.isalnum():
        word += char
    else:
        if word:
            words.append(word)
        word = ""
if word:
    words.append(word)

扫描成本为 Θ(|doc|)。之后排序,再把相邻相同 words 合并计数:

text
sort(words)                    O(k log k · |word|)
遍历排序后的 words              O(|doc|)
合并相同 word                   O(|word|)

若对 doc1 的每个 word 都从头在 doc2 中查找,成本约为 O(k1 · k2),还要乘上比较 words 的字符成本。

方案二:排序后用双指针 merge

两个 word lists 已排序时,同时从开头移动两个 pointers:

text
i ← list1 的开头
j ← list2 的开头
while i、j 都未到末尾:
    if word1[i] == word2[j]:
        total += count1[i] * count2[j]
        i、j 同时前进
    else if word1[i] ≤ word2[j]:
        i 前进
    else:
        j 前进

每一步至少推进一个 pointer,因此忽略字符比较成本时,work 为 Θ(k1 + k2);纳入字符长度后,仍可按 documents 总长度估计。

方案三:dictionary counting

用 dictionary 统计 frequencies:

python
count = {}
for word in doc:
    if word in count:
        count[word] += 1
    else:
        count[word] = 1

在 dictionary lookup 以 high probability 为 Θ(1) 的 model 下,处理 document 的成本为 O(|doc|) w.h.p.。随后遍历较小的 dictionary,对另一个 dictionary lookup 并累加:

python
total = 0
for word, count1 in counts1.items():
    if word in counts2:
        total += count1 * counts2[word]

该版本避免显式 sorting,也避免 O(k1 · k2) 的 nested search;代价是复杂度依赖 hashing model 和 hash table 的状态。

实际运行时间

课程使用两个文本测量:

text
t2.bobsey.txt   268,778 characters / 49,785 words / 3,354 unique words
t3.lewis.txt  1,031,470 characters / 182,355 words / 8,534 unique words

在 Pentium 4 2.8 GHz、CPython 2.62、Linux 2.6.26 上:

Version主要做法时间(秒)
docdist1regular expression、sorting、nested lookup228.1
docdist2改进逐行 words 的拼接164.7
docdist3insertion sort123.1
docdist4dictionary counting,但仍 sorting71.7
docdist5string.translate split words18.3
docdist6merge sort11.5
docdist7full dictionary approach1.8
docdist8一次处理整个 document0.2

这些数字不是今天机器上的 benchmark;它们展示了优化路径:从昂贵的 sorting 与 nested search,逐步转向更合适的 representation、hashing 和批量处理。algorithmic improvement 不只是减少一条语句,而是改变需要重复做什么,以及用什么 data structure 组织工作。

小结

model of computation 是复杂度分析的地基:RAM 将 array access 与 word arithmetic 视为 constant-time,pointer machine 强调动态对象和 references;Python 的 list、dict、heapq 和 long integers 继承了不同的 cost model。document distance 进一步说明,同一个数学目标可以用 sorting、merge 或 hashing 实现,而 data structure 的选择会同时改变渐进复杂度与实际运行时间。

参考资料

← 返回列表
← 上一篇 Algorithmic Thinking:Peak Finding 与复杂度分析 下一篇 → Sorting:Insertion Sort、Merge Sort 与递推树分析

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论