In [10]:
# Procedural approach
import math
def perimeter(polygon):
"""Given a list of vector vertices (in proper order),
returns the perimeter for the associated polygon."""
total = 0
for i in range(len(polygon)):
vertex1 = polygon[i]
vertex2 = polygon[(i+1) % len(polygon)]
distance = math.sqrt((vertex2[0] - vertex1[0]) ** 2
+ (vertex2[1] - vertex1[1]) ** 2)
total += distance

In [18]:
perimeter([[0, 0], [1, 0], [1, 1], [0, 1]]) # a square with sides of length 1

Out[18]:
4.0
In [19]:
vertices = [[0, -2], [1, 1], [3, 3], [5, 1], [4, 0], [4, -3]]
perimeter(vertices) # a more complex shape

Out[19]:
17.356451097651515
In [20]:
# just for illustration, let's see what this polygon looks like
%matplotlib inline
from matplotlib import pyplot as plt
vertices.append(vertices[0]) #so that we draw a line back to the beginning
plt.plot([val[0] for val in vertices], [val[1] for val in vertices])

Out[20]:
[<matplotlib.lines.Line2D at 0x7f026fcd50d0>]
In [14]:
# Object-Oriented approach

class Polygon:
"""A new class named Polygon."""

def __init__(self, vertices):
self.vertices = vertices
print("(Creating an instance of the class Polygon)")

def perimeter(self):
total = 0
for i in range(len(self.vertices)):
vertex1 = self.vertices[i]
vertex2 = self.vertices[(i+1) % len(self.vertices)]
distance = math.sqrt((vertex2[0] - vertex1[0]) ** 2
+ (vertex2[1] - vertex1[1]) ** 2)
total += distance

a = Polygon([[0, -2], [1, 1], [3, 3], [5, 1], [4, 0], [4, -3]])

(Creating an instance of the class Polygon)

17.356451097651515