In: Computer Science
(Area of a convex polygon)
A polygon is convex if it contains any line segment that connects
two points of the polygon. Write a program that prompts the user to
enter the number of points in a convex polygon, then enter the
points clockwise, and display the area of the polygon.
Sample Run
Enter the number of points: 7
Enter the coordinates of the points:
-12 0 -8.5 10 0 11.4 5.5 7.8 6 -5.5 0 -7 -3.5 -5.5
The total area is 244.575
# (X[i], Y[i]) are coordinates of i'th point.
def polygonArea(X, Y, n):
# Initialze area
area = 0.0
# Calculate value of shoelace formula
j = n - 1
for i in range(0, n):
area += (X[j] + X[i]) * (Y[j] - Y[i])
j = i # j is previous vertex to i
# Return absolute value
return float(abs(area / 2.0))
#Taking number of points from user
points = int(input("Enter the number of points: "))
#Taking coordinates as a string
coordinates = input("Enter the coordinates of the points:\n")
#Splitting coordinates using split function and converting into list
cords = list(coordinates.split(" "))
X=[]
Y=[]
#Appending values into x and y lists
for i in range(len(cords)):
if i%2==0:
X.append(float(cords[i]))
else:
Y.append(float(cords[i]))
n = len(X)
print(polygonArea(X, Y, n))
Sample input and output:
Enter the number of points: 7
Enter the coordinates of the points:
-12 0 -8.5 10 0 11.4 5.5 7.8 6 -5.5 0 -7 -3.5 -5.5
244.575
#If you have any doubts please leave comment, THANK YOU.