HASH-P1

A table of buckets

Practice 1 of 6Hashing9 tests

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, where m is the number of buckets.
  • A new key goes at the end of its bucket’s chain.
  • After a put adds 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1Put and getNot run
2Put the same key twiceNot run
3Missing keyNot run
4RemoveNot run
5Where the keys goNot run
6The table growsNot run
7Tuple keysNot run
8Grows twice, then removesNot run
9100,000 keysNot run