Exercise 1 β Cache Decorator
Python
def cache(func):
memo = {}
def wrapper(*args):
if args not in memo:
memo[args] = func(*args)
return memo[args]
return wrapper
@cache
def expensive(n):
print(f"Computing {n}...")
return n * n
expensive(5) # Computing 5... β 25
expensive(5) # from cache β 25Exercise 2 β Stack Class
Python
class Stack:
def __init__(self):
self._items = []
def push(self, item): self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("Stack is empty")
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("Stack is empty")
return self._items[-1]
def __len__(self): return len(self._items)
def __bool__(self): return bool(self._items)
s = Stack()
s.push(1); s.push(2); s.push(3)
print(s.peek()) # 3
print(s.pop()) # 3Exercise 3 β Infinite Counter Generator
Python
def counter(start=0, step=1):
n = start
while True:
yield n
n += step
import itertools
evens = list(itertools.islice(counter(0, 2), 5))
print(evens) # [0, 2, 4, 6, 8]Exercise 4 β Timer Context Manager
Python
import time
from contextlib import contextmanager
@contextmanager
def timer(label=""):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.4f}s")
with timer("List comp"):
result = [x**2 for x in range(1_000_000)]Exercise 5 β Flatten Nested List
Python
from collections.abc import Iterable
def flatten(iterable):
for item in iterable:
if isinstance(item, Iterable) and not isinstance(item, str):
yield from flatten(item)
else:
yield item
nested = [1, [2, [3, 4]], [5, 6], 7]
print(list(flatten(nested))) # [1, 2, 3, 4, 5, 6, 7]Tip: In interviews: clarify requirements first, discuss time/space complexity, then handle edge cases before declaring done.