← 中文资源

简体中文版本

用于成员检测的布隆过滤器

用布隆过滤器以极小误判率排除不存在的键且不产生漏判,换取显著的内存节省。

阅读英文原文

实现说明

用于成员检测的布隆过滤器可以归结为类 BloomFilter和函数 __init__、_positions、add、might_contain。 for index in range(self.hash_count) 反复执行,循环体之外没有别的重复。非法状态在入口就被拒绝:抛出 ValueError,而不是带着坏数据继续。

使用要点

  • 守卫 size <= 0 or hash_count <= 0 一旦成立就走提前的 raise,把后续流程挡掉。
  • 调用方只需要 add——其余都是内部实现。

常见问题

输入非法时会怎样?

在真正开工之前就会抛出 ValueError(守卫:size <= 0 or hash_count <= 0)——请在调用点处理,或有意向上传播。

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 文件在加载时定义 __init__、_positions、add。

入口签名:def add(self, item: str) -> None

核心语句

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

代码示例

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))