KatInterview

Audit a Flawed Proximity-Search Module in Python

Data Structure DesignModel answer
MediumModel answerData Structure Designcode-reviewpythongeospatial

Last updated

Review a small Python module for finding and labeling nearby places, spotting correctness, speed and design problems, then propose and justify concrete refactors.

Review a proximity-search module

A teammate opened a pull request for a small Python module that returns places close to a given coordinate and looks up the city name for a coordinate. You are the reviewer. Here is the code:

import math

def find_nearby(listings, lat, lon, radius_km=5, results=[]):
    for l in listings:
        d = math.sqrt((l['lat'] - lat)**2 + (l['lon'] - lon)**2) * 111
        if d < radius_km:
            results.append(l)
    results.sort(key=lambda x: math.sqrt((x['lat']-lat)**2 + (x['lon']-lon)**2))
    return results

def get_city(lat, lon):
    resp = requests.get(f"https://geo.example/reverse?lat={lat}&lon={lon}")
    return resp.json()['city']

listings is a list of dicts with lat and lon in degrees. The service handles many queries per second against a large, mostly static set of listings.

What to deliver

  1. Review the code. Identify problems under four headings: correctness, performance, scalability, and readability/design. Mark each finding as a blocker, should-fix, or nit.
  2. Propose concrete fixes. Show rewritten code for the most important issues, not just names of techniques. Consider data structures, vectorization, caching, and module structure.
  3. Explain scaling. Describe how your approach changes at roughly 10 thousand, 10 million, and 1 billion points.
  4. Say how you would test it. Name the edge cases you would cover.

Talk through your review in a deliberate order, and justify the priority you give each item.