Bloom Filter Probabilistic Membership (Python)

Implement a bloom filter with k hash functions for probabilistic membership testing in Python.

PythonData Integrity

Code

pythonsnippet
18 lines
class BloomFilter:
    def __init__(self, size=1000, k=7):
        self.bits = bytearray(size)
        self.size = size
        self.k = k

    def _hash(self, item, seed):
        h = seed
        for c in str(item):
            h = (h * 31 + ord(c)) % self.size
        return h

    def add(self, item):
        for i in range(self.k):
            self.bits[self._hash(item, i + 1)] = 1

    def contains(self, item):
        return all(self.bits[self._hash(item, i + 1)] for i in range(self.k))

What the code does

The working surface is the class BloomFilter and the functions __init__, _hash, add and contains — everything else is wiring.

Repetition is confined to for c in str(item) — the rest of the file is straight-line.

Applying it

The primary signature is def add(self, item)

The surface worth importing is add; the helpers around it are private to the snippet.

Statements that matter

def __init__(self, size=1000, k=7):
    self.bits = bytearray(size)
    self.size = size
    self.k = k
def _hash(self, item, seed):
    h = seed
    for c in str(item):
        h = (h * 31 + ord(c)) % self.size
    return h
def contains(self, item):
    return all(self.bits[self._hash(item, i + 1)] for i in range(self.k))

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `__init__`, `_hash`, `add` at load time.