Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Area of a Convex Polygon by EnCuKou
def checkio(points):
"""Return the area of a convex polygon"""
# Sum areas of the parallelograms (x1, 0)-(x1, y1)-(x2,y2)-(x2,0)
# for each line (x1,y1)-(x2,y2) in the polygon
# (not forgetting the line from last point to the first)
# If x1 > x2 (the parallelogram "goes backwards"), use "negative area"
# This should work for concave polygons too!
return abs(sum(
(x1 - x2) * (y1 + y2) / 2
for (x1, y1), (x2, y2)
in zip(points, [points[-1]] + points[:-1])))
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[1, 1], [9, 9], [9, 1]]) == 32, "The half of the square"
assert checkio([[4, 10], [7, 1], [1, 4]]) == 22.5, "Triangle"
assert checkio([[1, 2], [3, 8], [9, 8], [7, 1]]) == 40, "Quadrilateral"
assert checkio([[3, 3], [2, 7], [5, 9], [8, 7], [7, 3]]) == 26, "Pentagon"
assert checkio([[7, 2], [3, 2], [1, 5],
[3, 9], [7, 9], [9, 6]]) == 42, "Hexagon"
assert checkio([[4, 1], [3, 4], [3, 7], [4, 8],
[7, 9], [9, 6], [7, 1]]) == 35.5, "Heptagon"
May 23, 2013
Comments: