Cho danh sách đỉnh points của đa giác đơn giản theo thứ tự. Tính chu vi = tổng khoảng cách Euclid giữa các đỉnh liên tiếp (kể cả đoạn nối đỉnh cuối về đỉnh đầu).
Ví dụ: [(0,0), (0,5), (3,5), (3,0)] → chu vi 16 (2 cạnh 3 + 2 cạnh 5).
Ví dụ mã nguồn
from math import sqrt
def getInfo(x1, y1, x2, y2):
return sqrt((x1-x2)**2 + (y1-y2)**2)
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 += getInfo(prevx, prevy, nextx, nexty)
prevx, prevy = nextx, nexty
res += getInfo(prevx, prevy, firstx, firsty)
return res
points = [(0, 0), (0, 5), (3, 5), (3, 0)]
print(solve(points)) # 16.0
Đầu vào / Đầu ra
Input: [(0, 0), (0,5), (3, 5), (3,0)]
Output: 16.0