Ghostly Python
👩💻 Викторина: что выведет код?
import functools
def smart_cache(maxsize=2):
cache = {}
order = []
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(kwargs.items()))
if key in cache:
order.remove(key)
order.append(key)
return f"Cached: {cache[key]}"
result = func(*args, **kwargs)
cache[key] = result
order.append(key)
if len(order) > maxsize:
oldest = order.pop(0)
del cache[oldest]
return f"Computed: {result}"
return wrapper
return decorator
count = 0
def tracer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
global count
count += 1
indent = " " * count
print(f"{indent}→ {func.__name__}{args}")
result = func(*args, **kwargs)
print(f"{indent}← {result}")
count -= 1
return result
return wrapper
@smart_cache(maxsize=2)
@tracer
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print(fib(3))
print(fib(2))
print(fib(4))
print(f"Calls: {count}")
🐍 Ghostly Python | #викторина
❤5
10 · 2.7K ·