Skip to content

Instantly share code, notes, and snippets.

@natebwangsut
Last active September 5, 2017 06:44
Show Gist options
  • Save natebwangsut/2aaf163e72ca9da4ec6afd1190a5bbc1 to your computer and use it in GitHub Desktop.
Save natebwangsut/2aaf163e72ca9da4ec6afd1190a5bbc1 to your computer and use it in GitHub Desktop.
Hello
import math
# distance formula
def distance(us, vs):
sum = 0
# enumerate over all xs and ys together
for (x, y) in zip(us, vs):
sum += (x-y) ** 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, loc[1:]), loc[0]])
# get the closest element up to k, then exit
outcome = []
for item in sorted(list):
if len(outcome) < k:
outcome.append(item[1])
else:
break
return outcome
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment