Quellcode durchsuchen

Working version, dogmatically following specification

Rob Austein vor 7 Monaten
Ursprung
Commit
9552acff69
1 geänderte Dateien mit 19 neuen und 9 gelöschten Zeilen
  1. 19 9
      rfc1982_serial_number.py

+ 19 - 9
rfc1982_serial_number.py

@@ -3,11 +3,14 @@
 class Serial:
 
     def __init__(self, val):
-        self._val = int(val) & (2**32)
+        self._val = int(val) % 2**32
 
     def __int__(self):
         return self._val
 
+    def __str__(self):
+        return str(int(self))
+
     def __add__(self, val):
         return Serial(self._val + int(val))
 
@@ -19,24 +22,31 @@ class Serial:
 
     def __lt__(self, other):
         return self != other and (
-            (self._val < other._val and other._val - self._val < 2**31) or
-            (self._val > other._val and self._val - other._val > 2**31))
+            (int(self) < int(other) and int(other) - int(self)  < 2**31) or
+            (int(self) > int(other) and int(self)  - int(other) > 2**31))
 
     def __gt__(self, other):
         return self != other and (
-            (self._val < other._val and other._val - self._val > 2**31) or
-            (self._val > other._val and self._val - other._val < 2**31))
+            (int(self) < int(other) and int(other) - int(self)  > 2**31) or
+            (int(self) > int(other) and int(self)  - int(other) < 2**31))
 
 if __name__ == "__main__":
     from random import randint
 
     for test in range(100):
-        i1 = randint(0, 2**32-1)
-        i2 = randint(0, 2**32-1)
-
-        print(i1, i2)
+        i1 = Serial(randint(0, 2**32-1))
+        i2 = Serial(randint(0, 2**32-1))
 
         assert i1 == i2 or \
             (i1 < i2 and not (i1 > i2)) or \
             (i1 > i2 and not (i1 < i2)) or \
             int(i1) & int(i2) == 0x80000000
+
+        if i1 == i2:
+            print(f"{int(i1):10d} == {int(i2):10d}, how did that happen?")
+        elif i1 < i2:
+            print(f"{int(i1):10d} => {int(i2):10d}, can do it in one jump")
+        else:
+            i3 = i1 + (2**31 - 2)
+            print(f"{int(i1):10d} => {int(i2):10d}, need to wrap, i3 value {i3}")
+            assert i1 < i3 and i3 < i2