用 Python 编写的查找多边形周长的程序

pythonserver side programmingprogramming更新于 2025/12/21 17:48:17

假设我们有一个有序点列表,表示二维平面上的简单多边形端点。我们必须找到这个多边形的周长。

因此,如果输入类似于 points = [(0, 0), (0,5), (3, 5), (3,0)],则输出将为 16,因为

两条边的长度为 3,两条边的长度为 5,因此 2*5 + 2*3 = 16。

为了解决这个问题,我们将遵循以下步骤 −

  • 定义一个函数 getInfo() 。这将取 x1、y1、x2、y2
  • 返回 ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) 的平方根,即欧几里得距离
  • (x1, y1) 和 (x2, y2) 之间
  • 从主方法中,执行以下操作
  • N := 点的大小
  • (firstx, firsty) := points[0]
  • (prevx, prevy) := (firstx, firsty)
  • res := 0
  • 对于范围为 1 到 N-1 的 i,执行
    • (nextx, nexty) := points[i]
    • res := res + getInfo(prevx, prevy, nextx, nexty)
    • prevx := nextx
    • prevy := nexty
  • res := res + getInfo(prevx, prevy, firstx, firsty)
  • 返回 res

示例

让我们看看下面的实现以便更好地理解 −

from math import sqrt
def getInfo(x1, y1, x2, y2):
   return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))

def solve(points):
   N = len(points)
   firstx, firsty = points[0]
   prevx, prevy = firstx, firsty
   res = 0

   for i in range(1, N):
      nextx, nexty = points[i]
      res = res + getInfo(prevx,prevy,nextx,nexty)
      prevx = nextx
      prevy = nexty
   res = res + getInfo(prevx,prevy,firstx,firsty)
   return res

points = [(0, 0), (0,5), (3, 5), (3,0)]
print(solve(points))

输入

[(0, 0), (0,5), (3, 5), (3,0)]

输出

16.0

相关文章


有用资源