
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find perimeter of a polygon in Python
Suppose we have a list of ordered points represents a simple polygon endpoint on a 2D plane. We have to find the perimeter of this polygon.
So, if the input is like points = [(0, 0), (0,5), (3, 5), (3,0)], then the output will be 16 because
two sides are of length 3 and two sides are of length 5, so 2*5 + 2*3 = 16.
To solve this, we will follow these steps −
- Define a function getInfo() . This will take x1, y1, x2, y2
- return square root of ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) which is Euclidean distance
- between (x1, y1) and (x2, y2)
- From the main method, do the following
- N := size of points
- (firstx, firsty) := points[0]
- (prevx, prevy) := (firstx, firsty)
- res := 0
- for i in range 1 to N-1, do
- (nextx, nexty) := points[i]
- res := res + getInfo(prevx, prevy, nextx, nexty)
- prevx := nextx
- prevy := nexty
- res := res + getInfo(prevx, prevy, firstx, firsty)
- return res
Example
Let us see the following implementation to get better understanding −
from math import sqrt def getInfo(x1, y1, x2, y2): return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) 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 res = res + getInfo(prevx,prevy,firstx,firsty) return res points = [(0, 0), (0,5), (3, 5), (3,0)] print(solve(points))
Input
[(0, 0), (0,5), (3, 5), (3,0)]
Output
16.0
- Related Articles
- Program to find area of a polygon in Python
- Find the perimeter of a cylinder in Python Program
- Python Program for Find the perimeter of a cylinder
- Program to find the perimeter of an island shape in Python
- Program to find largest perimeter triangle using Python
- JavaScript program to find perimeter of a triangle
- Java Program to find the perimeter of a cylinder
- Java Program to Find the Perimeter of a Rectangle
- Java Program to Find the Perimeter of a Circle
- Swift Program to Find the Perimeter of a Circle
- Swift Program to Find the Perimeter of a Rectangle
- Haskell Program to Find the Perimeter of a Circle
- Kotlin Program to Find the Perimeter of a Rectangle
- Kotlin Program to Find the Perimeter of a Circle
- Program to reset a polygon to its initial state in Python

Advertisements