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

Python中三角形结构最大距离计算问题排查

三角形结构最大距离计算程序错误排查请求

我编写了一个程序,用于计算单个三角形或组合三角形结构能够离墙达到的最大距离。输入为一行正整数,格式如3 50 40 30:第一个整数为所用三角形边的数量,后续按降序排列的整数为边的长度。程序支持三角形共享边、连接顶点、任意旋转重叠等构建规则。

示例输入的计算结果为40,运行正常,但输入7 42 40 32 30 25 18 15时,预期结果为66.9495287,而代码计算结果为错误的39.9482860。

我的代码

import sys
import itertools
import numpy as np

def max_distance(n, lengths):
    max_dist = 0.0
    permutations = np.array(list(itertools.permutations(lengths)))

    for i in range(len(permutations)):
        perm = permutations[i]
        sides = np.array([perm[i:i+3] for i in range(n-2)])
        valid_triangles = sides[:, 0] < sides[:, 1] + sides[:, 2]
        valid_sides = sides[valid_triangles]

        for side in valid_sides:
            a, b, c = side
            s = (a + b + c) / 2
            area_squared = s * (s - a) * (s - b) * (s - c)

            # Ensure area_squared is positive before calculating height
            if area_squared > 0:
                height = 2 * np.sqrt(area_squared) / a
                max_dist = max(max_dist, height)

    if max_dist.is_integer():
        return str(int(max_dist))
    else:
        return format(max_dist, '.7f')

if __name__ == "__main__":
    input_data = sys.stdin.readline().strip().split()
    n = int(input_data[0])
    lengths = [int(x) for x in input_data[1:]]
   
    result = max_distance(n, lengths)
    print(result)

当前代码逻辑

函数max_distance接收参数n(边的数量)和长度列表,通过生成所有长度排列,检查有效三角形(满足最长边 < 另外两边之和),用海伦公式计算面积并推导高度,以此更新最大距离。我知晓代码未优化,但无法定位错误,恳请提供排查方向。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:22:48