In: Computer Science
How do I write a script for this in python in REPL or atom, NOT python shell
Consider the following simple “community” in Python . . .
triangle = [
["top", [0, 1]], ["bottom-left", [0, 0]], ["bottom-right", [2,
0]],
]
This is the calling of function. >>> nearestneighbor([0, 0.6], triangle, myeuclidean) 'top'
The new point is (0, 0.6) and the distance function is Euclidean. Now let’s confirm this result . . .
>>> myeuclidean([0, 0.6], [0, 1])
0.4
>>> myeuclidean([0, 0.6], [0, 0])
0.6
>>> myeuclidean([0, 0.6], [2, 0])
2.08806130178211
Code Without Snippet:
# Implementation of myeuclidean function
def myeuclidean(point,point_):
# Calculation Euclidean Distance
distance = ((point[0]-point_[0])**2) +
((point[1]-point_[1])**2)
distance = distance**(1/2)
return distance
# Implementation of Nearest Neighbours
def nearestneighbor(point,triangle,myeuclidean):
distances=[]
# Calling myeuclidean for each point of
triangle
for i in range(0,len(triangle)):
distances.append(myeuclidean(point,triangle[i][1]))
# Finding out the minimum distance point
index
minimum_distance_position =
distances.index(min(distances))
return triangle[minimum_distance_position][0]
# Main Function
if __name__=="__main__":
# Traingle Variable
triangle = [ ["top", [0, 1]], ["bottom-left", [0, 0]],
["bottom-right", [2, 0]] ]
# Function Call
print(nearestneighbor([0, 0.6], triangle,
myeuclidean))
Code With Snippet:
Input and Output Snippet:
Note:
Thank you!!!