python - 给定三个点的坐标,如何判断定义的三角形是等边、等腰还是不等边三角形?

标签 python geometry computational-geometry

我编写了以下代码,但我无法确定它是否识别等边三角形,因为我无法输入制作它所需的坐标(例如 3 的平方根):

x1 = eval(input('x1: '))
y1 = eval(input('y1: '))
x2 = eval(input('x2: '))
y2 = eval(input('y2: '))
x3 = eval(input('x3: '))
y3 = eval(input('y3: '))
side1 = (abs(x1 - x2) + abs(y1 - y2)) ** (1/2)
side2 = (abs(x2 - x3) + abs(y2 - y3)) ** (1/2)
side3 = (abs(x3 - x1) + abs(y3 - y2)) ** (1/2)
print('side1: ', side1, 'side2: ', side2,'side3:', side3)
if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2 :
    if side1 == side2 == side3:
        print('This triangle is equilateral')
    elif side1 == side2 or side2 == side3 or side1 == side3 :
        print('This triangle is isosceles')
    else:
        print('This triangle is scalene')
else:
    print('This is not a triangle!')

编辑:我重写了代码,如下

x1 = eval(input('x1: '))
y1 = eval(input('y1: '))
x2 = eval(input('x2: '))
y2 = eval(input('y2: '))
x3 = eval(input('x3: '))
y3 = eval(input('y3: '))
side1 = ((x1 - x2)**2 + (y1 - y2)**2) ** (1/2)
side2 = ((x2 - x3)**2 + (y2 - y3)**2) ** (1/2)
side3 = ((x3 - x1)**2 + (y3 - y1)**2) ** (1/2)
print('side1: ', side1, 'side2: ', side2,'side3:', side3)
if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2 :
    if side1 == side2 == side3:
        print('This triangle is equilateral')
    elif side1 == side2 or side2 == side3 or side1 == side3 :
        print('This triangle is isosceles')
    else:
        print('This triangle is scalene')
else:
    print('This is not a triangle!')

最佳答案

  • 由于您对坐标距离进行平方,因此不需要 abs
  • 您的 side3 的第二个 y 坐标是错误的:应该是 y1))。
  • 您对合法边的检查应包括相等性:边数为 2, 2, 4 给你一条直线,但你将它分类为等腰三角形。
  • 您可以使用ma​​th包来获得更易读的平方根。
  • 通过对边长进行排序可以节省一两步;这简化了 你的比较。

更新的代码:

from math import sqrt

x1 = float(raw_input('x1: '))
y1 = float(raw_input('y1: '))
x2 = float(raw_input('x2: '))
y2 = float(raw_input('y2: '))
x3 = float(raw_input('x3: '))
y3 = float(raw_input('y3: '))

side1 = sqrt((x1 - x2)**2 + (y1-y2)**2)
side2 = sqrt((x2 - x3)**2 + (y2-y3)**2)
side3 = sqrt((x3 - x1)**2 + (y3-y1)**2)

# Put the sides into a list; sort them.
tri= [side1, side2, side3]
tri.sort()

if tri[0] < tri[1]+tri[2]:
    if tri[0] == tri[2]:
        print('This triangle is equilateral')
    elif tri[1] == tri[2] or tri[1] == tri[0]:
        print('This triangle is isosceles')
    else:
        print('This triangle is scalene')
else:
    print('This is not a triangle!')

关于python - 给定三个点的坐标,如何判断定义的三角形是等边、等腰还是不等边三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37396046/

相关文章:

python - 菲茨 (ModuleNotFoundError : No module named 'frontend' ) error in docker

python - 将彩球放入垃圾箱的所有可能方法

c# - 我可以在 Python3 中使用不同的代码点吗?

用于在给定轴上旋转点的 C++ 库?

postgresql - 几何类型从数据库中读取为字符串

linear-algebra - 在 3D 中找到从点到截锥的最短向量

python - 如何解释 matchtemplate 输出? (开放式计算机,Python)

php - 如何检查给定的非凸区域是否与给定的矩形完全重叠

geometry - 如何计算任意三角形与正方形的相交面积?

algorithm - 给定一个带点的二维图,找到一条经过最多点的直线