# Scrivi il codice per la funzione cache. È un decoratore che deve
# ricordare cosa ha restituito la funzione decorata e restituire il valore memorizzato
# nelle chiamate successive con gli stessi argomenti.
# Si può assumere che tutti gli argomenti siano hashable.
# Usa solo la libreria standard di Python.
def cache(backend=None):
if backend is None:
backend = {}
def decorator(func):
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
result = backend.get(key)
if result is not None:
return result
result = func(*args, **kwargs)
backend[key] = result
return result
return wrapper
return decorator
calls = {"count": 0}
backend = {}
@cache(backend=backend)
def add(a, b):
calls["count"] += 1
return a + b
assert add(1, 2) == 3
assert calls["count"] == 1
assert add(1, 2) == 3
assert calls["count"] == 1
assert len(backend) == 1
print("OK")