# Point in Polygon in Python

Posted: , Last Updated:

``````def point_in_polygon(polygon, point):
"""
Raycasting Algorithm to find out whether a point is in a given polygon.
Performs the even-odd-rule Algorithm to find out whether a point is in a given polygon.
This runs in O(n) where n is the number of edges of the polygon.
*
:param polygon: an array representation of the polygon where polygon[i][0] is the x Value of the i-th point and polygon[i][1] is the y Value.
:param point:   an array representation of the point where point[0] is its x Value and point[1] is its y Value
:return: whether the point is in the polygon (not on the edge, just turn < into <= and > into >= for that)
"""

# A point is in a polygon if a line from the point to infinity crosses the polygon an odd number of times
odd = False
# For each edge (In this case for each point of the polygon and the previous one)
i = 0
j = len(polygon) - 1
while i < len(polygon) - 1:
i = i + 1
# If a line from the point into infinity crosses this edge
# One point needs to be above, one below our y coordinate
# ...and the edge doesn't cross our Y corrdinate before our x coordinate (but between our x coordinate and infinity)

if (((polygon[i][1] > point[1]) != (polygon[j][1] > point[1])) and (point[0] < (
(polygon[j][0] - polygon[i][0]) * (point[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1])) +
polygon[i][0])):
# Invert odd
odd = not odd
j = i
# If the number of crossings was odd, the point is in the polygon
return odd
``````

# Point in Polygon Algorithm

The Point in Polygon (PIP) problem is the problem of determining whether a point is any arbitrary polygon. This might sound trivial for a simple polygon like a square or a triangle, but gets more complex with more complex polygons like the one in the example below. In this post, the even-odd algorithm, also called crossing number algorithm or Jordan’s algorithm (since it can be proven using the Jordan curve theorem), will be introduced.

## Description of the Algorithm

The basic principle behind the Even-odd aka. Jordan aka. Cross Number Algorithm is to count the number of times a line from the point in question (in any, arbitrary direction) crosses any edge of the polygon. This line will always be outside of the polygon at it’s “end” in infinity, so if it is inside the polygon at the start (the point in question), it will have to leave the polygon at some point, crossing some edge. It can re-enter the polygon (see the example below), but it always has to leave again, making the total number of crossings uneven if the point is in the polygon. The opposite is also true; if the number of crossings is even, the point is always outside of the polygon. This is the above mentioned Jordan’s curve theorem.

The algorithm checks every edge of the polygon in a loop to determine if the line from the point to infinity crosses it. In the example below, this line is drawn from the point to infinity to the right, but it can be any direction.

The steps are:

1. For each edge in the polygon:
2. If the edge crosses the imaginary line from the point to infinity, increase a counter.
3. At then end, if the counter is uneven, return true. Else, return false.

A simple boolean variable that is inverted every time a crossing is found is also possible.

## Example of the Algorithm

Consider the following polygon with 8 edges and two points for which we want to determine whether they are in the polygon:

The steps the algorithm performs on this polygon to determine whether the first (green) point is in the polygon are, starting from the first edge:

1. Green Point crosses edge 8
2. Green Point does not cross edge 1
3. Green Point crosses edge 2
4. Green Point does not cross edge 3
5. Green Point crosses edge 4
6. Green Point crosses edge 5
7. Green Point does not cross edge 6
8. Green Point does not cross edge 7
9. Total number of crossings: 4
10. Even number of edge crossings, therefore the point is not in the polygon

The steps the algorithm performs on this polygon to determine whether the second (red) point is in the polygon are, starting from the first edge:

1. Red Point does not cross edge 8
2. Red Point does not cross edge 1
3. Red Point does not cross edge 2
4. Red Point does not cross edge 3
5. Red Point does not cross edge 4
6. Red Point crosses edge 5
7. Red Point does not cross edge 6
8. Red Point does not cross edge 7
9. Total number of crossings: 1
10. Uneven number of edge crossings, therefore the point is in the polygon

## Runtime Complexity of the Algorithm

The runtime complexity of the Jordan Algorithm aka. Crossing Number Algorithm aka. Even-Odd Algorithm to solve the point-in-polygon problem for a single point is linear with respect to the number of edges. This is evident by looking at the code, which contains a single loop over the edges, with no recursion or further function calls or loops.

Formally the runtime is O(|V|), |V|:=number of edges in the polygon.

