You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python矩形判定与坐标处理代码问题求助:对角线计算及整数校验

坐标处理任务问题修复与功能增强

存在的问题

  • 对角线计算错误:输入A(0,0)、B(5,0)、C(0,5)、X(2,2)时,原代码输出对角线为5,实际应为√50≈7.07
  • 缺少坐标合法性校验:未校验文本文件中的坐标是否均为整数,遇到非整数坐标无法正确处理

修正后的完整代码

import math

def distance(point1, point2):
    return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)

def is_rectangle(point_a, point_b, point_c):
    # 用勾股定理判断矩形(允许浮点精度误差)
    dist_ab = distance(point_a, point_b)
    dist_bc = distance(point_b, point_c)
    dist_ca = distance(point_c, point_a)
    
    distances = sorted([dist_ab, dist_bc, dist_ca])
    # 短边平方和近似等于长边平方,且排除三点共线情况
    if abs(distances[0]**2 + distances[1]**2 - distances[2]**2) < 1e-9:
        return True
    return False

def get_rectangle_fourth_vertex(a, b, c):
    # 利用矩形对角线中点相同的性质,计算第四个顶点
    d_x = a[0] + c[0] - b[0]
    d_y = a[1] + c[1] - b[1]
    return (d_x, d_y)

def is_inside_rectangle(rectangle_points, point):
    x_coords = [p[0] for p in rectangle_points]
    y_coords = [p[1] for p in rectangle_points]
    # 保持原逻辑的开区间判断
    return (min(x_coords) < point[0] < max(x_coords)) and (min(y_coords) < point[1] < max(y_coords))

def read_coordinates(file_path):
    coordinates = []
    try:
        with open(file_path, 'r') as file:
            for line in file:
                stripped_line = line.strip().strip('()')
                x_str, y_str = stripped_line.split(',')
                x = int(x_str.strip())
                y = int(y_str.strip())
                coordinates.append((x, y))
        # 校验坐标数量是否为4个
        if len(coordinates) != 4:
            return None
        return coordinates
    except (ValueError, IndexError):
        # 捕获非整数、格式错误等异常
        return None

# 主执行逻辑
coords = read_coordinates('coordinates.txt')
if not coords:
    print("False")
else:
    a, b, c, x = coords
    if is_rectangle(a, b, c):
        d = get_rectangle_fourth_vertex(a, b, c)
        rectangle = [a, b, c, d]
        if is_inside_rectangle(rectangle, x):
            diagonal_length = distance(a, d)
            print("True")
            print(f"Diagonal of the rectangle is: {diagonal_length:.2f}")
        else:
            print("False")
    else:
        print("False")

修改说明

  1. 修复对角线计算错误:
    原代码错误地将B点与X点的距离作为候选对角线,现在通过矩形顶点性质算出第四个顶点,再计算正确的对角线长度(矩形两条对角线长度相等)。
  2. 添加坐标整数校验:
    新增read_coordinates函数,读取时尝试将坐标转换为整数,遇到非整数、格式错误或坐标数量不足4个时,直接输出False。
  3. 优化矩形判断逻辑:
    改用勾股定理结合浮点误差判断,避免因浮点精度问题导致的误判,同时排除三点共线的无效情况。
  4. 完善矩形边界完整性:
    新增get_rectangle_fourth_vertex函数,补全矩形的第四个顶点,确保判断点是否在内部时使用完整的矩形边界。

内容的提问来源于stack exchange,提问作者user24663593

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:20:51