Skip to content

Instantly share code, notes, and snippets.

@badjano
Last active July 26, 2021 23:28
Show Gist options
  • Save badjano/94497a2edd85a53a57ff9ca27b720e25 to your computer and use it in GitHub Desktop.
Save badjano/94497a2edd85a53a57ff9ca27b720e25 to your computer and use it in GitHub Desktop.
import datetime
class Range:
def __init__(self, start, end):
self.start = min(start, end)
self.end = max(start, end)
self.empty = self.start == self.end
self.log = False
def print(self, *args, **kwargs):
if self.log:
print(*args, **kwargs)
def collides(self, other):
return not (other.end < self.start or other.start > self.end or self.empty or other.empty)
def __sub__(self, other):
if not self.collides(other):
self.print("NO COLLISION")
return [self.clone()]
if other.start == self.start:
if other.end < self.end:
self.print("SAME START, OTHER ENDS SOONER")
return [Range(other.end, self.end)]
else:
self.print("SAME START, OTHER IS BIGGER")
return []
if other.end == self.end:
if other.start > self.start:
self.print("SAME END, SELF STARTS SMALLER")
return [Range(self.start, other.start)]
else:
self.print("SAME END, OTHER IS BIGGER")
return []
elif other.start >= self.start:
if other.end >= self.end:
self.print("SELF STARTS SMALLER, OTHER ENDS LATER")
return [Range(self.start, min(self.end, other.start))]
else:
self.print("SELF STARTS SMALLER, OTHER ENDS SOONER ( SPLIT )")
return [
Range(self.start, other.start),
Range(other.end, self.end)
]
else:
if other.end <= self.end:
self.print("OTHER STARTS SOONER AND ENDS SOONER")
return [Range(other.end, self.end)]
else:
self.print("OTHER STARTS SOONER AND ENDS LATER")
return []
def __add__(self, other):
if not self.collides(other):
self.print("NO COLLISION")
return []
else:
return [Range(min(self.start, other.start), max(self.end, other.end))]
def __str__(self):
return f"({self.start} <> {self.end})"
def csv_data(self, f=None):
if not f:
f = int
return f"{f(self.start)},{f(self.end)}"
def clone(self):
return Range(self.start, self.end)
if __name__ == "__main__":
now = datetime.datetime.utcnow()
to_dt = lambda a: (now + datetime.timedelta(a)).date()
def run_cases(cases):
print("SUBTRACTION")
for case in cases:
a = Range(*case[:2])
b = Range(*case[-2:])
c = a - b
print(a, "-", b, "=", ", ".join([str(d) for d in c]) if c else "None")
print("ADDITION")
for case in cases:
a = Range(*case[:2])
b = Range(*case[-2:])
c = a + b
print(a, "+", b, "=", ", ".join([str(d) for d in c]) if c else "None")
cases = [
[1, 2, 3, 4],
[3, 4, 1, 2],
[1, 4, 2, 3],
[2, 3, 1, 4],
[1, 3, 2, 4],
[2, 4, 1, 3],
[1, 4, 3, 4],
[3, 4, 1, 4],
[1, 3, 3, 4],
]
run_cases(cases)
cases = [[to_dt(i) for i in j] for j in cases]
run_cases(cases)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment