Start learning free

LESSON 183 OF 188 · BACKEND: INTERVIEW QUESTIONS

Autocomplete in Python

Practice

The interview question: "Design the endpoint behind a search box's suggestions." The expected answer: suggest the products whose name starts with what was typed, ignoring case, put the best sellers first, and send only a few (here, at most 5). Empty text gets an empty list, not the whole catalog.

Two Python tools do the work. startswith checks only the beginning of a string, and sort with a key function and reverse=True puts the biggest values first:

"steel bottle".startswith("te")    # False: "te" is only inside
"tea towel".startswith("te")       # True

def by_age(dog):
    return dog["age"]

dogs.sort(key=by_age, reverse=True)   # oldest dog first

Order matters: sort before you cut the list to 5, or you keep the first five found instead of the five best sellers.

Your code must give these answers:

GET /suggest?q=te   →  200  [{"name": "Tea towel", "sold": 75}, {"name": "Tea cups", "sold": 64},
                             {"name": "Teapot", "sold": 40}, {"name": "Teddy bear", "sold": 21},
                             {"name": "Tent", "sold": 12}]
GET /suggest?q=TEA  →  200  [{"name": "Tea towel", "sold": 75}, {"name": "Tea cups", "sold": 64},
                             {"name": "Teapot", "sold": 40}]
GET /suggest?q=Tel  →  200  [{"name": "Telescope", "sold": 3}]
GET /suggest?q=m    →  200  [{"name": "Mug", "sold": 55}]
GET /suggest?q=x    →  200  []
GET /suggest?q=     →  200  []
GET /suggest        →  200  []

Your task: PRODUCTS (each with a name and how many were sold) and by_sold are given, and text is already read from q, trimmed and lowercased. In suggest, answer an empty list when text is empty, collect the products whose lowercase name starts with text into matches, and sort them most sold first. The return jsonify(matches[:5]) is already there.


Assignment
Follow the Coding Tutorial to fill suggest: the check for empty text, the matching loop and the sort.


Hint
Every string starts with the empty string, so without the empty check q= would match every product. Lowercase the name only for the comparison, not the names in PRODUCTS.


STEP 1 OF 6
    Ctrl + Enter to check

    Bq Autocomplete in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free