akela43

общая площадь прямоугольников

Sep 11th, 2023 (edited)
962
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. from functools import reduce
  2. from itertools import combinations as comb
  3. from dataclasses import dataclass, astuple
  4.  
  5. @dataclass
  6. class Box:
  7.     x1:float
  8.     y1:float
  9.     x2:float
  10.     y2:float
  11.     # зануление координат если он неправильный или пустой
  12.     def __post_init__(self):
  13.         if self.x1 >= self.x2 or self.y1 >= self.y2:
  14.             self.x1 = self.y1 = self.x2 = self.y2 = 0
  15.     # находит прямоугольник-пересечение двух прямоугольников
  16.     def intersect(self, other):
  17.         if astuple(self) == (0,0,0,0) or astuple(other) == (0,0,0,0):
  18.             return Box(0,0,0,0)
  19.        
  20.         x1 = max(self.x1, other.x1)
  21.         x2 = min(self.x2, other.x2)
  22.         y1 = max(self.y1, other.y1)
  23.         y2 = min(self.y2, other.y2)
  24.         return Box(x1, y1, x2, y2)
  25.     #площадь прямоугольника
  26.     def S(self):
  27.         return (self.y2-self.y1)*(self.x2-self.x1)
  28.  
  29.     def __str__(self):
  30.         return f"{self.x1}, {self.y1} : {self.x2}, {self.y2}\n"
  31.    
  32.        
  33. A = Box(3, 3, 5, 5)
  34. B = Box(0, 0, 2, 5)
  35. C = Box(1, 2, 4, 4)
  36. D = Box(3, 1, 5, 4)
  37. E = Box(10, 1, 15, 2)
  38. lst = [D,B,C,A, E]
  39. res = 0;
  40. #по принципу включения-исключения из комбинаторики
  41. for i in range(len(lst)):
  42.     res += (-1)**i * sum(reduce(Box.intersect,  seq).S() for seq in comb(lst, i+1))
  43. print(res)
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment