Recommend the next item from session transition counts

Why it matters Session-based recommenders for shopping and streaming start from transition counts before moving to sequence models.

Within a session, what a user views next depends strongly on what they just viewed. A first-order Markov model counts these transitions.

Write next_item_recs(sessions, last, k). sessions is a list of item lists in time order. Count every consecutive pair (a, b) with a != b across all sessions (direction matters: a then b). Return up to k items b with the highest count for a = last, ties by smaller id. Return [] if last has no outgoing transitions.

Signaturedef next_item_recs(sessions, last, k)

Example

next_item_recs([[1, 2, 3], [1, 2], [1, 3], [2, 1]], 1, 2) gives [2, 3].

Understand the idea

Someone who just looked at a phone is likely to look at a phone case next, not the other way round. A first-order Markov model captures this by counting, across many sessions, how often item b came right after item a. To recommend, look up the current item and return its most common followers.

Example: sessions [1, 2, 3], [1, 2], [1, 3] and [2, 1]. Transitions out of 1 are 1 to 2 (twice) and 1 to 3 (once). The pair 2 to 1 in the last session goes the other way and does not count for item 1. So after 1 we recommend [2, 3].

Rule: count(a, b) = number of adjacent pairs with a then b, a != b; recommend the top b for the current a.

Sequence models such as GRU or transformer recommenders learn richer versions of the same next-item signal.

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

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplenext_item_recs([[1, 2, 3], [1, 2], [1, 3], [2, 1]], 1, 2)
  • Sample 2: directionnext_item_recs([[5, 7], [9, 7], [9, 7], [7, 8]], 7, 3)
  • Test 3: self loopsnext_item_recs([[4, 4, 4, 6], [4, 6], [4, 5]], 4, 2)
  • Test 4: nonenext_item_recs([[1, 2]], 2, 3)