k-fold cross-validation rotates which block of the data is held out. Work out the blocks the way libraries do it without shuffling.
What to build
A program that lists the test block and training size of every fold.
Requirements
- Items are numbered 1 to n. The folds are consecutive blocks: the first
n % kfolds haven // k + 1items, the restn // k. - For each fold print
fold i: test A-B, train T, where A and B are the first and last test items and T the number of training items. - If a fold has a single item, print just that number instead of
A-B.
Input
One line: n and k.
Output
k lines.
Constraints
2 ≤ k ≤ n ≤ 10⁶.
Example
Input:
10 3
Output:
fold 1: test 1-4, train 6
fold 2: test 5-7, train 7
fold 3: test 8-10, train 7
Why it works
Giving the extra items to the first folds makes all folds as equal as possible, and each item is in the test block of exactly one fold.
Examples
Example 1 · Input
10 3
Expected output
fold 1: test 1-4, train 6 fold 2: test 5-7, train 7 fold 3: test 8-10, train 7
Example 2 · Input
4 4
Expected output
fold 1: test 1, train 3 fold 2: test 2, train 3 fold 3: test 3, train 3 fold 4: test 4, train 3
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Every fold has n // k items, and the first n % k folds get one extra.
Hint 2
Keep a running start position: each fold takes the next block of items.
Solution
Show one correct solution (try it yourself first)
n, k = map(int, input().split())
start = 1
for i in range(k):
size = n // k + (1 if i < n % k else 0)
end = start + size - 1
block = f"{start}" if size == 1 else f"{start}-{end}"
print(f"fold {i + 1}: test {block}, train {n - size}")
start = end + 1