bitmap.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from functools import reduce
  2. import math
  3. class Bitmap(int):
  4. def __new__(cls, value=0, *args, **kwargs):
  5. return super(cls, cls).__new__(cls, value)
  6. # iterable: positions of bits to set.
  7. @classmethod
  8. def from_list(cls, iterable):
  9. v = reduce(lambda x,y: x|2**y, iterable, 0) # iterable
  10. return super(cls, cls).__new__(cls, v)
  11. def __repr__(self):
  12. return "Bitmap("+format(self, 'b')+")"
  13. def __str__(self):
  14. return self.__repr__()
  15. def __or__(self, other):
  16. return self.__class__(super().__or__(other))
  17. def __and__(self, other):
  18. return self.__class__(super().__and__(other))
  19. def __invert__(self):
  20. return self.__class__(super().__invert__())
  21. def set(self, pos):
  22. return self.__or__(2**pos)
  23. def unset(self, pos):
  24. return self.__and__(~2**pos)
  25. def has(self, pos):
  26. return self & 2**pos
  27. def has_all(self, bitmap):
  28. return (self | bitmap) == self
  29. # pos of first set bit
  30. def first_bit_pos(self):
  31. return math.floor(math.log2(x & -x))
  32. def Bit(pos):
  33. return Bitmap(2 ** pos)