← All Python interview questions
Flag transaction outliers with the IQR rule
MediumStatisticsHDFCRazorpay
Risk wants transactions flagged when they fall outside the classic 1.5 x IQR fence.
Write flag_outliers(values) that takes a list of numbers and returns a list of the values that are below Q1 - 1.5*IQR or above Q3 + 1.5*IQR, in their original order.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import numpy as np
amounts = [120, 150, 130, 140, 135, 145, 125, 5000, 138, 142, 1, 133]- Step 1: `np.percentile(arr, [25, 75])` returns both quartiles in one pass, which is cheaper and less error-prone than two calls.
- Step 2: The interquartile range `q3 - q1` measures the spread of the middle half, so it is not dragged around by the extreme values you are hunting for.
- Step 3: The 1.5 multiplier is the conventional Tukey fence — quote it in interviews as a convention, not a law of nature.
- Step 4: Filtering the original list (not the array) preserves the input types and order the caller expects.
def flag_outliers(values):
arr = np.array(values, dtype=float)
q1, q3 = np.percentile(arr, [25, 75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
return [v for v in values if v < low or v > high]Learn the concept first
Stuck on Statistics? These free Python lessons teach it step by step.
More Statistics questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program