Назад к подготовке

Python dict lookup, декораторы и генераторы

Python dict lookup, декораторы и генераторы

Ответить самому

Сначала сформулируйте ответ как на собеседовании, затем откройте разбор и оцените себя.

Загрузка

Короткий ответ

Dict lookup is average O(1) through hashing, while list search is O(n). A decorator wraps a function or class to add behavior. A generator lazily produces values, saving memory for streams or large sequences.

Полный разбор

A Python dict is a hash table. Looking up a key usually hashes the key and probes a small number of slots, so average complexity is O(1). Searching a list checks elements sequentially, so it is O(n).

A decorator is callable syntax for wrapping another function or class. Common uses are caching, logging, timing, authorization, retries and context-like setup around a call. It should preserve metadata with functools.wraps when possible.

A generator is an iterator that yields values lazily. It is useful when the full collection is large, infinite, expensive to compute or naturally streamed. The trade-off is that generators are consumed once and do not provide random access unless materialized.

Теория

Python containers encode different algorithmic contracts: hash lookup, sequential scan and lazy iteration.

Типичные ошибки

  • Say dict lookup is always O(1) without acknowledging collisions/worst case.
  • Describe decorators as comments or annotations only.
  • Use a generator when the data must be reused many times.

Как отвечать на собеседовании

  • Answer with complexity first.
  • Give one concrete decorator use case and one generator use case.