Pick a Side, Move the Centre

Data with PythonHard+10 XP+10

Pick a Side, Move the Centre

A delivery company wants to split its customers between two depots, A and B. Each row of points is one customer's position, and centre_a and centre_b are the two depots' positions. Every position has the same number of coordinates.

It does this in two steps:

  1. Pick a side. Each customer goes to whichever depot is nearer, by straight-line distance. If both are exactly as near, the customer goes to A.
  2. Move the centre. Each depot moves to the average position of its own customers: the average of each coordinate, worked out separately. If a depot got no customers at all, it stays where it was.

Task: write two_centres(points, centre_a, centre_b) and return a dict:

  • "sides" — each customer's depot, "A" or "B", as a list in row order,
  • "new_a" — depot A's new position, as a list with every coordinate rounded to 3 decimal places,
  • "new_b" — depot B's new position, in the same way.

One tool you'll need: a mask with one True or False per row works inside square brackets on a grid too. grid[mask] keeps the whole rows whose position is True.

There is always at least one customer.

Examples

points = [[1, 1], [2, 1], [8, 9], [9, 8], [1, 2]]
centre_a = [0, 0]
centre_b = [10, 10]
returns {'sides': ['A', 'A', 'B', 'B', 'A'], 'new_a': [1.333, 1.333], 'new_b': [8.5, 8.5]}
points = [[0, 0], [4, 0], [2, 3]]
centre_a = [0, 0]
centre_b = [4, 0]
returns {'sides': ['A', 'B', 'A'], 'new_a': [1.0, 1.5], 'new_b': [4.0, 0.0]}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run