Last active
September 5, 2017 06:44
-
-
Save natebwangsut/2aaf163e72ca9da4ec6afd1190a5bbc1 to your computer and use it in GitHub Desktop.
Hello
This file contains 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 | |
# 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