1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- #!/usr/bin/env python3
- class Serial:
- modulus = 2 ** 32
- def __init__(self, val):
- self._val = int(val)
- if self._val < 0 or self._val >= self.modulus:
- raise ValueError
- def __add__(self, val):
- val = int(val)
- if val < 0 or val > (self.modulus - 1) >> 1:
- raise ValueError
- return type(self)((self._val + val) & (self.modulus - 1))
- def __le__(self, other):
- return (self.modulus - int(self) + int(other)) & (self.modulus >> 1) == 0
- def __ge__(self, other):
- return (self.modulus + int(self) - int(other)) & (self.modulus >> 1) == 0
- def __eq__(self, other):
- return int(self) == int(other)
- def __ne__(self, other):
- return int(self) != int(other)
- def __lt__(self, other):
- return self != other and self <= other
- def __gt__(self, other):
- return self != other and self >= other
- def __int__(self):
- return self._val
- def __str__(self):
- return f"{int(self):{len(str(self.modulus))}d}"
- def step(start, finish):
- if start < finish:
- return start, finish
- else:
- midpoint = start + ((Serial.modulus >> 1) - 2)
- assert start < midpoint and midpoint < finish
- return start, midpoint, finish
- if __name__ == "__main__":
- from random import randint
- for test in range(10000):
- i1 = Serial(randint(0, Serial.modulus - 1))
- i2 = Serial(randint(0, Serial.modulus - 1))
- assert i1 == i2 or \
- (i1 < i2 and not (i1 > i2)) or \
- (i1 > i2 and not (i1 < i2)) or \
- int(i1) & int(i2) == Serial.modulus >> 1
- print(f"{i1} => {i2}: {', '.join(str(s) for s in step(i1, i2))}")
|