## Space Complexity of the Algorithm

The space complexity is also linear w.r.t. the number of edges, since only fixed-size variables need to be stored in addition to the polygon. Additionally, the algorithm can be implemented on-line, meaning there is no need to look at past edges during the loop, so they can be evicted from memory (or comparable performance improvement measures).

Point in Polygon Algorithm in other languages:

# Python

Python™ is an interpreted language used for many purposes ranging from embedded programming to web development, with one of the largest use cases being data science.

## Getting to “Hello World” in Python

The most important things first - here’s how you can run your first line of code in Python.

1. Download and install the latest version of Python from python.org. You can also download an earlier version if your use case requires it - many technologies still require it due to the breaking changes introduced with Python 3.
2. Open a terminal, make sure the `python` or `python3` command is working, and that the command your’re going to be using is referring to the version you just installed by running `python3 --version` or `python --version`. If you’re getting a “command not found” error (or similar), try restarting your command line, and, if that doesn’t help, your computer. If the issue persists, here are some helpful StackOverflow questions for Windows, Mac and Linux.
3. As soon as that’s working, you can run the following snippet: `print("Hello World")`. You have two options to run this: 3.1 Run `python` in the command line, just paste the code snippet and press enter (Press `CTRL + D` or write `exit()` and press enter to exit). 3.2 Save the snippet to a file, name it something ending with `.py`, e.g. `hello_world.py`, and run `python path/to/hello_world.py`. Tip: use the `ls` command (`dir` in Windows) to figure out which files are in the folder your command line is currently in.

That’s it! Notice how printing something to the console is just a single line in Python - this low entry barrier and lack of required boilerplate code is a big part of the appeal of Python.

## Fundamentals in Python

To understand algorithms and technologies implemented in Python, one first needs to understand what basic programming concepts look like in this particular language.

### Variables and Arithmetic

Variables in Python are really simple, no need to declare a datatype or even declare that you’re defining a variable; Python knows this implicitly.

``````a = 1
b = {'c':2}

print(a + b['c']) # prints 3``````

### Arrays

Working with arrays is similarly simple in Python:

``````arr = ["Hello", "World"]

print(arr[0]) # Hello
print(arr[1]) # World
# print(arr[2]) # IndexError

arr.append("!")

print(arr[2]) # !``````

As those of you familiar with other programming language like Java might have already noticed, those are not native arrays, but rather lists dressed like arrays. This is evident by the fact that no size needs to be specified, and elements can be appended at will. In fact, `print(type(arr))` prints `<class 'list'>`. This means that arrays in Python are considerably slower than in lower level programming languages. There are, however, packages like numpy which implement real arrays that are considerably faster.

### Conditions

Just like most programming languages, Python can do `if-else` statements:

``````value = 1
if value==1:
print("Value is 1")
elif value==2:
print("Value is 2")
else:
print("Value is something else")``````

Python does however not have `case`-statements that other languages like Java have. In my opinion, this can be excused by the simplicity of the `if`-statements which make the “syntactic sugar” of `case`-statements obsolete.

### Loops

Python supports both `for` and `while` loops as well as `break` and `continue` statements. While it does not have `do-while` loops, it does have a number of built-in functions that make make looping very convenient, like ‘enumerate’ or `range`. Here are some examples:

``````value = 10
while value > 0:
print(value)
value -= 1

for index, character in enumerate("banana"):
print("The %d-th letter is a %s" % (index + 1, character))``````

Note that Python does not share the common iterator-variable syntax of other languages (e.g. `for(int i = 0; i < arr.length; i++)` in Java) - for this, the `enumerate` function can be used.

### Functions

Functions in Python are easily defined and, for better or worse, do not require specifying return or arguments types. Optionally, a default for arguments can be specified:

``````def print_something(something="Hello World"):
print(something)
return "Success"

print_something()
print(print_something("banana"))``````

(This will print “Hello World”, “Banana”, and then “Success”)

### Syntax

As you might have noticed, Python does not use curly brackets (`{}`) to surround code blocks in conditions, loops, functions etc.; This is because Python depends on indentation (whitespace) as part of its syntax. Whereas you can add and delete any amount of whitespace (spaces, tabs, newlines) in Java without changing the program, this will break the Syntax in Python. This also means that semicolons are not required, which is a common syntax error in other languages.