Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools lru_cache() Function



The Pythonlru_cache() function is a decorator that wraps a function with a callable object, which calls the function more efficiently during the input operations with the same arguments. This caches the result of the recent maxsize calls. LRU is an abbreviation called Least Recently Used.

This function has a default maximum size of 128, and it will specify the most number of recent calls to be cached.

Syntax

Following is the syntax for thelru_cache() function.

lru_cache(maxsize = 128, typed = False)

Parameters

The parameters for thelru_cache() function are listed below −

  • maxsize: This parameter specifies the cache size to store the most recent function. If the size is set to None, then the LRU feature will be disabled.
  • typed: Functional arguments of different types will be cached separately.

Return Value

This function returns the decorated function that wraps the original metadata.

Example 1

In the example below, we are finding the number of vowels in a given string using thelru_cache() function with the specified maximum size.

from functools import lru_cache @lru_cache(maxsize = 110) def count_vowels(x):     x = x.casefold()     return sum(x.count(vowel) for vowel in 'aeiou') print(count_vowels("Welcome to Turoialspoint"))

Output

The result is generated as follows −

10

Example 2

Now, we are calculating Fibonacci sequence numbers usinglru_cache(), where the sequence starts from 0 and 1, and each subsequent number is the sum of the previous numbers.

from functools import lru_cache@lru_cache(maxsize=100)def fib(x):    if x < 4:        return x    return fib(x-2) + fib(x-1)print(fib(20))

Output

The code is generated as follows −

10946

Example 3

In this example, we are using thelru_wraps() function to demonstrate the performance by caching results while calculating the sum of a numbers's digits in base 20.

from functools import lru_cache@lru_cache(maxsize=100)def sum(x):    if x == 0:        return 0    return x % 20 + sum(x // 20)print(sum(2398564))

Output

The output is obtained as follows −

61
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp