Home โ€บ Interview Questions โ€บ Implement the compute_avg_k function to calculate โ€ฆ

Implement the compute_avg_k function to calculate the mean Average Precision (MAP) across all queries.

๐ŸŸก Medium Coding Mid level
1Times asked
Jul 2026Last seen
Jul 2026First seen

๐Ÿ’ก Model Answer

Mean Average Precision (MAP) is the mean of the Average Precision (AP) scores for each query. For a single query, AP is calculated by iterating through the ranked list of retrieved items, keeping a running count of relevant items seen so far. At each position k where the item is relevant, compute precision@k = (number of relevant items retrieved up to k) / k. Sum all precision@k values for relevant items and divide by the total number of relevant items for that query. The MAP is then the average of these AP values across all queries.

Algorithm:

  1. For each query:

a. Initialize relevant_seen = 0, sum_precisions = 0.

b. For each rank k in the ranked list:

  - If item at k is relevant, increment relevant_seen.
  - If relevant_seen > 0, add (relevant_seen / k) to sum_precisions.

c. If there are relevant items, AP = sum_precisions / total_relevant; else AP = 0.

  1. MAP = (sum of APs) / number_of_queries.

Complexity: O(total number of retrieved items) time and O(1) extra space per query. This implementation is straightforward in Python or any language and scales linearly with the size of the ranked lists.

This answer was generated by AI for study purposes. Use it as a starting point โ€” personalize it with your own experience.

๐ŸŽค Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI โ€” Starts at โ‚น500