0

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
mhawke
  • 84,695
  • 9
  • 117
  • 138
Stephanie
  • 47
  • 5
  • Did you already add some output lines in order to see what might be wrong? By the way, you have writen a function intersects with two arguments, while you launch it only with one. Is everything OK there? – Dominique Dec 07 '15 at 08:31
  • I have ran outputs, still can't see to find problem. And yes it is cause the first argument is considered the class variable being testing so self is one argument and than self.rectangles represents other @Dominique – Stephanie Dec 07 '15 at 08:43
  • I hope you've written some test cases - have you tested whether your code thinks that two identical rectangles intersect? – DisappointedByUnaccountableMod Dec 07 '15 at 09:37

1 Answers1

0

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.