Alterna · учебный материал
Algorithmic instruments
Collections, tertols, functools, heapq and bisect in Python: choose the data structure for the operation.
Что в этом материале
- associations: data in terms of
- Flow, selection and search
- Example: Three best results
- Quick check
Содержание и основные понятия
Don't replace your understanding of the names of the modules. First name the invariant and complexity, then choose.
deque
,
Counter
a bunch or a binary search.
of the data structure
10 to 11 grades
EEG: Algorithm ideas
01
associations: data in terms of
Counter(iterable)
Frequent dictionary: Considers the emergence of values.
Sounds like
dict
but expresses intent.
deque()
Line with fast
appendleft
and
popleft
.
Do not delete the beginning of the usual list many times.
defaultdict(list)
Creates default value for a new key.
It's convenient for a grouping, but it's normal.
dict.get
Sometimes it's easier.
namedtuple / dataclass
They give you the names of the recording fields.
For an educational couple, it's often enough for a regular motorcade.
02
Flow, selection and search
Tool
Objective
Do not use instead
itertools.combinations
Select all pairs or small sets.
Linear big data algorithm.
functools.lru_cache
Remember the results of a pure recursive function.
Explanations of recursion if the cache conceals an important condition.
heapq
Take the minimum many times or store top-k.
Full sorting, if you need all order once.
bisect
Find a position on an already sorted list.
Searching ungraded data.
Invariant of piles
heapq
guarantees minimum position
0
The rest of the list is not fully sorted: do not treat a pile as a ready-made sorted array.
03
Example: Three best results
If only a few maximum values are required,
heapq.nlargest
When you need a fully sorted result, choose.
sorted
.
import
heapq
scores = [72, 91, 84, 68, 95, 88]
leaders = heapq.nlargest(3, scores)
print(leaders)
Result
[95, 91, 88]
It only contains the right three. The reference list does not change.
04
Quick check
Which container is more appropriate for multiple extraction of elements from the beginning of the line?