lru_cache vs cache

在Python中,lru_cachecache都是functools模块提供的装饰器,用于缓存函数的结果,但它们的功能和使用场景略有不同。

functools.lru_cache

lru_cache表示"最近最少使用"缓存。它是一个装饰器,用于缓存函数调用的结果。当缓存达到设定的最大容量时,会丢弃最近最少使用的缓存项。这对于一些计算量大且频繁调用的函数非常有用。

  • 语法@functools.lru_cache(maxsize=128, typed=False)

  • 参数

    • maxsize:指定缓存的最大容量。如果设置为None,缓存大小不受限制。
    • typed:如果设置为True,则会将不同类型的参数视为不同的调用(例如,f(3)f(3.0)会分别缓存)。
  • 示例

    python 复制代码
    from functools import lru_cache
    
    @lru_cache(maxsize=100)
    def expensive_function(x):
        # 模拟耗时计算
        return x * x

functools.cache

cache是一个更简单版本的缓存装饰器。它是lru_cache(maxsize=None)的别名,表示提供一个不受限制的缓存。这在需要缓存所有函数调用结果且不考虑缓存淘汰策略时非常有用。

  • 语法@functools.cache

  • 示例

    python 复制代码
    from functools import cache
    
    @cache
    def expensive_function(x):
        # 模拟耗时计算
        return x * x

关键区别

  1. 淘汰策略

    • lru_cache:使用最近最少使用的淘汰策略。当缓存达到最大容量时,丢弃最近最少使用的项。
    • cache:没有淘汰策略,缓存项数量不受限制。
  2. 定制化

    • lru_cache:允许设置缓存大小(maxsize)和类型敏感性(typed)。
    • cache:没有定制化选项,相当于lru_cache(maxsize=None)

使用场景

  • lru_cache:适用于需要限制内存使用且对使用顺序敏感的缓存场景。
  • cache:适用于需要简单且不受限制的缓存场景。

leetcode

题目:https://leetcode.cn/problems/special-permutations/description/

我讲下述代码提交后,发现 @lru_cache(maxsize=None) 时间超时, @cache 能够成功提交;

建议大家leetcode 刷题的时候,还是使用 @cache 好一点,简单无脑还快一点;

python 复制代码
class Solution:
    def specialPerm(self, nums: List[int]) -> int:

        @cache
        # @lru_cache(maxsize=None)
        def dfs(rear:int, lefts: tuple):
            if len(lefts) == 0:
                return 1

            res = 0
            for item in lefts:
                if item % rear == 0 or rear % item == 0:
                    res += dfs(item, tuple(set(lefts) - set([item])))
            
            return res % (1e9 + 7)
            

        res = 0
        for item in nums:
            res += dfs(
                    item, 
                    tuple(set(nums) - set([item]))
                )

        return int(res % (1e9 + 7))
相关推荐
wenyq72 分钟前
LeetCode 438. Find All Anagrams in a String
算法·leetcode
后台模板学习3 分钟前
Rust vs Python 在用户认证模块中的实现:底层
开发语言·python·rust
LB21123 分钟前
力扣102 198 70 55
数据结构·算法·leetcode
AIGC大时代5 分钟前
LangGraph 生产级笔记:Checkpointer + interrupt(),把人审做成可恢复状态机
python·agent·状态机·langgraph·hitl
凤城老人7 分钟前
基于 Flask 的企业级 CMS 架构设计与实现
后端·python·flask
所念皆星海91110 分钟前
Python学习---DAY10函数
开发语言·python·学习
刘天远10 分钟前
企业 Agent 需求怎么写:数据结构、流程图与 Python 校验
数据结构·人工智能·python·流程图
Java后端的Ai之路14 分钟前
23、Python - 策略模式
linux·python·策略模式
旖旎夜光19 分钟前
【LangChain实战】LangChain 学习笔记(一):从定义大模型到工具调用
人工智能·笔记·python·学习·langchain