Skip to content

Instantly share code, notes, and snippets.

@willmcgugan
Created August 1, 2022 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willmcgugan/8d161a6b1104aa2b79b6656893d4055d to your computer and use it in GitHub Desktop.
Save willmcgugan/8d161a6b1104aa2b79b6656893d4055d to your computer and use it in GitHub Desktop.
lru_cache is fast
@lru_cache(maxsize=4096)
def intersection(self, region: Region) -> Region:
"""Get the overlapping portion of the two regions.
Args:
region (Region): A region that overlaps this region.
Returns:
Region: A new region that covers when the two regions overlap.
"""
# Unrolled because this method is used a lot
x1, y1, w1, h1 = self
cx1, cy1, w2, h2 = region
x2 = x1 + w1
y2 = y1 + h1
cx2 = cx1 + w2
cy2 = cy1 + h2
rx1 = cx2 if x1 > cx2 else (cx1 if x1 < cx1 else x1)
ry1 = cy2 if y1 > cy2 else (cy1 if y1 < cy1 else y1)
rx2 = cx2 if x2 > cx2 else (cx1 if x2 < cx1 else x2)
ry2 = cy2 if y2 > cy2 else (cy1 if y2 < cy1 else y2)
return Region(rx1, ry1, rx2 - rx1, ry2 - ry1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment