确定两点之间形成的线是否与x轴或y轴交叉

时间:2019-02-07 09:37:56

标签: python geometry

我正在尝试执行此作业:

  

编写一个Python函数cross(),以确定该行是否   在(x1,y1)和(x2,y2)两点之间形成的点与x和/或   y轴。

     

该函数提示输入4个值-x1,y1,x2和y2。输出   以下消息之一:

Line crosses both x and y axes
Line crosses x axis only
Line crosses y axis only
Line does not cross both x and y axes

我阅读了讲义,但未涵盖此主题。有什么公式可以用来计算吗?

2 个答案:

答案 0 :(得分:1)

这应该非常简单,因为您只需要检查它是否横穿x轴或y轴即可。您只需检查自己的xy中是否有任何一个从正变负或从负变正。

def intersects_axis(v1, v2):
  return (v1 <= 0 <= v2 or v2 <= 0 <= v1)


def determine_intersections(x1, y1, x2, y2):

  print("Checking if {}, {} and {}, {} any axes".format(x1, y1, x2, y2))

  intersects_y = intersects_axis(y1, y2)
  intersects_x = intersects_axis(x1, x2)

  if intersects_y and intersects_x:
    print("Line crosses both x and y axes")
  elif intersects_y:
    print("Line crosses y axis only")
  elif intersects_x:
    print("Line crosses x axis only")
  else:
    print("Line does not cross both x and y axes")


if __name__ == "__main__":

  x1, y1 = 1, 1

  x2, y2 = 2, 2

  determine_intersections(x1, y1, x2, y2)

  x2, y2 = 1, -1

  determine_intersections(x1, y1, x2, y2)

  x2, y2 = -1, -1

  determine_intersections(x1, y1, x2, y2)

  x2, y2 = -1, 1

  determine_intersections(x1, y1, x2, y2)

哪个会给你:

Checking if 1, 1 and 2, 2 any axes
Line does not cross both x and y axes
Checking if 1, 1 and 1, -1 any axes
Line crosses y axis only
Checking if 1, 1 and -1, -1 any axes
Line crosses both x and y axes
Checking if 1, 1 and -1, 1 any axes
Line crosses x axis only

答案 1 :(得分:0)

问题真的出在段上,而不是线条上:一些简单的魔术

onClickHandler

(未指定在轴done()上具有端点的线段)