Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools cache() Function



The Pythoncache() function specifies the application performance by storing the results determined by the program. Similarly, caching involves storing values computed during function calls for future reuse, this is known as memorization.

We can perform repetitive operations on large datasets. By using caching results, we can minimize the time and cost of executing the calculations repeatedly on the datasets.

Syntax

Following is the syntax for thecache() function.

@functools.cache()

Parameters

Thecache() decorator doesn't accept any parameters.

Return Value

This function returns the cached version of the decorated function.

Example 1

In the example below, the factorial function calculates the factorial of a number usingcache() function and results the cached value.

import functools@functools.cachedef fact(x):    if x == 0:        return 1    else:        return x * fact(x - 1)print(fact(29))  print(fact(6))

Output

The result is generated as follows −

8841761993739701954543616000000720

Example 2

We are now using the square function, which calculates the square of a number using thecache() function. If the function is called with the same argument again, it returns the cached result instead of recalculating the program.

import functools@functools.cachedef fact(x):    return x * fact(x-1) if x else 1print(fact(20))print(fact(20)) #stored result, no need for recalculation

Output

The code is generated as follows −

24329020081766400002432902008176640000

Example 3

Here, we are finding the fibonacci function, which calculates the Fibonacci number for a given input using thecache() function.

import functools@functools.cachedef fib(x):    if x <= 1:        return x    return fib(x - 1) + fib(x - 2)print(fib(20))  print(fib(10))

Output

The output is obtained as follows −

676555
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp