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.
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).
put(name, value)stores the value under the name. If the name is there already, its pair is replaced where it stands.get(name, default=None)returns the value stored under the name, ordefaultif there isn't one.remove(name)takes the name out and returns its value, or raisesKeyErrorif it isn't there.len(parts)is how many names are stored,name in partssays whether one is, andload()is how many names there are to a pile.- When a
putadds 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. probescounts the work: one for every comparison of a stored name with the name being looked for, in any method. Moving pairs costs none.
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
- A number for every name
- A first guess at a rule
- Keys that can't change
- What can be a key
- Piles and probes
- Along one pile
- More piles as it fills
- Where does it go now?
- How Paul would do it
- Fix Yahya's version
- Make the hash map
- Ship it