Program to find best position for a service center in Python

Suppose we have a list of positions containing coordinate points where houses are located. We want to find the optimal location (xc, yc) for a service center such that the sum of Euclidean distances from all houses to the service center is minimized. This is known as the geometric median problem.

So, if the input is like positions = [(10,11),(11,10),(11,12),(12,11)], then the output will be 4.0

X Y (10,11) (11,10) (11,12) (12,11) Optimal Service Center

Algorithm Overview

We use ternary search to find the optimal position. This technique works because the sum of distances function is unimodal (has a single minimum) ?

  • Apply ternary search on x-coordinate

  • For each x, apply ternary search on y-coordinate

  • Calculate total Euclidean distance for each candidate position

  • Return the minimum distance found

Implementation

from math import sqrt

def solve(positions):
    numIter = 50

    def total(cx, cy, positions):
        total = 0.0
        for p in positions:
            x, y = p
            total += sqrt((cx - x) * (cx - x) + (cy - y) * (cy - y))
        return total

    def fy(x, positions):
        l, r = 0, 101
        res = 0
        for i in range(numIter):
            y1 = l + (r - l) / 3
            y2 = r - (r - l) / 3
            t1 = total(x, y1, positions)
            t2 = total(x, y2, positions)
            res = min(t1, t2)
            if t1 < t2:
                r = y2
            else:
                l = y1
        return res

    def fx(positions):
        l, r = 0, 101
        res = 0
        for i in range(numIter):
            x1 = l + (r - l) / 3
            x2 = r - (r - l) / 3
            t1 = fy(x1, positions)
            t2 = fy(x2, positions)
            res = min(t1, t2)
            if t1 < t2:
                r = x2
            else:
                l = x1
        return res

    return fx(positions)

positions = [(10,11),(11,10),(11,12),(12,11)]
print(solve(positions))
4.0

How It Works

The algorithm uses ternary search which divides the search space into three parts ?

  • total() - Calculates sum of Euclidean distances from point (cx, cy) to all houses

  • fy() - Finds optimal y-coordinate for a given x using ternary search

  • fx() - Finds optimal x-coordinate using ternary search

Key Points

  • Time Complexity: O(numIter²) where numIter = 50

  • Space Complexity: O(1) auxiliary space

  • Search Range: [0, 101] covers typical coordinate ranges

  • Precision: 50 iterations provide sufficient accuracy for most cases

Conclusion

This solution uses ternary search to find the geometric median of given points. The nested ternary search approach efficiently locates the optimal service center position with minimum total distance to all houses.

Updated on: 2026-03-26T14:06:46+05:30

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements