Add multilingual exercise code (#1959)

Replace the exercise pages' Python-only snippets with source-backed implementations for the 13 visible programming languages, and localize reader-facing comments by site language. Zig remains out of scope.

Approval bypass: repository protection requires one approval but does not enforce it for administrators. All 68 completed checks succeeded; four non-required Java jobs remained queued on the existing ubuntu-20.04 workflow, with no failed checks.
This commit is contained in:
Yudong Jin
2026-08-18 04:57:57 +08:00
committed by GitHub
parent bf86c39b6c
commit 28c1e74c1d
180 changed files with 5795 additions and 230 deletions
@@ -7,33 +7,23 @@
下面两段代码都计算 $1 + 2 + \dots + n$(设 $n \ge 1$)。请把 `n` 设为 4
按照程序实际执行的顺序回答问题,然后比较两种写法的效率。
```python
def sum_iter(n):
s = 0
for i in range(1, n + 1):
s += i
return s
def sum_recur(n):
if n == 1:
return 1
return n + sum_recur(n - 1)
```src
[file]{complexity_exercises}-[class]{}-[func]{sum_iter}
```
<!-- numbered-subquestions -->
1. 执行 `sum_iter(4)` 时,每轮循环结束后,变量 `s` 的值分别是多少?
2. 执行 `sum_recur(4)` 时,会依次调用哪些函数?从最深的一层开始返回时,结果怎样得到?
1. 输入 `n = 4` 执行迭代函数时,每轮循环结束后,累加变量 `res` 的值分别是多少?
2. 输入 `n = 4` 执行递归函数时,参数 `n` 会依次取哪些值?从最深的一层开始返回时,结果怎样得到?
3. 两种写法的时间复杂度和空间复杂度分别是多少?结合第 1、2 问的执行过程说明理由。
??? success "参考答案"
1. 循环变量 `i` 依次为 `1、2、3、4`,每轮结束后,`s` 依次变为
`1、3、6、10`,所以 `sum_iter(4)` 返回 10。
1. 循环变量 `i` 依次为 `1、2、3、4`,每轮结束后,`res` 依次变为
`1、3、6、10`,所以迭代函数返回 10。
2. 函数依次调用
`sum_recur(4) → sum_recur(3) → sum_recur(2) → sum_recur(1)`
`sum_recur(1)` 返回 1,随后各层依次得到 `2 + 1 = 3``3 + 3 = 6``4 + 6 = 10`
2. 参数 `n` 依次为 `4 → 3 → 2 → 1`
最深一层返回 1,随后各层依次得到 `2 + 1 = 3``3 + 3 = 6``4 + 6 = 10`
在最深处,4 次函数调用都尚未结束。
3. 两段代码都进行与 $n$ 成正比的循环或调用,因此时间复杂度均为 $O(n)$ 。
@@ -47,21 +37,8 @@ def sum_recur(n):
以下三个代码片段的输入均为正整数 $n$ 。请按时间复杂度从低到高排序,并写出各自的复杂度。
```python
# 片段一
s = 0
for i in range(n):
s += i
# 片段二
s = 0
for i in range(n):
for j in range(i, n):
s += j
# 片段三
while n > 1:
n = n // 2
```src
[file]{complexity_exercises}-[class]{}-[func]{linear_loop}
```
??? success "参考答案"
+5 -11
View File
@@ -25,23 +25,17 @@
下面的递归函数用分治计算 $x^n$:
```python
def fast_pow(x, n):
if n == 0:
return 1
half = fast_pow(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
```src
[file]{fast_power}-[class]{}-[func]{fast_pow}
```
用它计算 `fast_pow(3, 5)`
`x = 3``n = 5`,用这个函数计算
<!-- numbered-subquestions -->
1. 递归调用时,参数 `n` 依次变成哪些值?
2. 从最深层开始返回时,各层依次返回什么值?
3. 为什么要先保存 `half`,而不是`fast_pow(x, n // 2)` 写两遍
3. 为什么要先把递归结果保存 `half`,而不是在乘法两边各调用一次相同的子问题
??? success "参考答案"
@@ -50,7 +44,7 @@ def fast_pow(x, n):
2. `n = 0` 时返回 1`n = 1` 时返回 $1×1×3=3$
`n = 2` 时返回 $3×3=9$`n = 5` 时返回 $9×9×3=243$。
3. 如果`fast_pow(x, n // 2)` 在乘法两边各写一次,两次递归会计算完全相同的子问题
3. 如果在乘法两边各调用一次相同的子问题,两次递归会进行完全相同的计算
先把结果保存为 `half`,每层就只递归一次,递归深度约为 $\log n$;
调用两次会造成大量重复计算。