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’skbits to 1.might_contain(word)is True only if allkof its bits are 1.bits()lists the positions that are 1, smallest first.false_rate(n)returns the expected false positive rate afternwords (lesson 8). In Python it is(1 - math.exp(-k * n / m)) ** k. Heremath.exp(x)is the number e (about 2.718) raised to the power x, and** kraises 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
- 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.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The figure's filter | Not run | |
| 2 | Ask the figure's questions | Not run | |
| 3 | Empty filter | Not run | |
| 4 | One hash function | Not run | |
| 5 | Adding twice changes nothing | Not run | |
| 6 | No false negatives | Not run | |
| 7 | Counting false positives | Not run | |
| 8 | The expected rate | Not run | |
| 9 | 100,000 words | Not run |