简体   繁体   中英

Common Points in an array of rectangles

Deveoping a function that finds a common intersection between an array of rectangles however the method return False when it should be true. The function calls to the intersect function in the class rectangle. Any suggestions.

Class Rectangle:
    def intersects(self, other):
        """Return true if a rectangle intersects the other rectangle."""
        return (self.top_right.x > other.bottom_left.x and self.bottom_left.x <     other.top_right.x and self.bottom_left.y < other.top_right.y and self.top_right.y > other.bottom_left.y)

Class Many_Rect:
    def common_point(self):
        value = False
        for i in range(len(self.rectangles) - 2):
            for j in range(len(self.rectangles) - 1, -1, -1):
                if self.rectangles[i].intersects(self.rectangles[j]) == True:
                    value = True
                else:
                    return False
        return True

Part of your problem is because in your code as soon as any rectangle doesn't intersect your function returns False - but it shouldn't return False unless none of the rectangles intersect. However if two rectangles do intersect then you can return True as soon as that is found because there is no point checking any more. Your code should look like this:

def common_point(self):
    for i in range(len(self.rectangles) - 1):
        for j in range(i+1,len(self.rectangles)):
            if self.rectangles[i].intersects(self.rectangles[j])
                # these rectangles intersect - no point checking any more
                return True
    # none of the rectangles intersect
    return False

I'm not sure why you use len(self.rectangles)-2 as the range for i - I think this should be -1. Also j should range between i+1 up to len(self.rectangles), otherwise when i==j you will always get an intersection. I've incorporated these changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM