From 1a080be2a9cf374923220f51a090cd492ac732aa Mon Sep 17 00:00:00 2001 From: shaozk <913667678@qq.com> Date: Tue, 25 Aug 2026 17:07:17 +0800 Subject: [PATCH 1/2] Add: Chinese translation of memoryview() complexity documentation Co-Authored-By: opencode-agent[bot] --- docs/zh/builtins/memoryview_func.md | 429 ++++++++++++++++++++++++++++ 1 file changed, 429 insertions(+) create mode 100644 docs/zh/builtins/memoryview_func.md diff --git a/docs/zh/builtins/memoryview_func.md b/docs/zh/builtins/memoryview_func.md new file mode 100644 index 0000000..d7d579d --- /dev/null +++ b/docs/zh/builtins/memoryview_func.md @@ -0,0 +1,429 @@ +--- +source_sha: 26ab06b2234ef5af328ca310db336739cfcd9de23fad475459c794b9a4449591 +translated: machine +--- + +# memoryview() 函数的复杂度 + +`memoryview()` 函数在不拷贝数据的情况下创建字节类对象的内存视图。 + +## 复杂度分析 + +| 操作 | 时间 | 空间 | 备注 | +|------|------|-------|-------| +| 创建 memoryview | O(1) | O(1) | 仅创建视图,不拷贝底层数据 | +| 索引访问 | O(1) | O(1) | 直接内存访问 | +| 切片 | O(1) | O(1) | 创建新的视图对象,不拷贝数据 | +| `bytes(mv)` 转换 | O(n) | O(n) | n = 视图大小;拷贝数据 | +| 修改 | O(1) | O(1) | 仅当底层缓冲区可变时(如 bytearray) | + +## 方法 + +| 方法 | 时间 | 空间 | 备注 | +|--------|------|-------|-------| +| `tobytes()` | O(n) | O(n) | 转换为 bytes 对象 | +| `tolist()` | O(n) | O(n) | 转换为元素列表 | +| `toreadonly()` | O(1) | O(1) | 返回视图的只读版本 | +| `release()` | O(1) | O(1) | 释放底层缓冲区 | +| `cast(format)` | O(1) | O(1) | 重新解释为不同类型;字节大小必须相同 | +| `hex()` | O(n) | O(n) | 返回十六进制字符串表示 | +| `count(value)` | O(n) | O(1) | 统计 value 出现的次数 | +| `index(value)` | O(n) | O(1) | 查找 value 的第一个索引;未找到时抛出 ValueError | + +## 属性 + +| 属性 | 时间 | 备注 | +|-----------|------|-------| +| `obj` | O(1) | memoryview 引用的底层对象 | +| `nbytes` | O(1) | 视图中的总字节数 | +| `readonly` | O(1) | 布尔值,指示内存是否只读 | +| `format` | O(1) | 结构体格式字符串(如 'B' 表示无符号字节) | +| `itemsize` | O(1) | 每个元素的字节大小 | +| `ndim` | O(1) | 维度数量 | +| `shape` | O(1) | 各维度大小的元组 | +| `strides` | O(1) | 每个维度步进的字节数元组 | +| `suboffsets` | O(1) | 用于 PIL 风格数组的元组;简单缓冲区为 None | +| `contiguous` | O(1) | 布尔值;C 或 Fortran 连续时为 True | +| `c_contiguous` | O(1) | 布尔值;「C 序」连续时为 True | +| `f_contiguous` | O(1) | 布尔值;「Fortran 序」连续时为 True | + +## 基本用法 + +### 从 bytes 创建 + +```python +# O(1) - create view, no copy +b = b"hello" +mv = memoryview(b) +# + +# Access elements +mv[0] # 104 (ord('h')) +mv[1:3] # - slice is also O(1) view +``` + +### 从 bytearray 创建 + +```python +# O(1) - create view +ba = bytearray(b"hello") +mv = memoryview(ba) + +# Can modify through view +mv[0] = 72 # O(1) - changes 'h' to 'H' +print(ba) # bytearray(b'Hello') +``` + +### 从 array 创建 + +```python +# O(1) - works with array module +import array + +arr = array.array('i', [1, 2, 3, 4, 5]) +mv = memoryview(arr) + +# Access as view +mv[0] # 1 +``` + +## 复杂度细节 + +### 无拷贝 + +```python +# O(1) - memoryview doesn't copy data +b = b"a" * 10000 +mv = memoryview(b) # O(1) - instant, no copy + +# vs creating a list copy +lst = list(b) # O(n) - creates list + +# View uses original memory +``` + +### 切片 + +```python +# O(1) - slice is just another view +b = b"hello world" +mv = memoryview(b) + +# Original view +mv[0] # 104 + +# Slice - also O(1), doesn't copy +slice_view = mv[6:11] # - "world" + +# Can modify through slice (if writable) +``` + +### 索引 + +```python +# O(1) - direct memory access +mv = memoryview(b"test") + +# Read element +byte_val = mv[0] # 116 + +# Write element (if mutable) +ba = bytearray(b"test") +mv = memoryview(ba) +mv[0] = 84 # O(1) - changes to 'T' +``` + +## 常见模式 + +### 零拷贝数据访问 + +```python +# O(1) - no memory copy +data = bytearray(b"binary data here") +view = memoryview(data) # O(1) + +# Process without copying +def process(view): + for i in range(len(view)): + print(view[i]) + +process(view) # Efficient - no copy +``` + +### 高效的二进制协议 + +```python +# O(1) - parse binary data without copying +binary_data = b"\x01\x02\x03\x04" +view = memoryview(binary_data) + +# Parse header - O(1) +header_type = view[0] # 1 +header_version = view[1] # 2 + +# Parse payload - O(1) slice +payload = view[2:4] # +``` + +### 内存映射 + +```python +# O(1) - create view of mutable buffer +buffer = bytearray(1024) +view = memoryview(buffer) + +# Modify through view +view[0:4] = b"HEAD" # O(4) - copy 4 bytes + +# Read back +header = bytes(view[0:4]) # O(4) to convert to bytes +``` + +### 高效数据传输 + +```python +# O(1) - pass view instead of copying +def send_data(view): + # view is O(1) to create, no memory allocation + # Copy only when actually sending + bytes_to_send = bytes(view) # O(n) + # network.send(bytes_to_send) + +data = b"large data" * 1000 +view = memoryview(data) # O(1) - instant +# send_data(view) # Efficient +``` + +## 性能模式 + +### 对比拷贝 + +```python +# Inefficient - copying +data = b"x" * 10**6 +copy = data[100:200] # O(100) - creates new bytes + +# Efficient - memoryview +view = memoryview(data) # O(1) +slice_view = view[100:200] # O(1) - just a view +``` + +### 对比列表转换 + +```python +# List conversion - O(n) +b = b"hello" +lst = list(b) # O(5) - [104, 101, 108, 108, 111] + +# Memoryview - O(1) +mv = memoryview(b) # O(1) +mv[0] # 104 +``` + +### 批量处理 + +```python +# O(n) - process without copying +def process_chunks(data): + mv = memoryview(data) # O(1) + + # Process in chunks - O(n) total + for i in range(0, len(mv), 1024): + chunk = mv[i:i+1024] # O(1) per chunk - just view + process_chunk(chunk) # Process view + +data = b"x" * 1000000 +process_chunks(data) # Efficient - no copies +``` + +## 实际示例 + +### 二进制文件处理 + +```python +# O(1) - create view of file data +with open("large.bin", "rb") as f: + data = f.read() + +mv = memoryview(data) # O(1) + +# Access header without copying +magic = bytes(mv[0:4]) # O(4) - only copy what needed +version = mv[4] # O(1) + +# Process payload - O(1) view creation +payload = mv[16:] # O(1) +``` + +### 图像数据处理 + +```python +# O(1) - view image pixels +from PIL import Image + +img = Image.open("photo.png") +img_bytes = img.tobytes() # Get raw pixel data + +mv = memoryview(img_bytes) # O(1) view + +# Access pixel - O(1) +pixel_r = mv[0] # Red component +pixel_g = mv[1] # Green component +pixel_b = mv[2] # Blue component +``` + +### 网络协议解析器 + +```python +# O(1) - parse protocol messages +def parse_header(data): + view = memoryview(data) # O(1) + + # Extract fields - all O(1) + msg_type = view[0] + length = int.from_bytes(view[1:3], 'big') + flags = view[3] + + return { + 'type': msg_type, + 'length': length, + 'flags': flags + } + +packet = b"\x01\x00\x10\xFF" + b"payload..." +header = parse_header(packet) +``` + +### 高效缓冲区共享 + +```python +# O(1) - share buffer without copying +def fill_buffer(view, value): + for i in range(len(view)): + view[i] = value + +buffer = bytearray(1000) +view = memoryview(buffer) # O(1) + +fill_buffer(view, 0) # Fill with zeros - O(1000) +# buffer is now filled +``` + +## 边界情况 + +### 空的 memoryview + +```python +# O(1) +mv = memoryview(b"") # +len(mv) # 0 +``` + +### 单字节 + +```python +# O(1) +mv = memoryview(b"a") +mv[0] # 97 +``` + +### 不可变视图 + +```python +# O(1) - view of bytes (immutable) +mv = memoryview(b"hello") + +# Cannot modify +# mv[0] = 72 # TypeError - read-only buffer + +# But can create view +``` + +### 可变视图 + +```python +# O(1) - view of bytearray (mutable) +ba = bytearray(b"hello") +mv = memoryview(ba) + +# Can modify +mv[0] = 72 # O(1) - 'H' +print(ba) # bytearray(b'Hello') +``` + +### 内存共享 + +```python +# O(1) - modifications visible in original +ba = bytearray(b"test") +mv = memoryview(ba) + +# Modify through view +mv[0] = 84 # 'T' + +# Changes visible in original +print(ba) # bytearray(b'Test') + +# Changes also visible in view +print(mv[0]) # 84 +``` + +## 转换操作 + +```python +# O(n) - convert memoryview to bytes +data = b"hello" +mv = memoryview(data) + +# Convert to bytes +b = bytes(mv) # O(5) - creates copy +# b'hello' + +# Convert to list +lst = list(mv) # O(5) +# [104, 101, 108, 108, 111] +``` + +## 限制 + +```python +# O(1) - fast, but limited flexibility +mv = memoryview(b"hello") + +# Can't concatenate directly +# mv + mv # TypeError + +# Must convert to bytes first +result = bytes(mv) + bytes(mv) # O(2n) + +# Can't append +# mv.append(33) # AttributeError +``` + +## 最佳实践 + +✅ **应该**: + +- 使用 memoryview 进行零拷贝访问 +- 创建 memoryview 以便高效地传给函数 +- 使用切片高效获取子范围 +- 仅在必要时转换为 bytes + +❌ **避免**: + +- 为单次访问使用 memoryview(开销不值得) +- 假设 memoryview 像 list 一样工作(API 不同) +- 尝试修改不可变缓冲区(bytes) +- 为很小的数据创建 memoryview + +## 相关函数 + +- **[bytes()](bytes_func.md)** - 不可变字节 +- **[bytearray()](bytearray_func.md)** - 可变字节 +- **[array](https://docs.python.org/3/library/array.html)** - 类型化数组模块 + +## 版本说明 + +- **Python 2.x**:memoryview() 可用(2.7 版本加入) +- **Python 3.x**:改进的 memoryview,支持切片 +- **所有版本**:类字节对象的零拷贝视图 From a0b220da24f76197eb9207fa3c5b187fd47fff0f Mon Sep 17 00:00:00 2001 From: shaozk <913667678@qq.com> Date: Tue, 25 Aug 2026 17:07:19 +0800 Subject: [PATCH 2/2] Add: Chinese translations for README, CONTRIBUTING and TRANSLATING docs Co-Authored-By: opencode-agent[bot] --- CONTRIBUTING.md | 2 + CONTRIBUTING.zh-CN.md | 223 ++++++++++++++++++++++++++++ README.md | 2 + README.zh-CN.md | 332 ++++++++++++++++++++++++++++++++++++++++++ TRANSLATING.md | 2 + TRANSLATING.zh-CN.md | 242 ++++++++++++++++++++++++++++++ 6 files changed, 803 insertions(+) create mode 100644 CONTRIBUTING.zh-CN.md create mode 100644 README.zh-CN.md create mode 100644 TRANSLATING.zh-CN.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bff60a5..404ad33 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,5 @@ +**English** | [简体中文](CONTRIBUTING.zh-CN.md) + # Contributing to Python Big-O: Time & Space Complexity Thank you for interest in contributing! This guide will help you get started. diff --git a/CONTRIBUTING.zh-CN.md b/CONTRIBUTING.zh-CN.md new file mode 100644 index 0000000..340b524 --- /dev/null +++ b/CONTRIBUTING.zh-CN.md @@ -0,0 +1,223 @@ +[English](CONTRIBUTING.md) | **简体中文** + +# 参与 Python Big-O:时间与空间复杂度 + +感谢你对本项目的关注与贡献!本指南将帮助你快速上手。 + +## 如何参与贡献 + +### 报告错误 + +发现复杂度分析有误?请提交 issue,并附上: +- 受影响的操作或模块 +- 文档描述与正确内容之间的差异 +- 来源或证据(Python 文档、实现、基准测试结果) + +### 添加文档 + +帮助我们扩展以下内容的覆盖范围: +- 更多标准库模块(`itertools`、`functools`、`json` 等) +- 更多内置函数 +- 实现特定的细节 +- 版本特定的行为 + +### 改进现有内容 + +- 澄清解释 +- 添加更多示例 +- 修复拼写或格式错误 +- 添加性能提示 + +### 翻译文档 + +通过翻译页面、修正现有翻译或添加新的语言来帮助其他语言的读者。请参阅下方的[国际化与本地化](#国际化与本地化)以及 [TRANSLATING.md](TRANSLATING.md) 中的完整指南。 + +## 流程 + +1. **Fork** 仓库 +2. **创建分支**:`git checkout -b feature/what-you-add` +3. **修改代码**,遵循下方指南 +4. **本地测试**:`mkdocs serve` +5. **提交 PR**,附上清晰描述 + +## 文档风格指南 + +### 文件结构 + +``` +docs/ +├── section/ +│ ├── index.md # Overview +│ └── item.md # Details +``` + +### 复杂度表格格式 + +```markdown +| Operation | Time | Space | Notes | +|-----------|------|-------|-------| +| `method()` | O(n) | O(1) | Brief description | +``` + +### 代码示例 + +```python +# Clear, runnable examples +def example(): + lst = [1, 2, 3] + lst.append(4) # O(1) +``` + +### 提示块 + +用于重要提示: + +```markdown +!!! warning "Warning Title" + Warning content + +!!! tip "Tip Title" + Tip content + +!!! note "Note Title" + Note content +``` + +## 内容指南 + +### 复杂度标准 + +- 始终包含时间复杂度 +- 在相关时包含空间复杂度 +- 注明均摊与最坏情况 +- 标注 Python 版本差异 + +### 准确性要求 + +- 以官方 Python 文档为来源 +- 尽可能用 CPython 实现验证 +- 用实际基准测试验证结论 +- 对不显而易见的复杂度引用来源 + +### 示例 + +- 展示真实用例 +- 在有用时与替代方案对比 +- 解释为何某些方案更受青睐 +- 同时包含好的和坏的模式 + +## 国际化与本地化 + +英文是唯一权威来源。翻译文件位于镜像英文目录的语言子目录中,并在区域前缀下提供访问: + +``` +docs/builtins/list.md -> https://pythoncomplexity.com/builtins/list/ +docs/fi/builtins/list.md -> https://pythoncomplexity.com/fi/builtins/list/ +``` + +| 区域 | 语言 | 状态 | +|--------|----------|----------------------------| +| `en` | English | 完整(唯一权威来源) | +| `fi` | Suomi | 试点 - 13 页 | +| `zh` | 简体中文 | 试点 - 14 页 | + +没有翻译的页面会自动回退到英文,因此部分翻译始终可以安全合并。你无需在贡献前翻译整个章节。这些回退页面会以读者语言显示一条简短提示,说明该页面尚未翻译,因此本地化 URL 下的英文内容不会被视为 bug。 + +### 基本原则 + +- **翻译正文、标题、提示块标题和备注列。** 其余内容保持英文原文。 +- **切勿修改代码块。** 围栏内的标识符、注释和输出必须与英文源逐字节一致。 +- **切勿更改复杂度记号。** `O(1)`、`O(n log n)` 等表示法是语言无关的。 +- **保持表格结构。** 行数和列数必须与英文页面一致。 +- **使用词汇表。** 页面之间的一致性比任何单个词的选择都重要。每个语言在 [TRANSLATING.md](TRANSLATING.md) 中都有一个词汇表;确定新术语时请扩展它。 + +### 检查 + +翻译会作为 `make check` 的一部分自动验证: + +```bash +uv run python scripts/validate_translations.py +``` + +它会验证每个翻译页面都有对应的英文页面、代码块和表格结构仍然匹配、页面未过期。每个翻译都记录其所依据英文文件的 SHA-256,因此当英文页面更改时,其翻译会被标记,直到有人更新它们。 + +### 添加语言 + +欢迎添加新的语言,包括部分翻译。具体步骤(插件配置、搜索词干分析器、第一个页面、验证器注册)详见 [TRANSLATING.md](TRANSLATING.md)。 + +## 本地构建 + +```bash +# Install uv (if not already installed) +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Install dependencies +uv sync + +# Serve documentation +make serve + +# Visit http://localhost:8000 +# Translated pages live under a locale prefix, e.g. http://localhost:8000/fi/ +``` + +## 提交信息 + +使用清晰、描述性的信息: + +``` +Add: Complexity analysis for collections.deque + +Fix: Incorrect complexity for string.replace() + +Update: Python 3.12 performance notes + +Docs: Improve list.insert() explanation +``` + +## PR 描述模板 + +```markdown +## What This Changes + +Brief description of changes. + +## Why + +Explain the motivation. + +## Type of Change + +- [ ] New content +- [ ] Bug fix +- [ ] Documentation improvement +- [ ] Structure/organization + +## Related Issues + +Closes #(issue number) if applicable +``` + +## 评审流程 + +- 合并前至少需要一次评审 +- 用来源验证准确性 +- 检查与风格指南的一致性 +- 测试本地构建是否正常 + +## 有问题? + +提交 issue 提出你的问题。我们乐于提供帮助! + +## 许可证 + +参与贡献即表示你同意你的工作以 MIT 许可证授权(与项目相同)。 + +## 行为准则 + +- 保持尊重与包容 +- 提供建设性反馈 +- 相信他人善意 +- 向维护者报告违规行为 + +感谢你帮助让 Python 复杂度文档变得更好! diff --git a/README.md b/README.md index cd0a0fc..5f07d34 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +**English** | [简体中文](README.zh-CN.md) + # Python Big-O: Time & Space Complexity [![Lint / Format](https://img.shields.io/github/actions/workflow/status/heikkitoivonen/python-time-space-complexity/deploy.yml?label=lint%20%2F%20format)](https://github.com/heikkitoivonen/python-time-space-complexity/actions/workflows/deploy.yml) diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..9e4a5dc --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,332 @@ +[English](README.md) | **简体中文** + +# Python Big-O:时间复杂度与空间复杂度 + +[![Lint / Format](https://img.shields.io/github/actions/workflow/status/heikkitoivonen/python-time-space-complexity/deploy.yml?label=lint%20%2F%20format)](https://github.com/heikkitoivonen/python-time-space-complexity/actions/workflows/deploy.yml) +[![Type Check](https://img.shields.io/github/actions/workflow/status/heikkitoivonen/python-time-space-complexity/deploy.yml?label=type%20check)](https://github.com/heikkitoivonen/python-time-space-complexity/actions/workflows/deploy.yml) +[![Python](https://img.shields.io/badge/python-3.10%20to%203.14-blue)](https://www.python.org/) +[![License](https://img.shields.io/github/license/heikkitoivonen/python-time-space-complexity)](LICENSE.txt) +[![Docs](https://img.shields.io/badge/docs-pythoncomplexity.com-brightgreen)](https://pythoncomplexity.com) + +一个全面记录 Python 内置函数和标准库操作在不同 Python 版本和实现中的时间与空间复杂度的资源。 + +## 概述 + +本项目提供以下内容的详细算法复杂度文档: +- **Python 内置类型**:`list`、`dict`、`set`、`str` 等 +- **标准库模块**:`collections`、`heapq`、`bisect`、`annotationlib`、`compression.zstd` 等 +- **Python 版本**:3.10–3.14(包含新的 3.14 特性) +- **替代实现**:CPython、PyPy、Jython、IronPython + +## 特性 + +- 📊 覆盖所有主要内置类型和操作的全面复杂度表 +- 🔄 版本特定的行为和优化变更 +- 🚀 实现特定的说明(CPython vs PyPy vs 其他) +- 🛠️ 用于估算你自己代码复杂度的 CLI 工具 +- 🔍 交互式搜索和过滤 +- 📱 移动端友好的响应式设计 + +## 网站 + +访问文档:[pythoncomplexity.com](https://pythoncomplexity.com) + +--- + +## 快速开始 + +### 环境要求 +- Python 3.10+(推荐 3.14) +- [uv](https://github.com/astral-sh/uv) - 快速的 Python 包管理器 +- Git + +### 安装 + +```bash +# Install uv (one-time) +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Clone and set up +git clone https://github.com/heikkitoivonen/python-time-space-complexity.git +cd python-time-space-complexity + +# Install dependencies +uv sync + +# Start development server +make serve +# Open http://localhost:8000 +``` + +--- + +## 开发命令 + +### 使用 Make(推荐) + +```bash +make help # See all available commands +make dev # Install dev environment +make serve # Serve documentation locally +make build # Build static site +make check # Run lint + types + tests +make lint # Run linter +make format # Format code +make types # Run type checker +make test # Run tests +make clean # Clean build artifacts +make update # Update dependencies +``` + +### 直接使用 uv + +```bash +uv sync # Sync dependencies +uv run mkdocs serve # Run command in venv +uv add package-name # Add dependency +uv add --dev pytest-plugin # Add dev dependency +uv lock --upgrade # Update dependencies +``` + +### 复杂度估算 CLI + +测量你自己 Python 函数的 Big-O 复杂度: + +```bash +# Usage: python scripts/estimate_complexity.py +python scripts/estimate_complexity.py my_script my_function +``` + +示例输出: +```text +Input Size (n) | Avg Time (s) +----------------------------------- +100 | 0.000003 +500 | 0.000012 +... +Estimated Complexity: O(n) (Linear) +``` + +--- + +## 项目结构 + +``` +├── docs/ # MkDocs documentation source +│ ├── index.md # Landing page +│ ├── builtins/ # Built-in types (list, dict, set, tuple, str) +│ ├── stdlib/ # Standard library modules +│ ├── implementations/ # CPython, PyPy, Jython, IronPython +│ └── versions/ # Python version guides (3.10–3.14) +├── data/ # JSON data files +├── scripts/ # Utility scripts +├── tests/ # Test files +├── .github/workflows/ # GitHub Actions CI/CD +│ └── deploy.yml +├── pyproject.toml # Project metadata and dependencies +├── mkdocs.yml # MkDocs configuration +└── Makefile # Development commands +``` + +--- + +## 开发流程 + +### 1. 创建特性分支 +```bash +git checkout -b feature/add-numpy-complexity +``` + +### 2. 修改并在本地测试 +```bash +vim docs/new-module.md +make serve # View at http://localhost:8000 +``` + +### 3. 运行质量检查 +```bash +make lint # Check code quality +make format # Auto-format code +make types # Type checking +make test # Run tests +make check # All checks (required before commit) +``` + +### 4. 提交并推送 +```bash +git add . +git commit -m "Add: NumPy array complexity documentation" +git push origin feature/add-numpy-complexity +``` + +### 添加文档 +1. 在 `docs/` 中创建 markdown 文件 +2. 在 `mkdocs.yml` 导航中添加链接 +3. 使用 `make serve` 本地测试 +4. 提交前运行 `make check` + +--- + +## 代码质量标准 + +### 代码检查与格式化 +- **ruff** 用于代码检查(行长度:100 字符,Python 3.10+ 兼容) +- **pyright** 用于静态类型检查 +- **pytest** 用于测试 + +### 提交信息 +``` +Type: Brief description + +Types: Add, Fix, Update, Refactor, Docs, Test, Chore +Example: Add: List complexity documentation +``` + +--- + +## 快速参考 - Python 复杂度速查表 + +### 列表 +| 操作 | 时间 | 备注 | +|-----------|------|-------| +| `append()` | O(1)* | 均摊 | +| `insert(i)` | O(n) | 移动元素 | +| `pop()` | O(1) | 最后一个元素 | +| `pop(0)` | O(n) | 第一个元素 | +| `in` | O(n) | 线性查找 | +| `sort()` | O(n log n) | Timsort/Powersort | + +**小贴士:** 使用 `deque.appendleft()` 进行 O(1) 前插,而不是 `list.insert(0)`。 + +### 字典与集合 +| 操作 | 时间 | +|-----------|------| +| `d[key]` | 平均 O(1) | +| `d[key] = v` | 平均 O(1) | +| `key in d` | 平均 O(1) | +| `set.add()` | 平均 O(1) | +| `x in set` | 平均 O(1) | + +**小贴士:** 使用 set 进行快速的成员检测,而不是 list。 + +### 字符串 +| 操作 | 时间 | +|-----------|------| +| `len()` | O(1) | +| `s[i]` | O(1) | +| `in`(子串) | 平均 O(n) | +| `split()` / `join()` | O(n) | + +**小贴士:** 在循环中使用 `"".join(list)`,不要使用 `+=`。 + +### 标准库 + +| 模块 | 操作 | 时间 | +|--------|-----------|------| +| **deque** | `append()` / `appendleft()` | O(1) | +| **deque** | `pop()` / `popleft()` | O(1) | +| **heapq** | `heapify()` | O(n) | +| **heapq** | `heappush()` / `heappop()` | O(log n) | +| **bisect** | `bisect_left/right()` | O(log n) | + +### 常见模式 + +```python +# ❌ Bad: O(n) membership check +if item in list: pass + +# ✅ Good: O(1) membership check +if item in set: pass + +# ❌ Bad: O(n²) string concatenation +result = "" +for item in items: + result += item + +# ✅ Good: O(n) string building +result = "".join(items) + +# ❌ Bad: O(n) prepend +lst.insert(0, item) + +# ✅ Good: O(1) prepend +from collections import deque +dq = deque() +dq.appendleft(item) +``` + +### Python 版本性能 +``` +Python 3.10 ← Baseline +Python 3.11 ← +10-60% improvements (inline caching!) +Python 3.12 ← +5-10% improvements +Python 3.13 ← Similar (experimental free-threading) +Python 3.14 ← Better GC pauses, new heapq max-heap +``` + +### 实现对比 +| 实现 | 使用场景 | 速度 | GIL | +|---|---|---|---| +| CPython | 默认,标准 | 好 | 有 | +| PyPy | CPU 密集型循环 | 优秀* | 无 | +| Jython | Java 集成 | 好 | 无 | +| IronPython | .NET 集成 | 好 | 无 | + +--- + +## 部署 + +### GitHub Pages 设置 +1. 推送到 GitHub +2. 前往 **Settings** → **Pages** +3. 选择 **Deploy from a branch** → **gh-pages** +4. GitHub Actions 会在推送时自动部署 + +### 自定义域名(可选) +1. 更新 `mkdocs.yml` 中的 `site_url` +2. 配置 DNS 指向 GitHub Pages +3. 在 GitHub Settings → Pages 中输入自定义域名 +4. 启用 HTTPS + +--- + +## 故障排查 + +### 构建问题 +```bash +make clean && make build +uv run mkdocs serve --verbose +``` + +### 依赖问题 +```bash +rm -rf .venv/ && uv sync +``` + +### GitHub Pages 未更新 +1. 检查 GitHub Actions 选项卡中的错误 +2. 确认 gh-pages 分支存在 +3. 等待约 1-2 分钟完成部署 + +--- + +## 来源与参考 + +- [Python 官方文档](https://docs.python.org/3/) +- [TimeComplexity Wiki](https://wiki.python.org/moin/TimeComplexity) +- [Python 增强提案(PEPs)](https://www.python.org/dev/peps/) +- [uv 文档](https://docs.astral.sh/uv/) +- [MkDocs 文档](https://www.mkdocs.org/) +- [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) + +## 参与贡献 + +欢迎贡献!请参阅 [CONTRIBUTING.md](CONTRIBUTING.md) 了解贡献指南。 + +## 许可证 + +MIT 许可证 - 详见 [LICENSE.txt](LICENSE.txt) + +## 免责声明 + +虽然我们力求准确,但复杂度信息可能因具体实现和版本而异。对于性能关键代码,请务必参考官方文档和基准测试进行验证。 diff --git a/TRANSLATING.md b/TRANSLATING.md index c482ce1..f326e63 100644 --- a/TRANSLATING.md +++ b/TRANSLATING.md @@ -1,3 +1,5 @@ +**English** | [简体中文](TRANSLATING.zh-CN.md) + # Translating This project serves localized documentation from language subdirectories under diff --git a/TRANSLATING.zh-CN.md b/TRANSLATING.zh-CN.md new file mode 100644 index 0000000..ac430aa --- /dev/null +++ b/TRANSLATING.zh-CN.md @@ -0,0 +1,242 @@ +[English](TRANSLATING.md) | **简体中文** + +# 翻译指南 + +本项目从 `docs/` 下的语言子目录提供本地化文档。英文是默认语言,位于 `docs/` 根目录;每个翻译位于 `docs//`,镜像英文目录树。 + +``` +docs/builtins/list.md -> https://pythoncomplexity.com/builtins/list/ +docs/fi/builtins/list.md -> https://pythoncomplexity.com/fi/builtins/list/ +``` + +没有翻译的页面会自动回退到英文,因此部分翻译始终可以安全发布。 + +## 状态 + +| 区域 | 名称 | 阶段 | +|--------|----------|----------------------------| +| `en` | English | 完整(唯一权威来源) | +| `fi` | Suomi | 试点 - 13 页 | +| `zh` | 简体中文 | 试点 - 14 页 | + +## 工作流程 + +1. 将英文页面复制到 `docs//<相同路径>`。 +2. 添加翻译 front matter(见下文)。 +3. 翻译正文、标题、提示块标题和表格的 **备注** 列。 +4. 保持代码块、标识符和复杂度表达式不变。 +5. 运行 `make check` —— `scripts/validate_translations.py` 强制校验结构规则,并标记过期的翻译。 + +## Front matter + +每个翻译页面都带有其所依据英文源的 SHA-256: + +```yaml +--- +source_sha: 3f8a1c... +translated: machine +--- +``` + +- `source_sha` — 翻译时英文文件字节的 SHA-256。当英文页面发生变化时,哈希不再匹配,验证器会将翻译标记为过期。 +- `translated` — `machine`(未经审核)或 `reviewed`(由流利母语者检查过)。这是给维护者的簿记信息,不会显示在网站上;验证器只检查其是否为这两个值之一。 + +在对照更新后的英文源重新检查页面后,重新授权(消除过期标记): + +```bash +uv run python scripts/validate_translations.py --update-hashes fi +``` + +## 不要翻译的内容 + +| 原样保留 | 原因 | +|------------------------------------------|---------------------------------------------| +| 围栏代码块 | 代码就是代码 | +| `O(1)`, `O(n log n)`, `Θ`, `Ω` | 记法是语言无关的 | +| 方法和类型名(`append`, `dict`) | 它们是 Python 标识符,不是单词 | +| 模块名(`collections`, `heapq`) | 同上 | +| URL 和链接目标 | 路径是相对于语言区域解析的 | +| 表格结构(行数和列数) | 验证器会将其与英文对比 | + +标题**会被**翻译,这会改变锚点 slug。因此跨页面链接必须指向文件(`builtins/list.md`),绝不能指向其他页面中手写的锚点。 + +## 芬兰语词汇表(`fi`) + +页面之间的一致性比任何单个词的选择都重要。修正此处任何读起来不对的地方,整个翻译就会随之受益。 + +### 核心术语 + +| English | Finnish | Notes | +|--------------------|-----------------------|---------------------------| +| time complexity | aikavaativuus | | +| space complexity | tilavaativuus | | +| Big-O notation | O-notaatio | also seen: iso-O-notaatio | +| amortized | tasoitettu | alternative: amortisoitu | +| worst case | pahin tapaus | | +| average case | keskimääräinen tapaus | | +| best case | paras tapaus | | +| operation | operaatio | | +| element / item | alkio | | +| index | indeksi | | +| lookup | haku | | +| insertion | lisäys | | +| deletion / removal | poisto | | +| traversal | läpikäynti | | +| iteration | iterointi | | +| slice | viipale | verb: viipalointi | +| in place | paikallaan | | +| overhead | lisäkustannus | | +| trade-off | kompromissi | | + +### 数据结构 + +| English | Finnish | Notes | +|----------------|------------------|-----------------------------------------| +| list | lista | | +| dictionary | sanakirja | the type is still written `dict` | +| set | joukko | | +| tuple | monikko | | +| string | merkkijono | | +| bytes | tavut | | +| array | taulukko | | +| hash table | hajautustaulu | | +| hash | tiiviste | verb: hajauttaa | +| hash collision | tiivistetörmäys | | +| linked list | linkitetty lista | | +| heap | keko | | +| binary heap | binäärikeko | | +| queue | jono | | +| deque | pakka | usually left as `deque` in running text | +| stack | pino | | +| tree | puu | | +| key / value | avain / arvo | | + +### 实现词汇 + +| English | Finnish | Notes | +|--------------------|----------------------|--------------------------------| +| contiguous | yhtenäinen | | +| reference counting | viittausten laskenta | | +| garbage collection | roskienkeruu | | +| memory allocation | muistinvaraus | | +| resizing | koon muuttaminen | | +| immutable | muuttumaton | | +| mutable | muuttuva | | +| interned | sisäistetty | of strings; often left English | +| built-in | sisäänrakennettu | | +| standard library | standardikirjasto | | +| implementation | toteutus | | +| benchmark | suorituskykymittaus | verb: mitata suorituskykyä | +| sorting | järjestäminen | not "lajittelu" in CS contexts | +| comparison | vertailu | | +| binary search | binäärihaku | | + +### 提示块标题 + +| English | Finnish | +|-----------|-----------| +| Note | Huomio | +| Warning | Varoitus | +| Tip | Vinkki | +| Example | Esimerkki | +| Important | Tärkeää | + +## 中文词汇表(`zh`) + +简体中文。复杂度表达式保持拉丁字母形式(`O(n log n)`),Python 标识符从不翻译。 + +### 核心术语 + +| English | Chinese | Notes | +|--------------------|-------------|----------------------------| +| time complexity | 时间复杂度 | | +| space complexity | 空间复杂度 | | +| Big-O notation | 大 O 表示法 | space around the Latin `O` | +| amortized | 均摊 | alternative: 摊还 | +| worst case | 最坏情况 | | +| average case | 平均情况 | | +| best case | 最好情况 | | +| operation | 操作 | | +| element / item | 元素 | | +| index | 索引 | | +| lookup | 查找 | | +| insertion | 插入 | | +| deletion / removal | 删除 / 移除 | | +| traversal | 遍历 | | +| iteration | 迭代 | | +| slice | 切片 | | +| in place | 原地 | | +| overhead | 开销 | | +| trade-off | 权衡 | | + +### 数据结构 + +| English | Chinese | Notes | +|----------------|----------|-----------------------------------------| +| list | 列表 | | +| dictionary | 字典 | the type is still written `dict` | +| set | 集合 | | +| tuple | 元组 | | +| string | 字符串 | | +| bytes | 字节 | | +| array | 数组 | | +| hash table | 哈希表 | also seen: 散列表 | +| hash | 哈希 | hash value: 哈希值 | +| hash collision | 哈希冲突 | | +| linked list | 链表 | | +| heap | 堆 | | +| binary heap | 二叉堆 | | +| queue | 队列 | | +| deque | 双端队列 | usually left as `deque` in running text | +| stack | 栈 | | +| tree | 树 | | +| key / value | 键 / 值 | | + +### 实现词汇 + +| English | Chinese | Notes | +|--------------------|----------|-----------------| +| contiguous | 连续 | | +| reference counting | 引用计数 | | +| garbage collection | 垃圾回收 | | +| memory allocation | 内存分配 | | +| resizing | 扩容 | shrinking: 缩容 | +| immutable | 不可变 | | +| mutable | 可变 | | +| interned | 驻留 | of strings | +| built-in | 内置 | | +| standard library | 标准库 | | +| implementation | 实现 | | +| benchmark | 基准测试 | | +| sorting | 排序 | | +| comparison | 比较 | | +| binary search | 二分查找 | | + +### 提示块标题 + +| English | Chinese | +|-----------|---------| +| Note | 注意 | +| Warning | 警告 | +| Tip | 提示 | +| Example | 示例 | +| Important | 重要 | + +### 搜索 + +中文没有词边界,因此搜索索引需要分词。Material 使用 `jieba` 实现这一点,这正是它作为项目依赖的原因。如果未安装,整个中文句子会变成一个搜索词元,搜索将基本失效。 + +## 添加新语言区域 + +1. 在 `mkdocs.yml` 中将该语言添加到 `i18n` 插件的 `languages` 列表,包括 `site_name`、`site_description` 和 `nav_translations`。 +2. 确认该语言有 lunr 词干分析器(`lunr..js`)以便搜索可用;存在时插件会自动接入。没有词边界的语言还需要分词器 - 请参阅上面的中文说明。 +3. 在 `docs/overrides/main.html` 的 `fallback_notices` 中添加该语言的字符串,并在同一文件中翻译公告栏。没有条目的语言区域只不显示提示。 +4. 创建 `docs//` 并首先翻译 `index.md`。 +5. 在 `scripts/validate_translations.py` 中将该语言添加到 `LOCALES`。 +6. 在上面的状态表和 `CONTRIBUTING.md` 的状态表中各添加一行。 + +## 未翻译页面的提示 + +没有翻译的页面会在本地化 URL 下以英文源提供。如果没有提示,这看起来像一个 bug:读者要求的是中文,得到的却是英文。 + +因此 `docs/overrides/main.html` 会在任何源语言与当前构建语言不同的页面顶部显示一条简短提示。它依据 `page.file.locale`,该值由 i18n 插件按文件设置,因此无需 front matter,也不会与实际内容失同步。已翻译页面和英文页面不显示任何内容。