Bloom Filter Probabilistic Membership (Python)
Implement a bloom filter with k hash functions for probabilistic membership testing in Python.
Code
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))Report a problem with this exampleOpens a pre-filled issue on GitHub.