Python Cookbook Data Structures and Algorithms Day 1 정리

Star Expression

Problem: You need to unpack N elements from an iterable, but the iterable may be longer than N elements, causing a “too many values to unpack” exception.


Problem:  You want to keep a limited history of the last few items seen during iteration or during
some other kind of processing.

※Deque:  Using deque(maxlen=N) creates a fixed-sized queue. When new items are added and
the queue is full, the oldest item is automatically removed.


Problem: You want to make a list of the largest or smallest N items in a collection.

Caution: If you are looking for the N smallest or largest items and N is small compared to the overall size of the collection, these functions provide superior performance. If you are simply trying to find the single smallest or largest item (N=1), it is faster to use min() and max(). Similarly, if N is about the same size as the collection itself, it is usually faster to sort it first and take a slice (i.e.,use sorted(items)[:N] or sorted(items)[-N:]).


Problem:  You want to implement a queue that sorts items by a given priority and always returns
the item with the highest priority on each pop operation