当前位置:首页>python>Python 函数专项练习:6 道编程题从入门到精通

Python 函数专项练习:6 道编程题从入门到精通

  • 2026-06-30 11:34:51
Python 函数专项练习:6 道编程题从入门到精通

配套专栏:Python 全栈修炼之路 第 07 篇《函数 —— 代码复用的基石》

难度分布:⭐ → ⭐⭐ → ⭐⭐ → ⭐⭐⭐ → ⭐⭐⭐ → ⭐⭐⭐⭐

核心覆盖:*args/**kwargs、闭包、装饰器、递归、lru_cache、高阶函数、LEGB 作用域、延迟绑定


题目一:通用函数调用器 ⭐

📌 题目描述

编写函数 call_function(func, args=None, kwargs=None),实现一个通用的函数调用器:

def add(a, b, c=0):    return a + b + c# 位置参数调用call_function(add, args=[12])           # 3call_function(add, args=[123])        # 6# 关键字参数调用call_function(add, kwargs={"a"1"b"2})  # 3# 混合调用call_function(add, args=[1], kwargs={"b"2"c"10})  # 13

💡 编程思路

这道题考察 *args 和 **kwargs 的解包与转发

  1. 函数需要接收一个可调用对象 func,以及可选的位置参数列表 args 和关键字参数字典 kwargs
  2. 使用 * 解包位置参数列表,** 解包关键字参数字典。
  3. 通过 func(*args, **kwargs) 实现动态调用。

关键点None 的默认值处理 —— 当 args 或 kwargs 为 None 时,应替换为空列表/空字典。

🖥️ 参考代码

def call_function(func, args=None, kwargs=None):    """    通用函数调用器    参数:        func: 可调用对象        args: 位置参数列表        kwargs: 关键字参数字典    """    args = args or []    kwargs = kwargs or {}    return func(*args, **kwargs)def call_function_safe(func, args=None, kwargs=None):    """安全版本:捕获异常并返回友好错误信息"""    args = args or []    kwargs = kwargs or {}    try:        return func(*args, **kwargs)    except TypeError as e:        return f"调用失败: {e}"# 测试if __name__ == "__main__":    def add(a, b, c=0):        return a + b + c    def greet(name, greeting="你好"):        return f"{greeting}{name}!"    def var_args(*args, **kwargs):        return f"args={args}, kwargs={kwargs}"    # 位置参数    print(call_function(add, args=[12]))             # 3    print(call_function(add, args=[123]))          # 6    # 关键字参数    print(call_function(add, kwargs={"a"1"b"2})) # 3    print(call_function(greet, kwargs={"name""张三"}))  # 你好, 张三!    # 混合调用    print(call_function(add, args=[1], kwargs={"b"2"c"10}))  # 13    # 可变参数函数    print(call_function(var_args, args=[123], kwargs={"x"99}))    # args=(1, 2, 3), kwargs={'x': 99}    # 错误处理    print(call_function_safe(add, args=[1]))  # 缺少参数    print(call_function_safe(add, args=[1234]))  # 参数过多

🔗 关联知识点

知识点
说明
*args
 解包
将列表展开为位置参数
**kwargs
 解包
将字典展开为关键字参数
or []
 惯用法
None
 时替换为空列表
TypeError
 捕获
参数不匹配时的异常

题目二:闭包实现带历史记录的计算器 ⭐⭐

📌 题目描述

使用闭包实现一个带历史记录的计算器工厂 make_calculator(),每次调用返回独立的计算器实例:

calc1 = make_calculator()calc1.add(5)calc1.add(3)calc1.subtract(1)print(calc1.result())    # 7print(calc1.history())   # ['+5', '+3', '-1']calc2 = make_calculator()calc2.multiply(4)calc2.add(6)print(calc2.result())    # 4  (独立的实例)

💡 编程思路

这道题考察 闭包的状态保持能力

  1. make_calculator()
     内部维护 total 和 history 两个自由变量。
  2. 返回的内部函数通过 nonlocal 修改这些变量。
  3. 每次调用 make_calculator() 都会创建独立的闭包实例,互不干扰。

关键点:闭包通过 __closure__ 捕获外部变量,即使外部函数已返回,变量仍存活。

🖥️ 参考代码

def make_calculator(initial=0):    """    创建带历史记录的计算器闭包    返回: 包含 add/subtract/multiply/divide/result/history/clear 方法的对象    """    total = initial    history = []    def _update(value, symbol):        nonlocal total        total = value        history.append(f"{symbol}{value}")    def add(n):        _update(total + n, f"+{n}")        return total    def subtract(n):        _update(total - n, f"-{n}")        return total    def multiply(n):        _update(total * n, f"*{n}")        return total    def divide(n):        if n == 0:            raise ZeroDivisionError("除数不能为零")        _update(total / n, f"/{n}")        return total    def result():        return total    def get_history():        return history.copy()    def clear():        nonlocal total        total = initial        history.clear()    def undo():        """撤销上一步操作(重新计算历史)"""        nonlocal total        if not history:            return        history.pop()        total = initial        # 重新执行所有历史操作        for record in history:            op = record[0]            val = float(record[1:])            if op == '+':                total += val            elif op == '-':                total -= val            elif op == '*':                total *= val            elif op == '/':                total /= val    return type('Calculator', (), {        'add': add, 'subtract': subtract,        'multiply': multiply, 'divide': divide,        'result': result, 'history': get_history,        'clear': clear, 'undo': undo    })()# 测试if __name__ == "__main__":    calc1 = make_calculator(10)    calc1.add(5)       # 15    calc1.multiply(2)  # 30    calc1.subtract(3)  # 27    print(f"calc1 结果: {calc1.result()}")  # 27    print(f"calc1 历史: {calc1.history()}")  # ['+5', '*2', '-3']    # 撤销    calc1.undo()    print(f"撤销后: {calc1.result()}")  # 30    print(f"历史: {calc1.history()}")   # ['+5', '*2']    # 独立实例    calc2 = make_calculator()    calc2.add(100)    print(f"calc2 结果: {calc2.result()}")  # 100(独立)    # 验证闭包独立性    calc3 = make_calculator(0)    calc3.add(1)    calc3.add(1)    print(f"calc3: {calc3.result()}")  # 2    print(f"calc1: {calc1.result()}")  # 30(不受影响)    # 查看闭包内部    print(f"\n闭包变量: {calc1.add.__closure__}")

🔗 关联知识点

知识点
说明
闭包状态保持
外部函数返回后变量仍存活
nonlocal
修改嵌套作用域的变量
type()
 动态创建
返回包含多个方法的对象
独立实例
每次调用创建独立的自由变量副本

题目三:实现 retry 重试装饰器 ⭐⭐

📌 题目描述

编写一个带参数的装饰器 retry(max_attempts, delay, exceptions),在函数调用失败时自动重试:

import random@retry(max_attempts=3, delay=1, exceptions=(ValueError,))def unstable_api():    """模拟不稳定的 API 调用"""    if random.random() < 0.7:        raise ValueError("服务暂时不可用")    return "success"result = unstable_api()# 如果前两次失败、第三次成功,则返回 "success"# 如果三次都失败,则抛出最后一个异常

💡 编程思路

这道题考察 带参数装饰器的三层嵌套结构

  1. 最外层 retry(max_attempts, delay, exceptions) 接收装饰器参数。
  2. 中间层 decorator(func) 接收被装饰的函数。
  3. 最内层 wrapper(*args, **kwargs) 实现重试逻辑。

关键点

  • 使用 functools.wraps(func) 保留原函数元数据。
  • 使用 time.sleep(delay) 控制重试间隔。
  • 只捕获指定的异常类型,其他异常直接抛出。

🖥️ 参考代码

import functoolsimport timedef retry(max_attempts=3, delay=0, exceptions=(Exception,)):    """    重试装饰器    参数:        max_attempts: 最大尝试次数(含首次调用)        delay: 每次重试的间隔秒数        exceptions: 需要重试的异常类型元组    """    def decorator(func):        @functools.wraps(func)        def wrapper(*args, **kwargs):            last_exception = None            for attempt in range(1, max_attempts + 1):                try:                    return func(*args, **kwargs)                except exceptions as e:                    last_exception = e                    if attempt < max_attempts:                        wait = delay * attempt  # 递增等待                        print(f"  第 {attempt} 次失败: {e}{wait}s 后重试...")                        time.sleep(wait)                    else:                        print(f"  第 {attempt} 次仍失败,放弃重试")            raise last_exception        return wrapper    return decoratordef retry_with_backoff(max_attempts=3, base_delay=1, backoff_factor=2,                        exceptions=(Exception,), max_delay=60):    """    指数退避重试装饰器(进阶版)    每次等待时间: base_delay * backoff_factor^(attempt-1)    """    def decorator(func):        @functools.wraps(func)        def wrapper(*args, **kwargs):            last_exception = None            for attempt in range(1, max_attempts + 1):                try:                    return func(*args, **kwargs)                except exceptions as e:                    last_exception = e                    if attempt < max_attempts:                        wait = min(base_delay * (backoff_factor ** (attempt - 1)),                                  max_delay)                        print(f"  第 {attempt} 次失败: {e}{wait:.1f}s 后重试...")                        time.sleep(wait)            raise last_exception        return wrapper    return decorator# 测试if __name__ == "__main__":    import random    call_count = 0    @retry(max_attempts=3, delay=0.1, exceptions=(ValueError,))    def unstable_api():        """模拟不稳定的 API(第3次调用成功)"""        global call_count        call_count += 1        if call_count < 3:            raise ValueError("服务暂时不可用")        return "success"    result = unstable_api()    print(f"结果: {result}")  # success    print(f"总调用次数: {call_count}")  # 3    # 测试全部失败    call_count = 0    @retry(max_attempts=2, delay=0.1, exceptions=(ValueError,))    def always_fail():        global call_count        call_count += 1        raise ValueError("永远失败")    try:        always_fail()    except ValueError as e:        print(f"最终异常: {e}")        print(f"总调用次数: {call_count}")  # 2    # 测试异常类型过滤    @retry(max_attempts=3, delay=0.1, exceptions=(ValueError,))    def type_error_api():        raise TypeError("类型错误,不应被重试")    try:        type_error_api()    except TypeError as e:        print(f"非目标异常直接抛出: {e}")

🔗 关联知识点

知识点
说明
三层嵌套装饰器
参数层 → 装饰器层 → 包装器层
functools.wraps
保留原函数 __name____doc__
异常捕获过滤
只重试指定类型的异常
指数退避
逐步增加重试间隔,避免雪崩

题目四:手写 LRU 缓存装饰器 ⭐⭐⭐

📌 题目描述

不使用 functools.lru_cache,手写一个带大小限制的 LRU 缓存装饰器 lru_cache(maxsize=128)

@lru_cache(maxsize=3)def expensive_compute(n):    print(f"  计算 {n}...")    return n * nexpensive_compute(1)  # 计算 1...expensive_compute(2)  # 计算 2...expensive_compute(1)  # 命中缓存,不打印expensive_compute(3)  # 计算 3...expensive_compute(4)  # 计算 4...(此时缓存已满,淘汰最久未使用的 2)expensive_compute(2)  # 计算 2...(已被淘汰,需重新计算)

💡 编程思路

这道题直击第7篇的 lru_cache 底层原理

  1. 使用 OrderedDict 存储缓存(键为参数,值为结果),利用其 O(1) 的 move_to_end() 和 popitem(last=False)
  2. 每次缓存命中时,将键移到末尾(表示最近使用)。
  3. 缓存未命中时,计算结果并插入。如果超出 maxsize,弹出最久未使用的(头部)。
  4. 提供 cache_info() 和 cache_clear() 方法。

难点:装饰器需要给被装饰函数动态添加方法(cache_infocache_clear),使用 functools.update_wrapper + 直接赋值属性。

🖥️ 参考代码

import functoolsfrom collections import OrderedDictdef lru_cache(maxsize=128):    """    手写 LRU 缓存装饰器    参数:        maxsize: 最大缓存条目数,None 表示无限制    """    def decorator(func):        cache = OrderedDict()        hits = misses = 0        @functools.wraps(func)        def wrapper(*args):            nonlocal hits, misses            # 缓存命中            if args in cache:                hits += 1                cache.move_to_end(args)  # 移到末尾(最近使用)                return cache[args]            # 缓存未命中            misses += 1            result = func(*args)            cache[args] = result            # 淘汰最久未使用的            if maxsize is not None and len(cache) > maxsize:                cache.popitem(last=False)            return result        def cache_info():            """返回缓存统计信息"""            return {                "hits": hits,                "misses": misses,                "maxsize": maxsize,                "currsize"len(cache)            }        def cache_clear():            """清空缓存"""            nonlocal hits, misses            cache.clear()            hits = misses = 0        # 将方法绑定到 wrapper 上        wrapper.cache_info = cache_info        wrapper.cache_clear = cache_clear        return wrapper    return decorator# 测试if __name__ == "__main__":    compute_count = 0    @lru_cache(maxsize=3)    def expensive_compute(n):        global compute_count        compute_count += 1        print(f"  计算 expensive_compute({n})...")        return n * n    print("=== 基础测试 ===")    print(expensive_compute(1))  # 计算并缓存    print(expensive_compute(2))  # 计算并缓存    print(expensive_compute(3))  # 计算并缓存(缓存满)    print(expensive_compute(1))  # 命中缓存(1 移到末尾)    print(expensive_compute(4))  # 计算并缓存(淘汰 2,因为 2 最久未使用)    print(expensive_compute(2))  # 未命中,重新计算    print(f"总计算次数: {compute_count}")  # 5(1,2,3,4,2)    print(f"缓存信息: {expensive_compute.cache_info()}")    # 清空缓存    expensive_compute.cache_clear()    print(f"清空后: {expensive_compute.cache_info()}")    # 与 functools.lru_cache 对比    print("\n=== 与标准库对比 ===")    from functools import lru_cache as std_lru_cache    std_count = 0    @std_lru_cache(maxsize=3)    def std_compute(n):        global std_count        std_count += 1        return n * n    std_compute(1)    std_compute(2)    std_compute(3)    std_compute(1)  # 命中    std_compute(4)  # 淘汰 2    std_compute(2)  # 重新计算    print(f"标准库计算次数: {std_count}")  # 5    print(f"标准库缓存信息: {std_compute.cache_info()}")

🔗 关联知识点

知识点
说明
OrderedDict
有序字典,move_to_end() O(1)
popitem(last=False)
弹出头部(最久未使用)
nonlocal
在嵌套函数中修改外部变量
动态绑定方法
wrapper.cache_info = cache_info
functools.wraps
保留原函数元数据

题目五:函数管道(链式调用) ⭐⭐⭐

📌 题目描述

实现一个函数管道系统,支持将多个函数串联执行,前一个函数的输出作为后一个函数的输入:

# 方式一:使用 pipe 函数result = pipe(    [12345678910],    filter(lambda x: x % 2 == 0),     # [2, 4, 6, 8, 10]    map(lambda x: x ** 2),             # [4, 16, 36, 64, 100]    lambda x: sorted(x, reverse=True), # [100, 64, 36, 16, 4]    lambda x: sum(x)                   # 220)print(result)  # 220# 方式二:使用 | 运算符(重载)result = (    Pipeline([12345])    | filter(lambda x: x % 2 != 0)    | map(lambda x: x ** 2)    | list)print(result)  # [1, 9, 25]

💡 编程思路

这道题考察 高阶函数与 Python 运算符重载

  • 方式一(pipe 函数)
    :接收初始值和一系列函数,依次将值传入每个函数。使用 reduce 或简单的 for 循环实现。
  • 方式二(Pipeline 类)
    :通过重载 __or__ 运算符实现 | 语法。Pipeline 对象持有当前值,每次 | 返回新的 Pipeline 对象。

关键点map 和 filter 返回的是迭代器,在管道中需要自动处理迭代器到可迭代对象的转换。

🖥️ 参考代码

from functools import reducedef pipe(data, *functions):    """    函数管道:将数据依次通过一系列函数处理    参数:        data: 初始数据        *functions: 一系列处理函数    返回:        最终处理结果    """    return reduce(lambda val, func: func(val), functions, data)class Pipeline:    """支持 | 运算符的函数管道"""    def __init__(self, data):        self.data = data    def __or__(self, func):        """重载 | 运算符"""        result = func(self.data)        return Pipeline(result)    def __repr__(self):        return f"Pipeline({self.data!r})"    def collect(self):        """获取最终结果"""        return self.datadef compose(*functions):    """    函数组合:从右到左执行 (f ∘ g)(x) = f(g(x))    与 pipe 的区别:compose 返回一个新函数,而不是立即执行    """    def composed(x):        return reduce(lambda val, func: func(val), reversed(functions), x)    return composed# 测试if __name__ == "__main__":    # === pipe 函数测试 ===    print("=== pipe 函数 ===")    result1 = pipe(        [12345678910],        filter(lambda x: x % 2 == 0),        map(lambda x: x ** 2),        list,        sorted,        sum    )    print(f"偶数平方和: {result1}")  # 220    result2 = pipe(        "Hello World Python Programming",        str.split,        map(len),        list,        max    )    print(f"最长单词长度: {result2}")  # 11 (Programming)    result3 = pipe(        [31415926],        sorted,        lambda x: x[-3:],  # 取最大的三个        sum    )    print(f"最大的三个数之和: {result3}")  # 17    # === Pipeline 类测试 ===    print("\n=== Pipeline 类 ===")    result4 = (        Pipeline([12345678910])        | filter(lambda x: x % 3 == 0)        | map(lambda x: x ** 2)        | list    )    print(f"3的倍数的平方: {result4.collect()}")  # [9, 36, 81]    # === compose 函数组合测试 ===    print("\n=== compose 函数组合 ===")    # (f ∘ g ∘ h)(x) = f(g(h(x)))    transform = compose(        lambda x: x.upper(),           # 最后执行        lambda x: x.replace(' ''_'), # 中间执行        str.strip                      # 最先执行    )    print(transform("  hello world  "))  # "HELLO_WORLD"    # 数值处理管道    process = compose(        lambda nums: sum(nums) / len(nums),  # 求平均        lambda nums: nums[1:],                 # 去掉最小值        sorted    )    print(f"去掉最小值后的平均: {process([12345100])}")  # (2+3+4+5+100)/5 = 22.8

🔗 关联知识点

知识点
说明
reduce
累积执行一系列函数
__or__
 运算符重载
实现 `
高阶函数
函数作为参数传递和返回
compose
 函数组合
f(g(x))
 的数学概念
迭代器 vs 可迭代对象
map
/filter 返回迭代器

题目六:递归解决汉诺塔(含可视化) ⭐⭐⭐⭐

📌 题目描述

实现汉诺塔问题的递归解法,要求:

  1. 输出每一步的移动指令
  2. 统计最少移动次数
  3. 可视化每一步的盘子分布状态
  4. 支持自定义盘子数量
hanoi(n=3, source='A', target='C', auxiliary='B')输出:第 1 步: A → C  (移动盘子 1)第 2 步: A → B  (移动盘子 2)第 3 步: C → B  (移动盘子 1)第 4 步: A → C  (移动盘子 3)第 5 步: B → A  (移动盘子 1)第 6 步: B → C  (移动盘子 2)第 7 步: A → C  (移动盘子 1)总步数: 7 (2^3 - 1)

💡 编程思路

汉诺塔是递归思维的经典训练题:

递归策略

  1. 将上面 n-1 个盘子从 source 移到 auxiliary(借助 target)
  2. 将最大的盘子从 source 移到 target
  3. 将 n-1 个盘子从 auxiliary 移到 target(借助 source)

终止条件:n = 1 时,直接移动。

可视化:用三个列表表示三根柱子,每次移动后打印当前状态。

🖥️ 参考代码

def hanoi(n, source='A', target='C', auxiliary='B', verbose=True):    """    汉诺塔递归解法    参数:        n: 盘子数量        source: 起始柱        target: 目标柱        auxiliary: 辅助柱        verbose: 是否打印步骤    """    steps = []    def _move(n, src, tgt, aux):        if n == 1:            steps.append((src, tgt))            if verbose:                print(f"  移动盘子 1: {src} → {tgt}")        else:            _move(n - 1, src, aux, tgt)            steps.append((src, tgt))            if verbose:                print(f"  移动盘子 {n}{src} → {tgt}")            _move(n - 1, aux, tgt, src)    if verbose:        print(f"=== 汉诺塔 (n={n}) ===")    _move(n, source, target, auxiliary)    if verbose:        print(f"总步数: {len(steps)} (2^{n} - 1 = {2**n - 1})")    return stepsdef hanoi_visualize(n):    """可视化汉诺塔的每一步"""    # 初始化:所有盘子在 A 柱(大盘在下)    towers = {        'A'list(range(n, 0, -1)),        'B': [],        'C': []    }    def _print_towers():        max_height = n        for i in range(max_height, 0, -1):            row = ""            for pole in ['A''B''C']:                if i <= len(towers[pole]):                    disk = towers[pole][i - 1]                    row += f"  {'█' * disk:^{2 * n + 1}}"                else:                    row += f"  {'|':^{2 * n + 1}}"            print(row)        print("  " + "  ".join(f"{pole:^{2 * n + 1}}" for pole in ['A''B''C']))        print()    steps = hanoi(n, verbose=False)    print(f"=== 汉诺塔可视化 (n={n}) ===\n")    _print_towers()    for i, (src, tgt) in enumerate(steps, 1):        disk = towers[src].pop()        towers[tgt].append(disk)        print(f"第 {i} 步: {src} → {tgt}  (盘子 {disk})")        _print_towers()    print(f"完成!总步数: {len(steps)}")def hanoi_iterative(n):    """    汉诺塔的迭代解法(进阶)    规律:    - 奇数步:移动最小的盘子(按 A→C→B→A 循环方向)    - 偶数步:移动唯一合法的非最小盘子    """    if n == 0:        return []    towers = {        'A'list(range(n, 0, -1)),        'B': [],        'C': []    }    # 移动方向取决于 n 的奇偶性    poles = ['A''B''C']    if n % 2 == 0:        poles = ['A''C''B']  # 偶数时方向反转    steps = []    total = 2 ** n - 1    for move_num in range(1, total + 1):        if move_num % 2 == 1:            # 奇数步:移动最小盘子            # 找到最小盘子所在柱子            src = None            for p in poles:                if towers[p] and towers[p][-1] == 1:                    src = p                    break            # 按循环方向移动            src_idx = poles.index(src)            tgt = poles[(src_idx + 1) % 3]        else:            # 偶数步:移动唯一合法的非最小盘子            src = tgt = None            for p in poles:                for q in poles:                    if p != q and towers[p] and towers[q]:                        if towers[p][-1] < towers[q][-1]:                            src, tgt = p, q                            break                if src:                    break        disk = towers[src].pop()        towers[tgt].append(disk)        steps.append((src, tgt))    return steps# 测试if __name__ == "__main__":    # 基础递归    print("=== n = 3 ===")    steps = hanoi(3)    assert len(steps) == 7    assert steps == [('A''C'), ('A''B'), ('C''B'),                     ('A''C'), ('B''A'), ('B''C'), ('A''C')]    # 可视化    print("\n=== 可视化 n = 3 ===")    hanoi_visualize(3)    # 验证迭代版本与递归版本一致    for n in range(16):        recursive_steps = hanoi(n, verbose=False)        iterative_steps = hanoi_iterative(n)        assert len(recursive_steps) == len(iterative_steps) == 2**n - 1        print(f"n={n}: 递归 {len(recursive_steps)} 步, 迭代 {len(iterative_steps)} 步 ✓")    # 性能测试    import timeit    n = 20    t = timeit.timeit(lambda: hanoi(n, verbose=False), number=10)    print(f"\nn={n} 递归耗时: {t:.4f}s (共 {2**n - 1} 步)")

🔗 关联知识点

知识点
说明
递归分治
大问题分解为子问题
终止条件
n == 1
 时直接移动
递归深度
n 层汉诺塔递归深度为 n
迭代替代递归
奇偶步规律实现非递归解法
状态可视化
用列表模拟柱子状态

总结:知识点覆盖矩阵

题目
难度
核心考察点
通用函数调用器
*args
/**kwargs 解包与转发
闭包计算器
⭐⭐
闭包状态保持、nonlocal、独立实例
retry 重试装饰器
⭐⭐
三层嵌套装饰器、异常捕获、指数退避
手写 LRU 缓存
⭐⭐⭐
OrderedDict
、缓存淘汰策略、动态绑定方法
函数管道
⭐⭐⭐
高阶函数、reduce、运算符重载、compose
汉诺塔可视化
⭐⭐⭐⭐
递归分治、终止条件、迭代替代递归

建议:按顺序从第 1 题做到第 6 题。第 1-2 题巩固参数和闭包基础,第 3-4 题深入装饰器原理,第 5 题体会函数式编程思想,第 6 题是递归思维的终极训练。完成全部 6 题后,你对 Python 函数的理解将达到新的高度。


延伸阅读

  • LeetCode 509. 斐波那契数(递归 + 记忆化)
  • LeetCode 206. 反转链表(递归 vs 迭代)
  • LeetCode 394. 字符串解码(递归嵌套)
  • Python 官方文档 - functools

本文是《Python 全栈修炼之路》第 07 篇配套练习,欢迎点赞收藏!

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-07-03 12:17:59 HTTP/2.0 GET : https://f.mffb.com.cn/a/499677.html
  2. 运行时间 : 0.212544s [ 吞吐率:4.70req/s ] 内存消耗:4,808.55kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=e5105766729132ef9a9d45962aa241c2
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000793s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.000657s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.000527s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.008310s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000646s ]
  6. SELECT * FROM `set` [ RunTime:0.003333s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000603s ]
  8. SELECT * FROM `article` WHERE `id` = 499677 LIMIT 1 [ RunTime:0.002557s ]
  9. UPDATE `article` SET `lasttime` = 1783052279 WHERE `id` = 499677 [ RunTime:0.023097s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 66 LIMIT 1 [ RunTime:0.000976s ]
  11. SELECT * FROM `article` WHERE `id` < 499677 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.000470s ]
  12. SELECT * FROM `article` WHERE `id` > 499677 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.011724s ]
  13. SELECT * FROM `article` WHERE `id` < 499677 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.008155s ]
  14. SELECT * FROM `article` WHERE `id` < 499677 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.001427s ]
  15. SELECT * FROM `article` WHERE `id` < 499677 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.032948s ]
0.216641s