LearnCoding

Out-of-time train/test split

EasyLeakage, Evaluation, Time series

Problem

Given row timestamps and test_fraction: - Let n = len(timestamps) and k = floor(n·(1 − test_fraction)). - If k ≥ n, everything is train. - Otherwise cutoff is the k-th smallest timestamp (0-based, in sorted order). Train is all indices with timestamp < cutoff; test is all indices with timestamp ≥ cutoff. This guarantees no timestamp appears on both sides. Return (train_indices, test_indices), each ascending.

Signature

def time_split(timestamps: list[int], test_fraction: float) -> tuple[list[int], list[int]]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> time_split([5,1,4,2,3], 0.4) == ([1, 3, 4], [0, 2])
True

>>> time_split([1,2,2,2,3], 0.4) == ([0], [1, 2, 3, 4])
True

Solve it in your own editor; nothing on this page runs code.

Hints

Sort timestamps, compute the k-th cutoff.

k = floor(n * (1 - test_fraction)); if k >= n, everything is train.

Train is everything < cutoff, test is everything >= cutoff — ties must fall on one side.

Reference solution

import math

def time_split(timestamps, test_fraction):
    n = len(timestamps)
    if n == 0:
        return [], []
    s = sorted(timestamps)
    k = int(math.floor(n * (1 - test_fraction) + 1e-12))
    if k >= n:
        return list(range(n)), []
    cutoff = s[k]
    train = [i for i, t in enumerate(timestamps) if t < cutoff]
    test = [i for i, t in enumerate(timestamps) if t >= cutoff]
    return train, test

What a strong solution covers

  • Splits on time, not rows, and keeps ties on one side.
  • Handles empty input and the fractions 0 and 1.
  • Discusses adding a gap or embargo for delayed labels, and group-aware splits.

Common mistakes

  • a random shuffle split
  • splitting at a row position so equal timestamps fall on both sides.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.