mastering python chapter3

23
3. Container and Collections - Storing Data the Right Way Mastering Python Keunhyun Oh

Upload: keunhyun-oh

Post on 21-Jan-2018

37 views

Category:

Software


0 download

TRANSCRIPT

3. Container and Collections - Storing Data the Right Way

Mastering PythonKeunhyun Oh

Core Collections• List

• Dict

• Set

• Tuple

Advanced Collections• ChainMap

• Counter

• DefaultDic

• OrderedDic

• Deque

• Heapq

• Named Tuple

• Enum

Big O• To indicate the time complexity for an operation

• O(n): Taking n step to execute

Big O Example 1: O(1)

Big O Example 2: O(n)

Big O Example 3: O(n^2)

Core Collections

List• A mutable list of items

• Time Complexity

• append, get, set, Len: O(1)

• remove, insert: O(n)

Dict• Unsorted but a fast map of items

• Time Complexity

• O(1) expected

• Worst Case: O(n) (hash Collision

• When deleting items from a dictionary, it won’t actually resize the dictionary in memory yet

Set• Like a dict without Values

• Time Complexity

• O(1) expected

• Worst Case: O(n) (hash Collision)

Set: Operations

Tuple• The immutable list

• Hashable

• Possible to be used as a key in a dict

• A variable number of items (ex. *egg)

Advanced Collections

ChainMap• The list of dictionaries

• Useful for command-line applications followed by defaults

Counter• Keeping track of the most occurring elements

• Supporting operations similar to the set operations

Deque• The double ended queue

• Created as a doubly linked list, which means that every item points to the next and the previous item

• Adding and removing items from either the beginning or the end a very light O(1) operation

• Supporting operations similar to the set operations

Defaultdic• Dictionary with a default value

• Supporting generating itself recursively

Namedtuple• Tuples with field names

Enum• A group of constants

• Making it really easy to have constants in your modules while still avoiding magic numbers

• Iterable

• Not just integers bug custom types as well

OrderedDict• A dictionary where the insertion order matter

• O(1)

• Memory usage heavier than dic

Heapq• The ordered list

• Heap: A binary tree for which every parent node has a value less than or equal to any of its children

Bisect• The sorted list

• Maintaining a list in sorted order without having to sort the list after each insertion

• Insertion(O(n)) slower than list(O(1))

• Search faster than list