Bloom Filter With Hashlib
Implement a bloom filter using hashlib for probabilistic membership testing with false positive control.
Code
import hashlib, math
class BloomFilter:
def __init__(self, capacity, error_rate=0.01):
self.size = int(-capacity * math.log(error_rate) / math.log(2)**2)
self.hash_count = int(self.size / capacity * math.log(2))
self.bits = bytearray(self.size // 8 + 1)
def _hash(self, item, seed):
h = hashlib.sha256(f'{seed}:{item}'.encode()).digest()
return int.from_bytes(h[:8], 'big') % self.size
def add(self, item):
for i in range(self.hash_count):
idx = self._hash(item, i)
self.bits[idx // 8] |= 1 << (idx % 8)
def __contains__(self, item):
return all((self.bits[self._hash(item, i) // 8] >> (self._hash(item, i) % 8)) & 1 for i in range(self.hash_count))Report a problem with this exampleOpens a pre-filled issue on GitHub.