5 Best Ways to Program to Find Perimeter of a Polygon in Python

Rate this post

πŸ’‘ Problem Formulation: Determining the perimeter of a polygon is a fundamental geometric problem, which involves calculating the sum length of all the sides of the polygon. For instance, given the coordinates of a pentagon’s vertices, the goal is to compute the total distance around its five edges. This article explores various Python methods to achieve this, each helpful depending on the polygon information available and the required code compactness.

Method 1: Using Polygon Vertex Coordinates

Incalculating the perimeter using vertex coordinates, this method relies on computing the distance between successive vertices of the polygon. The function accepts a list of tuples representing the vertices’ coordinates, and the distance between consecutive vertex pairs is summed to find the total perimeter.

Here’s an example:

def find_perimeter(coordinates):
    perimeter = 0
    for i in range(len(coordinates)):
        next_index = (i + 1) % len(coordinates)
        side_length = ((coordinates[next_index][0] - coordinates[i][0]) ** 2 + (coordinates[next_index][1] - coordinates[i][1]) ** 2) ** 0.5
        perimeter += side_length
    return perimeter

# Example usage:
polygon_vertices = [(1,1), (1,6), (4,9), (9,6), (9,1)]
print(find_perimeter(polygon_vertices))

Output: 26.870057685088806

This Python function find_perimeter iteratively goes through the list of vertex coordinates, computes the Euclidean distance between each pair of consecutive vertices, and adds it to the accumulated perimeter. The modulus operator returns to the first vertex after reaching the end of the list, ensuring that the last side of the polygon is properly calculated.

Method 2: Using object-oriented programming (OOP)

If you prefer an OOP approach, you can create a Polygon class that stores the vertices and has a method to calculate the perimeter. This encapsulates the perimeter calculation within an object, which can be particularly handy when dealing with multiple polygons or complex geometrical applications.

Here’s an example:

class Polygon:
    def __init__(self, vertices):
        self.vertices = vertices
    
    def find_perimeter(self):
        perimeter = 0
        for i in range(len(self.vertices)):
            next_index = (i + 1) % len(self.vertices)
            side_length = ((self.vertices[next_index][0] - self.vertices[i][0]) ** 2 + (self.vertices[next_index][1] - self.vertices[i][1]) ** 2) ** 0.5
            perimeter += side_length
        return perimeter

# Example usage:
polygon = Polygon([(1,1), (1,6), (4,9), (9,6), (9,1)])
print(polygon.find_perimeter())

Output: 26.870057685088806

The Polygon class contains a constructor to initialize the vertices and a find_perimeter method which calculates the perimeter in the same way as Method 1. This approach not only calculates the perimeter but does so in an object-oriented fashion that might integrate more seamlessly into larger systems.

Method 3: Using the Shapely Library

For a more high-level approach, the Shapely library in Python allows for the simple creation of geometric objects and has built-in methods to calculate properties like length, area, and perimeter. This method simplifies the code as it delegates the geometric computations to the Shapely library.

Here’s an example:

from shapely.geometry import Polygon

# Define the coordinates of the polygon's vertices
coordinates = [(1,1), (1,6), (4,9), (9,6), (9,1)]
shape = Polygon(coordinates)

# Calculate the perimeter
perimeter = shape.length
print(perimeter)

Output: 26.870057685088806

Here, a Shapely Polygon object is instantiated using the vertices, and its length attribute is accessed to obtain the perimeter. This method abstracts the details of geometry calculations, providing a rather extensive suite of geometrical operations out-of-the-box.

Method 4: Using numpy for Vectorized Operations

For polygons with a large number of vertices or when performance is crucial, using numpy for vectorized operations can significantly speed up the computation. This method leverages numpy’s robust array processing capabilities to calculate the distances between points.

Here’s an example:

import numpy as np

def find_perimeter_np(coordinates):
    coords = np.array(coordinates)
    rolled_coords = np.roll(coords, -1, axis=0)
    distances = np.sqrt(np.sum((coords - rolled_coords) ** 2, axis=1))
    return np.sum(distances)

# Example usage:
polygon_vertices = np.array([(1,1), (1,6), (4,9), (9,6), (9,1)])
print(find_perimeter_np(polygon_vertices))

Output: 26.870057685088806

This code uses numpy’s array and roll functions to manipulate the list of vertices as arrays, computing the Euclidean distances in a vectorized manner. This allows the function to be more efficient, particularly when dealing with a large number of vertices, thanks to numpy’s optimized array operations.

Bonus One-Liner Method 5: Using List Comprehension and sum()

A very compact way to achieve the perimeter calculation is to use Python’s list comprehension feature combined with the built-in sum() function. This one-liner is Pythonic and demonstrates the language’s ability to condense operations into a single readable line.

Here’s an example:

polygon_vertices = [(1,1), (1,6), (4,9), (9,6), (9,1)]
print(sum(((polygon_vertices[i][0] - polygon_vertices[(i+1)%len(polygon_vertices)][0]) ** 2 + (polygon_vertices[i][1] - polygon_vertices[(i+1)%len(polygon_vertices)][1]) ** 2) ** 0.5 for i in range(len(polygon_vertices))))

Output: 26.870057685088806

This one-liner computes the perimeter by iterating over the indices of the polygon’s vertex list, calculating the distance for each side and summing them up. It offers a concise way to write a function without sacrificing readability.

Summary/Discussion

  • Method 1: Using Polygon Vertex Coordinates. Strengths: Simple, straightforward, doesn’t require external libraries. Weaknesses: Can be verbose with complex shapes.
  • Method 2: Using object-oriented programming (OOP). Strengths: Encapsulates polygon data and operations, useful for object-oriented designs. Weaknesses: Slightly more complex than functional approach.
  • Method 3: Using the Shapely Library. Strengths: Abstracts away the complexity of geometric calculations, provides additional geometric functionality. Weaknesses: Requires an external library, not built-in.
  • Method 4: Using numpy for Vectorized Operations. Strengths: Highly efficient for large datasets, leverages fast array processing. Weaknesses: Overkill for small datasets, requires numpy installation.
  • Bonus Method 5: Using List Comprehension and sum(). Strengths: Very compact and Pythonic. Weaknesses: Can be less readable for those unfamiliar with list comprehensions.