bloom filter的python实现
时间: 2023-04-27 13:04:00 浏览: 128
Bloom filter是一种快速的数据结构,用于判断一个元素是否在一个集合中。它使用一组哈希函数和一个位数组来实现。Python中可以使用bitarray库来实现Bloom filter。以下是一个简单的Python实现:
```python
import bitarray
import mmh3
class BloomFilter:
def __init__(self, size, hash_count):
self.size = size
self.hash_count = hash_count
self.bit_array = bitarray.bitarray(size)
self.bit_array.setall()
def add(self, item):
for seed in range(self.hash_count):
result = mmh3.hash(item, seed) % self.size
self.bit_array[result] = 1
def __contains__(self, item):
for seed in range(self.hash_count):
result = mmh3.hash(item, seed) % self.size
if self.bit_array[result] == :
return False
return True
```
在上面的代码中,我们使用了mmh3哈希函数来生成哈希值。我们还定义了一个BloomFilter类,它包含一个位数组和一些方法来添加和检查元素是否在集合中。我们可以使用以下代码来测试Bloom filter:
```python
bf = BloomFilter(500000, 7)
words = ['hello', 'world', 'python', 'bloom', 'filter']
for word in words:
bf.add(word)
print('hello' in bf) # True
print('world' in bf) # True
print('python' in bf) # True
print('bloom' in bf) # True
print('filter' in bf) # True
print('test' in bf) # False
```
在上面的代码中,我们首先创建了一个Bloom filter,然后将一些单词添加到集合中。最后,我们检查一些单词是否在集合中。
阅读全文
相关推荐
















