title: Intersection and difference of two rectangles
body: <p>Searching the internet has not given a satisfactory solution for the following problem. Given a class <code>Rectangle</code> defined as the following:</p>
  
  <pre><code>class Rectangle:
  
      def __init__(self, x1, y1, x2, y2):
          if x1 &gt; x2 or y1 &gt; y2:
              raise ValueError('coordinates are invalid')
          self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2
  
      @property
      def width(self):
          return self.x2 - self.x1
  
      @property
      def height(self):
          return self.y2 - self.y1
  
      def bounds(self, other):
          return Rectangle(min(self.x1, other.x1), min(self.y1, other.y1),
                           max(self.x2, other.x2), max(self.y2, other.y2))
  
      def intersect(self, other):
          return self.x1 &lt; other.x2 and self.x2 &gt; other.x1 and \
                 self.y1 &lt; other.y2 and self.y2 &gt; other.y1
  </code></pre>
  
  <p><em>How would you create a method to get the intersection and a generator to get the difference of two rectangles?</em> Presumably, a more complete implementation of the following methods are needed, but it is not clear to me what should be written.</p>
  
  <pre><code>def __and__(self, other):
      if self.intersect(other):
          # return a new rectangle that provides
          # the intersection between self and other
      return None
  
  def __sub__(self, other):
      take_away = self &amp; other
      if take_away is None:
          return self
      if take_away is self:
          return None
      return self.get_partitions(take_away)
  
  def get_partitions(self, take_away):
      # yield 1 or 3 rectangles that are not part of take_away
      # alternative:
      # yield 1 or 2 overlapping rectangles not part of take_away
  </code></pre>
  
  <p>Does anyone have an elegant implementation for these methods? My hope is to avoid writing code for every conceivable case that might be encountered.</p>