Bloom Filter for Membership Tests
Use a Bloom filter to rule out absent keys with no false negatives, trading a small false-positive rate for large memory savings.
Code
import hashlib
from typing import Iterable
class BloomFilter:
def __init__(self, size: int, hash_count: int) -> None:
if size <= 0 or hash_count <= 0:
raise ValueError("size and hash_count must be positive")
self.size = size
self.hash_count = hash_count
self.bits = bytearray(size)
def _positions(self, item: str) -> Iterable[int]:
for index in range(self.hash_count):
digest = hashlib.sha256(f"{index}:{item}".encode()).digest()
yield int.from_bytes(digest[:4], "big") % self.size
def add(self, item: str) -> None:
for position in self._positions(item):
self.bits[position] = 1
def might_contain(self, item: str) -> bool:
return all(self.bits[position] == 1 for position in self._positions(item))What the code does
The working surface is the class BloomFilter and the functions __init__, _positions, add and might_contain — everything else is wiring.
Iteration happens inside for index in range(self.hash_count) — everything outside it runs once. Invalid states are rejected up front: it throws ValueError instead of continuing with bad data.
Watch out for
- The guard
size <= 0 or hash_count <= 0short-circuits the flow with an earlyraisewhen its condition holds.
Applying it
Entry signature: def add(self, item: str) -> None
The surface worth importing is add; the helpers around it are private to the snippet.
Statements that matter
def __init__(self, size: int, hash_count: int) -> None:
if size <= 0 or hash_count <= 0:
raise ValueError("size and hash_count must be positive")
self.size = size
self.hash_count = hash_count
self.bits = bytearray(size)
def add(self, item: str) -> None:
for position in self._positions(item):
self.bits[position] = 1
def _positions(self, item: str) -> Iterable[int]:
for index in range(self.hash_count):
digest = hashlib.sha256(f"{index}:{item}".encode()).digest()
yield int.from_bytes(digest[:4], "big") % self.size
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- What happens on invalid input?
- It throws `ValueError` before any real work runs, via the guard `size <= 0 or hash_count <= 0` — handle it at the call site or let it propagate deliberately.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `__init__`, `_positions`, `add` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.