# Parašykite kodą funkcijai cache. Tai turi būti dekoratorius, kuris
# turėtų prisiminti, ką grąžino dekoruota funkcija, ir grąžinti saugomą
# reikšmę pakartotinio kvietimo su tais pačiais argumentais metu.
# Galima manyti, kad visi argumentai yra hash'able.
# Naudokite tik Python standartinę biblioteką.
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")