Skip to content

Instantly share code, notes, and snippets.

@kolatat
Forked from natebwangsut/k_clostest.py
Created September 5, 2017 05:57
Show Gist options
  • Save kolatat/7688779d2541886a44b8efd7607bbe0c to your computer and use it in GitHub Desktop.
Save kolatat/7688779d2541886a44b8efd7607bbe0c to your computer and use it in GitHub Desktop.
Hello
import math
# distance formula
def distance(x, y):
sum = 0
# enumerate over all xs and ys together
for (xs, ys) in zip(x,y):
sum += ((xs-ys) ** 2)
return math.sqrt(sum)
# find the k(th) closest location from the place
def k_closest(place, k, location):
# calculate all distance and add it into list
list = []
for loc in location:
list.append(distance(place, location[1:]), location[0])
# from the list, obtain all places and append the distance (if more than 2)
dict = {}
for i in range(len(list)):
if list[i][0] in dict:
dict[list[i][0]].append(list[i][1])
else:
dict[list[i][0]] = list[i][1]
# given a dictionary of items, return a list up to k(th) closest places
outcome = []
for item in sorted(dict.items()):
for settings in i[1]:
outcome.append(settings)
return outcome[:k]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment