Skip to main content

Given two lists of 0 and 1, the true labels and the predictions, compute precision, recall and F1 without a library. For example, labels 1, 1, 1, 0, 0 and predictions 1, 1, 0, 1, 0 give precision 2/3, recall 2/3 and F1 2/3.

Coding rounds · Intermediate 2

Short answer

Count true positives, false positives and false negatives in one pass. Precision is tp / (tp + fp), recall is tp / (tp + fn), and F1 is their harmonic mean, 2 * p * r / (p + r). Guard each division against a zero denominator. One pass, O(n) time and constant memory.

Deeper answer

Clarify first: are the lists the same length, which value is the positive class, and are the predictions already labels or scores that need a threshold? Ask what to return when a denominator is zero. Returning 0 is a common convention, but say it out loud.

Go through the two lists together. A pair (1, 1) adds to tp, a pair (0, 1) adds to fp, and a pair (1, 0) adds to fn. True negatives are not needed. Then precision = tp / (tp + fp), recall = tp / (tp + fn), and F1 = 2 * p * r / (p + r), which is the same as 2 * tp / (2 * tp + fp + fn). With NumPy a count is one line: tp = np.sum((y == 1) & (pred == 1)).

Test the worked example, a model that predicts no positives, and data with no positive labels. Interviewers watch for swapped fp and fn, for the plain average instead of the harmonic mean, and for a crash on zero division.

What a strong answer covers

Answer it out loud in the mock interview about 2 min

Follow-ups to expect

Common mistakes

Learn it

Choosing a metric

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.