forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_301.py
More file actions
31 lines (24 loc) · 730 Bytes
/
problem_301.py
File metadata and controls
31 lines (24 loc) · 730 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from hashlib import md5, sha256
from binascii import unhexlify
class BloomFilter:
def __init__(self):
self.vector = 0
def get_hash(self, value):
return int.from_bytes(
unhexlify(md5(value.encode("UTF-8")).hexdigest()),
byteorder='little')
def add(self, value):
hashed = self.get_hash(value)
self.vector |= hashed
def check(self, value):
hashed = self.get_hash(value)
for a, b in zip(bin(hashed)[2:], bin(self.vector)[2:]):
if bool(int(a)) and not bool(int(b)):
return False
return True
# Tests
bf = BloomFilter()
bf.add("test1")
bf.add("test2")
assert bf.check("test1")
assert not bf.check("test3")