Paul's Python CoursePPC

Project 7 of 15, for Neil

Hash Map from Scratch

Neil's parts script finds any part in a look or two, however many he has. Build a dict from scratch to see how: piles, collisions, doubling, and every probe counted.

About an hour and a half, in 13 steps.

Sign up free to open itLog in

Act 4 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • NeilI timed my parts dict, and a lookup's just as quick with two hundred parts as with the kart track's ten thousand.
  • NeilA list has to walk along, so what's a dict doing instead? I've never actually looked inside one.
  • PaulIt does a sum on the key, and the answer tells it which pile to look in. Build one and you'll see.
  • PaulYou'll need more piles as it fills up, and some rule for when to make them.

In hash_map.py, part_hash(name) turns a name into a number, the same number every time. Build a HashMap: a dictionary made by hand, from names to anything, filed in piles.

HashMap(piles=8) starts with that many empty piles in self.piles, a list of lists of (name, value) pairs. A name lives in pile number part_hash(name) % len(self.piles).

  1. put(name, value) stores the value under the name. If the name is there already, its pair is replaced where it stands.
  2. get(name, default=None) returns the value stored under the name, or default if there isn't one.
  3. remove(name) takes the name out and returns its value, or raises KeyError if it isn't there.
  4. len(parts) is how many names are stored, name in parts says whether one is, and load() is how many names there are to a pile.
  5. When a put adds a new name and there are then more than 0.75 names to a pile, double the number of piles and move every pair to its new pile: the old piles in order, each from front to back, onto the end of its new pile.
  6. probes counts the work: one for every comparison of a stored name with the name being looked for, in any method. Moving pairs costs none.
What it prints
200 parts in 512 piles, 0.39 to a pile
Finding every part: 260 probes
Finding every part along one long list: 20100 probes

What you learn

What's in it

  1. A number for every name
  2. A first guess at a rule
  3. Keys that can't change
  4. What can be a key
  5. Piles and probes
  6. Along one pile
  7. More piles as it fills
  8. Where does it go now?
  9. How Paul would do it
  10. Fix Yahya's version
  11. Make the hash map
  12. Ship it