Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Caché LRU
Caché LRU
LRU Cache ConceptsHow an LRU Cache WorksImplementing an LRU CacheComplexity of an LRU CacheLRU Practice ProblemsLRU in the Real World
Debates

Guía de Caché LRU · 5/6

LRU Practice Problems

Por ahora, este capítulo solo está disponible en inglés.

These four problems extend the basic LRU cache in directions that come up in interviews and in real code. Try each one before reading the approach. The solutions use OrderedDict to keep the focus on the idea; you can swap in the hand-written linked list from the implementation chapter.

Problem 1: Count the misses

A program issues a sequence of page requests, and memory holds k pages managed by LRU. Return the number of misses (page faults). Then find the smallest k for which the number of misses is at most a given limit.

Approach: simulate the cache once per capacity. Because LRU is a stack algorithm, misses never increase when k grows, so the smallest suitable k can be found with binary search over 1..number of distinct pages.

from collections import OrderedDict

def lru_misses(requests, k):
    cache, misses = OrderedDict(), 0
    for page in requests:
        if page in cache:
            cache.move_to_end(page)
        else:
            misses += 1
            cache[page] = True
            if len(cache) > k:
                cache.popitem(last=False)
    return misses

def smallest_capacity(requests, limit):
    lo, hi = 1, max(1, len(set(requests)))
    while lo < hi:
        mid = (lo + hi) // 2
        if lru_misses(requests, mid) <= limit:
            hi = mid
        else:
            lo = mid + 1
    return lo

reqs = [1, 2, 3, 1, 4, 1, 2, 5, 1, 2, 3, 4]
print(lru_misses(reqs, 3))         # 8
print(smallest_capacity(reqs, 7))  # 4

Problem 2: LRU with expiry

Extend the cache so that every entry also expires ttl seconds after it was written. An expired entry behaves like a missing one. The clock must be injectable so the cache can be tested without sleeping.

Approach: store (value, expires_at). Check the expiry on get and delete stale entries lazily. Capacity eviction still follows LRU order. Lazy expiry keeps both operations O(1); expired entries may occupy space until they are read or evicted, which is the same trade-off Redis makes alongside its active expiry cycle.

import time
from collections import OrderedDict

class TTLLRUCache:
    def __init__(self, capacity, ttl, clock=time.monotonic):
        self.capacity, self.ttl, self.clock = capacity, ttl, clock
        self.data = OrderedDict()            # key -> (value, expires_at)

    def get(self, key, default=None):
        item = self.data.get(key)
        if item is None:
            return default
        value, expires_at = item
        if self.clock() >= expires_at:
            del self.data[key]               # lazy expiry
            return default
        self.data.move_to_end(key)
        return value

    def put(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)

now = [0.0]
c = TTLLRUCache(2, ttl=10, clock=lambda: now[0])
c.put("a", 1)
now[0] = 5;  print(c.get("a"))   # 1
now[0] = 11; print(c.get("a"))   # None (expired)
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorComplexity of an LRU CacheCapítulo siguienteLRU in the Real World

Problem 3: Byte-limited cache

Entries have different sizes. The cache has a byte budget instead of an entry count. Inserting a value must evict least recently used entries until the new value fits. A value larger than the whole budget is not cached at all.

Approach: keep a running total of bytes. After an insert or update, pop from the least recent end while the total exceeds the budget. Each entry is evicted at most once after being inserted, so the cost is O(1) amortized per operation.

from collections import OrderedDict

class ByteLRU:
    def __init__(self, max_bytes):
        self.max_bytes, self.used = max_bytes, 0
        self.data = OrderedDict()            # key -> bytes

    def get(self, key):
        if key not in self.data:
            return None
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key, blob):
        if len(blob) > self.max_bytes:
            return False
        if key in self.data:
            self.used -= len(self.data.pop(key))
        self.data[key] = blob
        self.used += len(blob)
        while self.used > self.max_bytes:
            _, old = self.data.popitem(last=False)
            self.used -= len(old)
        return True

b = ByteLRU(10)
b.put("x", b"12345"); b.put("y", b"1234"); b.get("x")
b.put("z", b"123")              # 12 bytes: evicts "y"
print(list(b.data), b.used)     # ['x', 'z'] 8

Problem 4: Memoize with a recency limit

A recursive function counts paths in a grid where some cells are blocked. Memoize it with a bounded LRU cache and report the hit ratio. Then explain why maxsize that is too small slows the function down.

Approach: decorate the function with functools.lru_cache(maxsize=...) and read cache_info(). Recursion revisits recent subproblems, so even a modest cache helps, but when maxsize is smaller than the active frontier the cache thrashes and most calls miss.

from functools import lru_cache

BLOCKED = {(1, 1), (2, 3)}
ROWS, COLS = 6, 6

@lru_cache(maxsize=64)
def paths(r, c):
    if (r, c) in BLOCKED or r >= ROWS or c >= COLS:
        return 0
    if (r, c) == (ROWS - 1, COLS - 1):
        return 1
    return paths(r + 1, c) + paths(r, c + 1)

print(paths(0, 0))
info = paths.cache_info()
print(f"hit ratio {info.hits / (info.hits + info.misses):.2f}")

Summary

  • Simulation plus the stack property of LRU turns capacity planning into a binary search.
  • TTL, byte budgets and memoization are all small extensions of the same ordered map.
  • Always reason about what happens when an update, an oversized value or a tiny capacity arrives.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.