用 Python 查詢多邊形周長的程式
假設我們有一個有序點列表,其表示一個二維平面上的簡單多邊形端點。我們必須找出此多邊形的周長。
因此,如果輸入類似於 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 := points 的大小
- (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
廣告