Data types, hashing

Data types in Python

  • Mutable and immutable types?
  • Mutable — points to the same object id()
    Immutable — creates new object when we modify
    list
    None
    set
    bool: True, False
    dict
    int, float
    bytearray
    str
    tuple
    frozenset
    bytes (integer in range 0 ≤ x ≤ 255)
  • Mutable and immutable types as function argument?
    • When mutable is argument to function → python does call by object reference.
    • Immutable object → python “switches” to call by value (creates a new string object to hold the newly created object).
  • Coding exercises
  • Tricky questions

Sorting list/tuple/dictionaries

dict(sorted(count_dict.items(), key=lambda x:x[1]))

Dictionary in Python

Python dicts are hash tables. Keys can be None, and keys should consist of immutable objects. Each row takes up 24 bytes.

  • If there is a collision, Python uses open addressing.
    • After 5 key-values are stored, when adding another key-value pair, the probability of hash collisions is too large, so the dictionary is doubled in size. It now takes 240 bytes of memory.
  • The common strategies to resolve collisions in a hash table are:
    • Open addressing - if the bucket you should use is busy, you just keep searching for a new bucket to be used, when deleting collided element will be also deleted.
    • Separate chaining - diving into buckets.
Coding exercises

What can we use as a key in dict?

Answer

Hashing and hash functions

Hash function
hashable()

Collections

namedtupes, defaultdicts, Counter

String formatting

d       Decimal integer
b       Binary integer
x       Hexadecimal integer
f       Float as [-]m.dddddd
e       Float as [-]m.dddddde+-xx
g       Float, but selective use of E notation
s       String
c       Character (from integer)

:>10d   Integer right aligned in 10-character field
:<10d   Integer left aligned in 10-character field
:^10d   Integer centered in 10-character field
:0.2f   Float with 2 digit precision

Resources

SuperMade with Super