Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Test If Point is in Rectangle

I am new to python and still learning the ropes but I am hoping someone with more experience can help me out.

I am trying to write a python script that:

  1. creates four points
  2. creates four rectangles
  3. check if each of the point is in any of the rectangles then write out the results to a output file.

The problem involves two data structures Point and Rectangle class. I have already started to create the Point class and Rectangle classes. Rectangle class should hold relevant data sets created from random module’s random method. As you can tell from my attempts that I am kind of all over the place but I have used #comments to try to get what I am trying to do.

Specific questions I have are:
1) how can I get this script working?
2) What variables or functions am I missing to generate random rectangles and see if specific points are in those rectangles?

## 1. Declare the Point class
class Point:
    def __init__(self,x = 0.0, y = 0.0): 
        self.x = x 
        self.y = y
    pass
## 2. Declare the Rectangle class 
class Rectangle: 
    def __int__(self): ## A rectangle can be determined aby (minX, maxX) (minY, maxY) 
        self.minX = self.minY = 0.0 
        self.maxX = self.maxY = 1.0 
    def contains(self, point): ## add code to check if a point is within a rectangle 
        """Return true if a point is inside the rectangle."""
        # Determine if a point is inside a given polygon or not
        # Polygon is a list of (x,y) pairs. This function
        # returns True or False. 
    def point_in_poly(x,y,poly):
        n = len(poly)
        inside = False
        p1x,p1y = poly[0]
        for i in range(n+1):
            p2x,p2y = poly[i % n]
            if y > min(p1y,p2y):
                if y <= max(p1y,p2y):
                    if x <= max(p1x,p2x):
                        if p1y != p2y:
                            xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
            p1x,p1y = p2x,p2y
        return inside
## 3. Generate four points 
##define a Point list to keep four points 
points = []
##add codes to generate four points and append to the points list
polygon = [(0,10),(10,10),(10,0),(0,0)]
point_x = 5
point_y = 5

## 4. Generate four rectangles 
##define a Rectangle list 
rects = [] 
for i in range(4):
    rectangle = Rectangle() 
    ## Generate x 
    x1 = random.random() 
    x2 = random.random() 
    ## make sure minX != maxX 
    while(x1 == x2): 
        x1 = random.random() 
    if x1<x2: 
        rectangle.minX=x1 
        rectangle.maxX=x2 
    elif x1>x2:
        rectangle.minX=x2
        rectangle.maxX=x1
    rects.append(rectangle)
    ## Develop codes to generate y values below 
    ## make sure minY != maxY 
    while(y1 == y2):
        y1 = random.random()
    if y1<y2:
        rectangle.minY=y1
        rectangle.maxY=y2
    elif y1>y2:
        recetangle.minY=y2
        racetangle.maxY=y1
    ## add to the list 
    rects.append(rectangle)

## 5. Add code to check which point is in which rectangle 
resultList = [] ## And use a list to keep the results 
for i in range(4):
    for j in range(4):
        if points[i] in rectangle[j]:
            print i

# write the results to file
f=open('Code5_4_1_Results.txt','w') 
for result in resultList:
    f.write(result+'\n') 
f.close()
like image 607
Geonerd Avatar asked Jul 09 '15 14:07

Geonerd


2 Answers

This is pretty simple math. Given a rectangle with points (x1,y1) and (x2,y2) and assuming x1 < x2 and y1 < y2 (if not, you can just swap them), a point (x,y) is within that rectangle if x1 < x < x2 and y1 < y < y2. Since Python comparison operators can be chained, this is even valid Python code which should produce the correct result (in other languages you'd have to write something like x1 < x and x < x2, etc).

If you want, you can use <= instead of <. Using <= means points on the boundary of the rectangle (eg, the point (x1,y1)) count as being inside it, while using < so means such points are outside it.

like image 56
celticminstrel Avatar answered Nov 14 '22 23:11

celticminstrel


It is better to write a separate function to do the job. Here's my function. You can just copy it if you want

def pointInRect(point,rect):
    x1, y1, w, h = rect
    x2, y2 = x1+w, y1+h
    x, y = point
    if (x1 < x and x < x2):
        if (y1 < y and y < y2):
            return True
    return False
like image 43
Hzzkygcs Avatar answered Nov 14 '22 22:11

Hzzkygcs