Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Area of a Convex Polygon by clems71130
import math
class Vec2(object):
def __init__(self, x=0.0, y=0.0):
self.x = float(x)
self.y = float(y)
def __add__(self, o):
return Vec2(self.x + o.x, self.y + o.y)
def __sub__(self, o):
return Vec2(self.x - o.x, self.y - o.y)
def __div__(self, o):
return Vec2(self.x / o, self.y / o)
def __repr__(self):
return 'Vec2(%.2f, %.2f)' % (self.x, self.y)
def abs(self):
return math.sqrt(self.x * self.x + self.y * self.y)
def triangle_area(va, vb, vc):
a = (va - vb).abs()
b = (vb - vc).abs()
c = (vc - va).abs()
s = (a + b + c) / 2.0
return math.sqrt(s * (s - a) * (s - b) * (s - c))
def checkio(data):
data = [Vec2(*v) for v in data]
last = data[1]
area = 0.0
for i in data[2:]:
area += triangle_area(data[0], last, i)
last = i
return area
#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 24, 2013