Created
August 27, 2014 20:24
-
-
Save mmccollow/c8cd10ed21de3d919632 to your computer and use it in GitHub Desktop.
Simple Bloom Filter Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Implementation of a simple Bloom Filter | |
# @author Matt McCollow <[email protected]> | |
import hashlib | |
class Filter(): | |
def __init__(self, debug=False): | |
self.bits = 0x0 | |
self.mask = 0xFFFF | |
self.elements = [] | |
self.debug = debug | |
def hash(self, string): | |
md5 = hashlib.md5(string).hexdigest() | |
sha1 = hashlib.sha1(string).hexdigest() | |
return (md5[:1], sha1[-1:]) | |
def add(self, string): | |
hashes = self.hash(string) | |
self.bits = self.bits | (1 << int(hashes[0], 16)) | |
self.bits = self.bits | (1 << int(hashes[1], 16)) | |
self.elements.append(string) | |
if self.debug: | |
print bin(self.bits) | |
def contains(self, string): | |
hashes = self.hash(string) | |
mask1 = 1 << int(hashes[0], 16) | |
mask2 = 1 << int(hashes[1], 16) | |
if (((mask1 | mask2) & self.bits) == (mask1 | mask2)): | |
return True | |
return False | |
def items(self): | |
print self.elements |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment