-
-
Save kolatat/7688779d2541886a44b8efd7607bbe0c 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(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