'Is a data point within a rectangle?
Write a function isIn() which returns True if a point is within a rectangle specified by two sets of coordinates and False if the point is outside the rectangle. The function should accept three parameters:
- the first parameter is a set of coordinates which defines one of the corners of the rectangle,
- the second parameter is also a set of coordinates that defines the second corner,
- the third set of coordinates defines a single point which is being tested.
For example,
isIn((1,2), (3,4), (1.5, 3.2)) should return True,
isIn((4,3.5), (2,1), (3, 2)) should return True,
isIn((-1,0), (5,5), (6,0)) should return False,
isIn((4,1), (2,4), (2.5,4.5)) should return False.
Test your function with at least 2 different sets of data points in addition to the examples above.
NOTES:
If the point being tested is on the side of the rectangle, consider it to be within the rectangle. For example, if the rectangle is defined as (1,2), (3,4) and the point is (2,2), the function should return True.
In this assignment, we assume that the edges of the rectangle are parallel to coordinate axes.
We also assume that the first parameter does not always represent the left corner of the rectangle and the second parameter is not always the right corner. The function should work correctly either way. Please note the second test condition above where the first parameter, (4,3.5), represents the top-right corner and the second parameter, (2,1), represents left-bottom corner.
def isIn(firstCorner=(0,0), secondCorner=(0,0), point=(0,0)):
Solution 1:[1]
#function to check if a point lies in rectangle
def isIn(firstCorner=(0,0),secondCorner=(0,0),point=(0,0)):
#assign values to variables
x1,y1=firstCorner[0],firstCorner[1]
x2,y2=secondCorner[0],secondCorner[1]
x,y=point[0],point[1]
#A point lies inside or not the rectangle
#if and only if it’s x-coordinate lies
#between the x-coordinate of the given bottom-right
#and top-left coordinates of the rectangle
#and y-coordinate lies between the y-coordinate of
#the given bottom-right and top-left coordinates.
if (x >= x1 and x <= x2 and y >= y1 and y <= y2) :
return True
#alternate case if coordinates are in reverse order
elif(x >= x2 and x <= x1 and y >= y2 and y <= y1):
return True
else:
return False
#testing the function
print(isIn((1,2),(3,4),(1.5,3.2)))
print(isIn((4,3.5),(2,1),(3,2)))
print(isIn((-1,0),(5,5),(6,0)))
print(isIn((4,1),(2,4),(2.5,4.5)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
