Trips That Don't Fit the Box

Data ProcessingMedium+20 XP+20

Trips That Don't Fit the Box

A bike-share company is cleaning a column of trip durations, in minutes, before training a model to predict how long trips take. A few entries look wrong: a 2-minute trip that is probably someone re-docking a bike, a 240-minute trip from a bike that was never returned properly. Rather than judge them by eye, the team applies the standard IQR rule.

  1. Quartiles. Sort the durations and split the sorted list into a lower half and an upper half. If the count is odd, the middle value (the median) goes into neither half. Q1Q_1Q1​ is the median of the lower half and Q3Q_3Q3​ is the median of the upper half. The median of an even-sized list is the average of its two middle values.
  2. Fences. With IQR=Q3−Q1IQR = Q_3 - Q_1IQR=Q3​−Q1​:
lower fence=Q1−1.5×IQR,upper fence=Q3+1.5×IQR\text{lower fence} = Q_1 - 1.5 \times IQR, \qquad \text{upper fence} = Q_3 + 1.5 \times IQRlower fence=Q1​−1.5×IQR,upper fence=Q3​+1.5×IQR
  1. Flag. A trip is an outlier if its duration is outside the fences: below the lower fence or above the upper fence. A duration exactly on a fence is kept.

Task: write iqr_fences(durations) and return a tuple (lower_fence, upper_fence, flagged):

  • the two fences, each rounded to 4 decimal places;
  • flagged, the positions of the outlier trips in the original durations list, in increasing order. If there are none, it's an empty list.

durations holds at least 4 numbers, in the order the trips were logged, not sorted.

The fences are built from Q1Q_1Q1​ and Q3Q_3Q3​, which one wild value barely moves. That's why this rule is often preferred over the z-score rule, whose mean and standard deviation get dragged around by the very outliers they are supposed to catch.

Interquartile Range Explorer

Visualize quartile construction, the middle 50%, outlier resistance, and box plots.

Build Quartiles

Start with the unsorted dataset. The first step toward finding quartiles is to sort the data in ascending order.

7
1
5
3
6
2
4
Step 1 of 8

Examples

durations = [14, 9, 22, 11, 58, 13, 16, 12]
returns (0.25, 30.25, [4])
durations = [31, 27, 2, 30, 29, 33, 28, 45, 26]
returns (18.25, 40.25, [2, 7])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run