Home > Python >Python Exercise: Safest Positions

Safest Positions

Given n as an positive integer input, from a grid that starts from (0,0) and ends with (n, n), find all(one or many) safest points that is defined as to have the maximum sum of distances to a list of points given.
For Example:
Given n = 4, points = ((0,0), (4,4))
Return ((0, 4), (4, 0))

You need login to comment

Solution submitted by Dzeng at April 22, 2020, 12:43 a.m.
def safestpositions(n, points): pointlist = [] distance = 0 maxdistance = 0 safestpoints = [] for i in range (0, n+1): for t in range(0, n+1): pointlist.append((i, t)) for i in pointlist: for point in points: distance += ((i[0] - point[0])**2 + (i[1] - point[1])**2)**(1/2) print(distance) if distance > maxdistance: safestpoints = [] safestpoints.append((i, distance)) maxdistance = distance elif distance == maxdistance: safestpoints.append((i, distance)) distance = 0 return safestpoints print(safestpositions(8, [(0,0),(2,1),(6,7),(1, 7)]))

You need login to submit your solution