数据点是否在矩形内?

时间:2019-01-30 05:28:18

标签: python

编写一个函数isIn(),如果一个点在两组坐标指定的矩形内,则返回True;如果该点在矩形的外部,则返回False。该函数应接受三个参数:

  • 第一个参数是一组坐标,用于定义矩形的一个角,
  • 第二个参数也是定义第二个角的一组坐标
  • 第三组坐标定义了一个正在测试的点。

例如,

isIn((1,2), (3,4), (1.5, 3.2))应该返回True

isIn((4,3.5), (2,1), (3, 2))应该返回True

isIn((-1,0), (5,5), (6,0))应该返回False

isIn((4,1), (2,4), (2.5,4.5))应该返回False

除上述示例外,还至少使用2组不同的数据点来测试您的功能。

注意:

如果要测试的点在矩形的侧面,则认为它在矩形内。例如,如果矩形定义为(1,2), (3,4),而点为(2,2),则函数应返回True。 在此分配中,我们假设矩形的边缘与坐标轴平行。 我们还假设第一个参数并不总是代表矩形的左角,而第二个参数并不总是代表右角。该功能应以任何一种方式正常工作。请注意上面的第二个测试条件,其中第一个参数(4,3.5)代表右上角,第二个参数(2,1)代表左下角。

def isIn(firstCorner=(0,0), secondCorner=(0,0), point=(0,0)):

1 个答案:

答案 0 :(得分: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)))