Strategy Pattern in Python: Write Flexible, Clean Code How to pick different algorithms at runtime—without a tangled web of if/else Hey there! Today I want to write about a design pattern: the Strategy Pattern . Perfect for when you have multiple ways to solve the same problem and you want clean, maintainable code. Why the Strategy Pattern? Let’s start with a scenario: imagine you're building a pizza delivery app, and different restaurants have wildly different APIs. Without planning, you might end up stuffing your code full of branching logic. Instead, the Strategy Pattern lets you isolate each integration into its own “strategy,” making your code neat and flexible. In software design terms, a strategy defines a family of algorithms, each encapsulated in its own class (or callable), and they’re all interchangeable at runtime. This helps avoid massive if/else blocks and makes adding new behavior super easy without touching existing code—hell...
Upgrading Python Recursion with functools.lru_cache Make Fibonacci fast—and understand what's happening under the hood Hey there! If you've ever played with the Fibonacci sequence in Python, you probably know how painfully slow a naive recursive version can be. Let’s explore how functools.lru_cache can turn that recursion into lightning fast compute. The problem: Fibonacci and slow recursion Say you write this classic recursive function: def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) It’s simple and elegant. But try fib(40) or higher, and you'll wait... because it recombines the same subproblems again and again. A quick fix with lru_cache Here’s how we can upgrade it: from functools import lru_cache @lru_cache(maxsize=128) def fib_cached(n): if n < 2: return n return fib_cached(n-1) + fib_cached(n-2) print(fib_cached(40)) # instant result print(fib_cached.cache_info()) # shows hits ...