“python functools” Kode Jawaban

python functools

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600
Handsome Herring

python functools

import functools
import time

@functools.lru_cache(maxsize=256)
def find_user(name):
    # imitating slow search
    time.sleep(1)
    user = {"id": 11, "name": "Diane"}
    return user

find_user("Diane")
# kinda slow

find_user("Diane")
# blazingly fast
Puzzled Puffin

Jawaban yang mirip dengan “python functools”

Pertanyaan yang mirip dengan “python functools”

Lebih banyak jawaban terkait untuk “python functools” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya