lru_cache vs cache

在Python中,lru_cache和cache都是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))
相关推荐
羲云网络2 小时前
GPT Image 2.6 接入指南:Flare、Sunburst 怎么选,编辑失败如何排查
人工智能·python·aigc·图像生成·acedatacloud
Navigator_Z3 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH4 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶5 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
橙橙笔记5 小时前
具身智能的学习 - 完成一个机械臂 第1节
python·学习·机械臂·具身智能
雪落漂泊5 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
小小张说故事5 小时前
Python 的 class 语句到底执行了什么?拆开 __prepare__、metaclass.__new__ 和那个被讲反的 __set_name__ 顺序
python
LabVIEW开发7 小时前
LabVIEW 连接板:28 个端子怎么排,优先级怎么定
java·算法·labview
天天被压力7 小时前
【A股分钟级高频数据完全手册 #07】北交所历史分钟K线接口:京市Pro版分时批量
java·人工智能·python