Skip to content

Instantly share code, notes, and snippets.

@aoloe aoloe/main.py
Created May 7, 2018

Embed
What would you like to do?
Python: Find the distance between points
#!/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
You can’t perform that action at this time.