In: Computer Science
In Python Create a function called ℎ?????. The function has as arguments a list called ?????? and a list call center. • List ?????? contains lists that represent points. o For example, if ?????? = [[4,2], [3,2], [6,1]], the list [4,2] represents the point with coordinate ? at 4 and y coordinate at 2, and so on for the other lists. Assume that all lists within points contain two numbers (that is, they have x, y coordinates). • List ?????? contains two numbers that also represent a point. o For example, ?????? = [3,3] represents the point with coordinate ? at 3 and with coordinate y at 3. • The function must return the point in points closest to center according to the distance calculated using the formula: ???????e = | ?2 - ?1| + | ?2 - ?1| o For example, if ?????? = [[4,2], [3,2], [6,1]] and ?????? = [3,3], then the function must return [3,2] (note that according to the formula the distance between the points is:
▪ |4 − 3| + |2 − 3| = 2
▪ |3 − 3| + |3 − 3| = 1
▪ |6 − 3| + |1 − 3| = 5
Code:
def hattan(points,center):
# calculating all the distances between each points and center
dist = ([abs(item[0]-center[0]) + abs(item[1]-center[1]) for item in points])
# getting the position of minimum value in the list
minpos = dist.index(min(dist))
return(points[minpos]) # returning points at minimum index
points = [[4,2], [3,2], [6,1]]
center = [3,3]
print('Requied points: ',hattan(points,center))
Output:
for any doubts, please comment below.