Created
August 1, 2022 18:51
-
-
Save willmcgugan/8d161a6b1104aa2b79b6656893d4055d to your computer and use it in GitHub Desktop.
lru_cache is fast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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