
Code
Buckets & Collisions
How does a dict find a key instantly, even among a million? It's a
hash table. Let's build a tiny one to see the trick.
The idea
- Keep a list of buckets (each bucket is a small list).
hash(key)turns the key into a big integer.hash(key) % len(buckets)picks a bucket index.- Store the
(key, value)pair in that bucket.
buckets = [[] for _ in range(4)]
index = hash("oil") % 4 # some number 0..3
buckets[index].append(("oil", 5))
Collisions
Two different keys can land in the same bucket, a
collision. That's fine: the bucket holds several pairs, and we
scan just that one small bucket comparing keys with ==. With
enough buckets, each holds only a few pairs, so lookups stay O(1)
on average. (Real dicts also grow their table as they fill up.)
Pip tip: This is why dict keys must be hashable (like
str,int,tuple). A list can change, so its hash would change too and it would get lost in the wrong bucket!
Assignment
Finish LanternTable:
put(key, value): if the key is already in its bucket, replace that pair with(key, value). Otherwise append the new pair and add 1 toself.count.get(key, default=None): return the value stored forkey, ordefaultif it isn't there.- Store pairs as
(key, value)tuples insideself.buckets. No dicts allowed inside the table!
Finish LanternTable:
put(key, value): if the key is already in its bucket, replace that pair with(key, value). Otherwise append the new pair and add 1 toself.count.get(key, default=None): return the value stored forkey, ordefaultif it isn't there.- Store pairs as
(key, value)tuples insideself.buckets. No dicts allowed inside the table!
main.py Python sleeping
Press Run to try your code, then Check to test it.