Advertisement
acclivity

pyIntersectionOfRectangles

Apr 4th, 2021
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. # Find the intersection rectangle of two given rectangles.
  2. # Mike Kerry - April 2021 - [email protected]
  3.  
  4.  
  5. def FindIntersection(recta, rectb):
  6.     # Compute bottom left point of intersection rectangle
  7.     cx1 = max(recta[0][0], rectb[0][0])
  8.     cy1 = max(recta[0][1], rectb[0][1])
  9.  
  10.     # Compute top right point of intersection rectangle
  11.     cx2 = min(recta[1][0], rectb[1][0])
  12.     cy2 = min(recta[1][1], rectb[1][1])
  13.  
  14.     # Is there any intersection?
  15.     if cx1 > cx2 or cy1 > cy2:
  16.         print("No intersection")
  17.         return None
  18.     return [(cx1, cy1), (cx2, cy2)]       # Bottom Left and Top Right coords of intersection
  19.  
  20.  
  21. # Mainline code
  22. r1 = [(0, 0), (5, 5)]      # coordinates of bottom left and top right of 1st rectangle
  23. r2 = [(3, 3), (7, 7)]      # coordinates of bottom left and top right of 2nd rectangle
  24.  
  25. intersect = FindIntersection(r1, r2)
  26.  
  27. if intersect:
  28.     print("Intersection Rectangle is:", intersect)
  29.     lenx = abs(intersect[0][0] - intersect[1][0])
  30.     leny = abs(intersect[0][1] - intersect[1][1])
  31.     perim = 2 * (lenx + leny)
  32.     print("Perimeter of Intersection Rectangle is:", perim, "units")
  33.     area = lenx * leny
  34.     print("Area of Intersection Rectangle is:", area, "square units")
  35. else:
  36.     print("There is no intersection")
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement