Created
September 22, 2020 18:56
-
-
Save adammichaelwood/b13e90ebaf99c3e376faf6258d82f60b to your computer and use it in GitHub Desktop.
Distance Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def distance_calculator(points): | |
""" Takes an ordered list of points (tuple), and returns the total path distance. | |
>>> points = [(-7,-3), (6,1), (4, 10), (2, -5), (-8, 5), (8, 3)] | |
>>> distance = distance_calculator(points) | |
>>> distance = round(distance, 2) | |
68.22 | |
""" | |
distance = 0 | |
for i, point in enumerate(points): | |
if not index_in_list(points, i+1): | |
break | |
next_point = points[i+1] | |
seg_dist = segment_distance(point, next_point) | |
distance = distance + seg_dist | |
return distance | |
def segment_distance(a, b): | |
"""Calculate the distance between a and b.""" | |
horizontal_distance = b[0] - a[0] | |
vertical_distance = b[1] - a[1] | |
h = horizontal_distance ** 2 | |
v = vertical_distance ** 2 | |
distance = math.sqrt(h+v) | |
return distance | |
def index_in_list(a_list, index): | |
return (index < len(a_list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment