Program to find area of a polygon in Python

Suppose we have a list of ordered points that represents a simple polygon on a 2D plane. We need to find the area of this polygon using the Shoelace formula (also known as the surveyor's formula).

So, if the input is like points = [(0, 0), (0, 5), (3, 5), (3, 0)], then the output will be 15.

(0,0) (0,5) (3,5) (3,0) X Y

How the Shoelace Formula Works

The Shoelace formula calculates the area of a polygon by summing cross products of consecutive vertices. For each pair of consecutive points (x?, y?) and (x?, y?), we calculate x? × y? ? y? × x?.

Algorithm Steps

To solve this, we follow these steps ?

  • Define a helper function to calculate cross product between two points
  • Initialize variables for the first point and running sum
  • Iterate through consecutive point pairs
  • Add cross product of the last point with the first point to close the polygon
  • Return the absolute value divided by 2

Example

Let us see the following implementation to get better understanding ?

def getInfo(x1, y1, x2, y2):
    return x1 * y2 - y1 * x2

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 = res + getInfo(prevx, prevy, nextx, nexty)
        prevx = nextx
        prevy = nexty
    
    # Close the polygon by connecting last point to first
    res = res + getInfo(prevx, prevy, firstx, firsty)
    return abs(res) / 2.0

# Test with a rectangle
points = [(0, 0), (0, 5), (3, 5), (3, 0)]
area = solve(points)
print(f"Area of polygon: {area}")
Area of polygon: 15.0

Alternative Implementation

Here's a more compact version using Python's built?in functions ?

def polygon_area(points):
    n = len(points)
    area = 0
    
    for i in range(n):
        j = (i + 1) % n  # Next vertex (wraps to 0 for last vertex)
        area += points[i][0] * points[j][1]
        area -= points[j][0] * points[i][1]
    
    return abs(area) / 2.0

# Test with different polygons
rectangle = [(0, 0), (0, 5), (3, 5), (3, 0)]
triangle = [(0, 0), (4, 0), (2, 3)]

print(f"Rectangle area: {polygon_area(rectangle)}")
print(f"Triangle area: {polygon_area(triangle)}")
Rectangle area: 15.0
Triangle area: 6.0

Key Points

Aspect Description
Formula Shoelace formula: ½|?(x?y??? ? x???y?)|
Time Complexity O(n) where n is number of vertices
Space Complexity O(1) additional space
Requirements Points must be ordered (clockwise or counterclockwise)

Conclusion

The Shoelace formula provides an efficient way to calculate polygon area using coordinate geometry. The algorithm works by summing cross products of consecutive vertices and handles both convex and concave polygons as long as vertices are ordered correctly.

Updated on: 2026-03-26T15:40:03+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements