Best Position for a Service Centre LeetCode solution in Python

1
class Solution:
2
def getMinDistSum(self, positions: List[List[int]]) -> float:
3
n = len(positions)
4
if n == 1:
5
return 0
6

7
def gradient(x, y):
8
ans = [0, 0]
9
for i in range(n):
10
denom = math.sqrt(
11
pow(x - positions[i][0], 2) + pow(y - positions[i][1], 2)
12
)
13
ans[0] += (x - positions[i][0]) / denom if denom else 0
14
ans[1] += (y - positions[i][1]) / denom if denom else 0
15
return ans
16

17
def fn(x, y):
18
res = 0
19
for i in range(n):
20
res += math.sqrt(
21
pow(x - positions[i][0], 2) + pow(y - positions[i][1], 2)
22
)
23
return res
24

25
x = sum(x for x, _ in positions) / n
26
y = sum(y for _, y in positions) / n
27
lr = 1
28
while lr > 1e-7:
29
dx, dy = gradient(x, y)
30
x -= lr * dx
31
y -= lr * dy
32
lr *= 0.997
33
if not dx and not dy:
34
lr /= 2
35
return fn(x, y)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0