#!/usr/bin/env python # coding: utf-8 # 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 return total # In[18]: perimeter([[0, 0], [1, 0], [1, 1], [0, 1]]) # a square with sides of length 1 # In[19]: vertices = [[0, -2], [1, 1], [3, 3], [5, 1], [4, 0], [4, -3]] perimeter(vertices) # a more complex shape # In[20]: # just for illustration, let's see what this polygon looks like get_ipython().run_line_magic('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]) # 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 return total # In[17]: a = Polygon([[0, -2], [1, 1], [3, 3], [5, 1], [4, 0], [4, -3]]) a.perimeter() # In[ ]: