HASH-P6

A Bloom filter

Practice 6 of 6Hashing9 tests

The problem

Build the Bloom filter from lesson 8. It has m bits and uses k positions per word. The two hash functions h1 and h2 are given in the starter code. The positions for a word are

(h1(word) + i * h2(word)) % m      for i = 0, 1, …, k − 1

This trick, called double hashing, makes k positions from just two hash values.

  • add(word) sets the word’s k bits to 1.
  • might_contain(word) is True only if all k of its bits are 1.
  • bits() lists the positions that are 1, smallest first.
  • false_rate(n) returns the expected false positive rate after n words (lesson 8). In Python it is (1 - math.exp(-k * n / m)) ** k. Here math.exp(x) is the number e (about 2.718) raised to the power x, and ** k raises the result to the power k.
B = Bloom(16, 3)
B.add('cat'); B.add('dog'); B.add('owl')
B.bits()                  # [0, 2, 3, 4, 6, 10, 11, 12]
B.might_contain('fox')    # False
B.might_contain('bee')    # True: a false positive

Store bits, not words: the tests check that false positives happen exactly where they should.

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 1,000,000 bits and 100,000 words.

Builds on HASH-8 Bloom filters.

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
1The figure's filterNot run
2Ask the figure's questionsNot run
3Empty filterNot run
4One hash functionNot run
5Adding twice changes nothingNot run
6No false negativesNot run
7Counting false positivesNot run
8The expected rateNot run
9100,000 wordsNot run