Overlapping co-ordiantes of rectangles fail to print in python

arunsocs at gmail.com arunsocs at gmail.com
Thu Nov 17 09:27:49 EST 2016


 I am working with following code in which I am trying to output co ordinates of overlapping rectangles.. However the code fails to output the co ordinates. I am customizing the following code This is the input

1.6 1.2 7.9 3.1
1.2 1.6 3.4 7.2
2.6 11.6 6.8 14.0
9.6 1.2 11.4 7.5
9.6 1.7 14.1 2.8 

This is the code:

from __future__ import division
from collections import namedtuple
from itertools import combinations

Point = namedtuple( 'Point', ['x','y'] )

class Rectangle:
    def __init__( self, coordinates ):
        self.min = Point( coordinates[0], coordinates[1] )
        self.max = Point( coordinates[2], coordinates[3] )

    @property
    def center( self ):
        return Point( (self.max.x + self.min.x)/2, (self.max.y + self.min.y)/2 )

    @property
    def area( self ):
        return (self.max.x - self.min.x) * (self.max.y - self.min.y)

    def intersect( self, otherRect ):
        x_vals = sorted([self.max.x, self.min.x, otherRect.max.x, otherRect.min.x])
        y_vals = sorted([self.max.y, self.min.y, otherRect.max.y, otherRect.min.y])

        possibleIntersections = []
        intersections = []

        for i in range(3):
            for j in range(3):
                possibleIntersections.append( Rectangle([x_vals[i], y_vals[j], x_vals[i+1], y_vals[j+1]]) )

        for r in possibleIntersections:
            if self.contains( r.center ) and otherRect.contains( r.center ) and r.area > 0:
                intersections.append( r )

        return intersections

    def contains( self, point ):
        return self.min.x <= point.x and point.x <= self.max.x and self.min.y <= point.y and point.y <= self.max.y

    def __repr__( self ):
        return '[{0},{1}]'.format( self.min, self.max )

def readInputconvert( filename ):
    rects = []
    with open(filename,'r') as f:
        count = int(f.readline().rstrip());

        for _ in range( count ):
            rects.append( Rectangle( map( float, f.readline().rstrip().split(' ') ) ) )

    return rects

rectangles = readInputconvert( 'input.txt' ) # read input

sign = -1
area = sum( map( lambda x: x.area, rectangles) )

for i in range(2,len(rectangles)+1):
    for rects in combinations( rectangles, i ):
        intersections = [rects[0]]
        rects = rects[1:]
        for rectangle in rects:
            newintersections = []
            for otherR in intersections:
                newintersections.extend( rectangle.intersect(otherR) )

            intersections = newintersections
            print intersections

        #intersectingArea = sum( map( lambda x: x.area, intersections ) )
        #rea = area + (sign * intersectingArea)

    sign = sign*-1

Where I need to change the code to output all overlapping rectangles and its co ordinates?



More information about the Python-list mailing list