Created
May 7, 2018 12:39
-
-
Save aoloe/dd7830382d386512a065e4da5b3b64f2 to your computer and use it in GitHub Desktop.
Python: Find the distance between points
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
#!/usr/bin/env python3 | |
import math | |
from itertools import accumulate | |
from functools import reduce | |
points = [(1,2), (2,1), (5,3)] | |
# points = [[1,2], [2,1], [5,3]] | |
print(points) | |
def distance(a: tuple, b: tuple): | |
dx = a[0] - b[0] | |
dy = a[1] - b[1] | |
return math.sqrt(dx**2 + dy**2) | |
print('0 -> 1: '+ str(distance(points[0], points[1]))) | |
# print(distance("12", "21")) | |
# first creatae a list of distances and then find the minimal one | |
d = [distance(a, b) for i, a in enumerate(points) for j, b in enumerate(points) if i != j] | |
print('min: ' + str(min(d))) | |
# walk through the list of all point pairs and keep the minimal distance (max = 1000) | |
d = [(a, b) for i, a in enumerate(points) for j, b in enumerate(points) if i != j] | |
print('min reduce: ' + str(reduce(lambda m, a: min(m, distance(a[0], a[1])), d, 1000))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment