The problem
Build a hash table that uses chaining (lesson 2). Do not use Python’s dict or set: the point is to build one. Use Python’s own hash(key) for the hash.
- A new table has 8 buckets. A key goes in bucket
hash(key) % m, wheremis the number of buckets. - A new key goes at the end of its bucket’s chain.
- After a
putadds a new key, if the number of keys n is now bigger than m, double m. Then move every key to its new bucket: take the old buckets in order (0 first), and each chain from front to back. - The table never shrinks.
buckets()returns the keys in each bucket, for example[[], [9], [], [3, 11]].
T = ChainMap()
T.put('NDLS', 1); T.put('BCT', 2)
T.get('NDLS') # 1
T.get('MAS') # None
T.remove('BCT') # True
len(T) # 1
The tests make an object and call its methods in order. A test shows the list of calls, and compares the list of everything they returned (methods that return nothing give None).
Limits
- Up to 100,000 keys. Every method except buckets() must take O(1) time on average.
Builds on HASH-1 Hash functions and HASH-2 Chaining.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
9 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Put and get | Not run | |
| 2 | Put the same key twice | Not run | |
| 3 | Missing key | Not run | |
| 4 | Remove | Not run | |
| 5 | Where the keys go | Not run | |
| 6 | The table grows | Not run | |
| 7 | Tuple keys | Not run | |
| 8 | Grows twice, then removes | Not run | |
| 9 | 100,000 keys | Not run |