Hashing
Not met yet
A hash function turns a key into a number, and the same key always gives the same number. A hash map takes the remainder of that number by how many piles it has, and that picks the key's pile. Different keys can land in the same pile, which is a collision, and that's allowed. Because a key's pile depends on its hash, a key must never change after it's filed: Python only takes hashable keys, like strings, numbers and tuples of them, never lists.
Try it
main.pydef part_hash(name):
number = 0
for character in name:
number = (number * 31 + ord(character)) % 1_000_003
return number
for name in ["brass-valve", "kettle", "anvil"]:
print(name, part_hash(name) % 8)
Output
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks a hash function always sends different keys to different piles, so collisions can't happen.
- Thinks a list can be a dictionary key, not knowing that keys must be hashable and lists can change.
- Thinks a tuple can't be a dictionary key because it holds several things, when a tuple of hashable things can.
- Thinks a hash function can give a different number for the same key on a later call in the same run.