BitSet的python实现
作者:
endinggy
,
2022-03-16 18:00:43
,
所有人可见
,
阅读 236
class Bitset(object):
def __init__(self, n):
self.usize = 64
self.n = n // self.usize + 1
self.arr = array('Q', [0] * self.n)
def set(self, i):
i, j = divmod(i, self.usize)
self.arr[i] |= (1 << j)
def reset(self, i):
i, j = divmod(i, self.usize)
d = self.arr[i] >> j & 1
self.arr[i] -= d * (1 << j)
def any(self):
for i in range(self.n):
if self.arr: return True
return False
def count(self):
cnt = 0
for i in range(self.n):
for j in range(self.usize - 1, -1, -1):
cnt += (self.arr[i] >> j) & 1
return cnt
def __or__(self, other):
res = Bitset((self.n - 1) * self.usize)
for i in range(self.n):
res.arr[i] = self.arr[i] | other.arr[i]
return res
def __and__(self, other):
res = Bitset((self.n - 1) * self.usize)
for i in range(self.n):
res.arr[i] = self.arr[i] & other.arr[i]
return res
def __xor__(self, other):
res = Bitset((self.n - 1) * self.usize)
for i in range(self.n):
res.arr[i] = self.arr[i] ^ other.arr[i]
return res