Sub topic 2
Fix the Algorithm and Data Structure First
Assume you can write Python functions, loops, and modules, use lists, dictionaries, and sets, and run scripts from a terminal. Before changing syntax, measure the slow operation and define a target, such as “process 100,000 records in under one second.”
Choose the right algorithm and data structure
An algorithm is the set of steps used to solve a problem. A data structure is how the program stores its data. The right choice often matters more than small syntax changes.
For example, searching a list checks items one by one. Searching a set uses hashing and is usually constant time on average.
| Operation | List | Set |
|---|---|---|
| Membership test | O(n) | O(1) average |
| Preserve item order | Yes | No guaranteed order for this purpose |
| Allow duplicates | Yes | No |
import timeit
items_list = list(range(10_000))
items_set = set(items_list)
list_time = timeit.timeit(
"9_999 in items_list", globals=globals(), number=1_000
)
set_time = timeit.timeit(
"9_999 in items_set", globals=globals(), number=1_000
)
print(f"list: {list_time:.4f}s")
print(f"set: {set_time:.4f}s")Convert a list to a set when you need repeated membership checks and do not need duplicates or list ordering. Confirm the improvement with a benchmark and check that the new behavior remains correct.
Use lower-cost Python idioms
Built-in operations run optimized C code and are often faster than equivalent Python loops. Build strings with join, use comprehensions for simple transformations, and use sum, any, or all when they express the operation clearly.
parts = [str(number) for number in range(1_000)]
result = ",".join(parts)A comprehension does not automatically fix a poor algorithm. Prefer clarity, then measure.
> callout tip > Optimize the largest cost first. A faster loop cannot compensate for an algorithm that does unnecessary work.
Avoid repeated work with `lru_cache`
Caching stores a function’s result for later calls. functools.lru_cache works well for deterministic functions whose arguments are hashable.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
print(fib.cache_info())Use caching when calls repeat and results remain valid. Avoid it when arguments are unique, results depend on changing state, or memory use could grow without bound.
Exercise
Which change usually helps more: replacing a list membership test with a set, or renaming the loop variable?
Show answer
Replacing the list with a set usually helps more because it changes the average lookup complexity from O(n) to O(1).