Re-rank a feed with per-creator caps and a no-repeat window

Why it matters Feeds and marketplaces apply creator and seller caps after ranking to keep results fair and varied.

A feed ranked purely by score can show the same creator five times in a row. Business rules cap how often a creator appears and keep repeats apart.

Write rerank_with_caps(items, scores, creators, k, max_per_creator, window). items, scores and creators are parallel lists. Fill up to k slots greedily: at each slot, scan the remaining items by score descending (ties by smaller position in the input) and take the first one whose creator has fewer than max_per_creator picks so far AND does not equal the creator of any of the last window picks. If no remaining item qualifies, stop early. Return the list of picked items.

Signaturedef rerank_with_caps(items, scores, creators, k, max_per_creator, window)

Example

rerank_with_caps(["a", "b", "c", "d"], [0.9, 0.8, 0.7, 0.6], ["x", "x", "y", "x"], 4, 2, 1) gives ['a', 'c', 'b'].

Understand the idea

Ranking models score items one at a time, so they happily put five posts from the same creator at the top of a feed. Platforms add business rules after ranking: at most m items per creator, and no creator twice within a short window. The simplest way to apply them is greedy: fill each slot with the best item that does not break a rule.

Example: items a, b, c, d with creators x, x, y, x, cap 2 and window 1. Slot 1 takes a (x). Slot 2: b is x again, blocked by the window, so take c (y). Slot 3: b (x) is fine now. Slot 4: d would be a third x, over the cap, so the feed stops at [a, c, b].

Rule: pick argmax score among items with count(creator) < cap and creator not in the last w picks.

Feeds on social, video and shopping apps apply rules like these to keep results fair to creators and pleasant for users.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplererank_with_caps(['a', 'b', 'c', 'd'], [0.9, 0.8, 0.7, 0.6], ['x', 'x', 'y', 'x'], 4, 2, 1)
  • Sample 2: window tworerank_with_caps([1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1], ['p', 'p', 'q', 'q', 'r', 'p'], 6, 3, 2)