题目:
here is a convex polygon on a coordinate plane. This polygon is presented as a list of vertices coordinates. Each vertex is connected sequentially with the last connecting back to the first. A polygon has N vertices. You should write a program that will calculate the area of a polygon. The result should be given with one digits precision as ±0.1.
Example:
checkio([[1, 1], [9, 9], [9, 1]]) == 32
checkio([[4, 10], [7, 1], [1, 4]]) == 22.5
checkio([[1, 2], [3, 8], [9, 8], [7, 1]]) == 40
checkio([[3, 3], [2, 7], [5, 9], [8, 7], [7, 3]]) == 26
checkio([[7, 2], [3, 2], [1, 5],
[3, 9], [7, 9], [9, 6]]) == 42
checkio([[4, 1], [3, 4], [3, 7], [4, 8],
[7, 9], [9, 6], [7, 1]]) == 35.5
链接:
https://py.checkio.org/en/mission/area-of-a-convex-polygon/
代码:
def checkio(data):
def san(x):
a = x[2][1] - x[1][1]
b = -(x[2][0] - x[1][0])
c = (x[2][0] - x[1][0])*x[2][1] - (x[2][1] - x[1][1])*x[2][0]
x0 = x[0][0]
y0 = x[0][1]
l1 = (a*x0+b*y0+c)/(a**2+b**2)**0.5
l2 = (a**2+b**2)**0.5
s = 0.5*l1*l2
if s > 0:
s = s
else:
s = -s
return round(s, 1)
x = data
m = []
for i in range(1, len(x)-1):
m.append([x[0], x[i], x[i+1]])
ss = 0
for i in m:
ss += san(i)
return ss