
- 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 area 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 area of this polygon.
So, if the input is like points = [(0, 0), (0,5), (3, 5), (3,0)], then the output will be 15.
To solve this, we will follow these steps −
- Define a function getInfo() . This will take x1, y1, x2, y2
- return x1*y2 - y1*x2
- 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| / 2.0
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 res = res + getInfo(prevx,prevy,firstx,firsty) return abs(res)/2.0 points = [(0, 0), (0,5), (3, 5), (3,0)] print(solve(points))
Input
[(0, 0), (0,5), (3, 5), (3,0)]
Output
15.0
- Related Articles
- Program to find perimeter of a polygon in Python
- C++ Program to implement Slicker Algorithm that avoids Triangulation to find Area of a Polygon
- Python Program to find the area of a circle
- How to fill an area within a polygon in Python using matplotlib?
- Program to find area of largest island in a matrix in Python
- Area of a n-sided regular polygon with given Radius in C Program?
- Python Program to Find the Area of a Rectangle Using Classes
- Program to reset a polygon to its initial state in Python
- Program to find area of largest square of 1s in a given matrix in python
- Area of largest Circle inscribe in N-sided Regular polygon in C Program?
- Area of largest Circle inscribed in N-sided Regular polygon in C Program?
- Program to find the Circumcircle of any regular polygon in C++
- Program to find area of largest submatrix by column rearrangements in Python
- JavaScript program to find area of a circle
- Program to find largest rectangle area under histogram in python

Advertisements