Joel Stevick

The Python readiness check · 60 minutes · 2 tasks

Python for RAG coding test practice

Developers applying for a role that builds retrieval-augmented generation (RAG): the same difficulty as mid-level, with tasks on the data a RAG pipeline and its eval harness handle.

A new test every time, written by Claude, like the screens on HackerRank, CodeSignal and Codility: 60 minutes, 2 tasks, hidden tests that score it and a review of your code. Your first Python for RAG test is free; after that $5 a test, or $19 for five.

As hard as the mid-level test, on RAG work instead of general Python. It tests what the Python tutorial for RAG teaches.

The topics

Chunking text, Keyword scoring, Ranking and fusion, Widening a chunk, Vectors and cosine similarity, JSON and JSON Lines records, Scoring an eval, Dataclasses, Decorators, Async with asyncio, Error handling.

A sample task: Fuse search rankings

A task from this level, whole, as the test shows it. Your test is a new one, written for you.

Write fuse(rankings, k=60, limit=10), the reciprocal rank fusion step of a search pipeline that merges the results of several searches (a keyword search and a vector search, say) into one list.

rankings is a list of rankings. Each ranking is a list of chunk ids (strings), best first. A chunk's position in a ranking is its rank, counted from 1. Each chunk's score is the sum, over every ranking it is in, of 1 / (k + rank).

  • A chunk that appears more than once in the same ranking counts only once there, at its first (best) rank. The ranks of the other chunks are their positions in the list as given.
  • Return the ids of the chunks with the highest scores, best first, at most limit of them (none when limit is 0 or less). Chunks with equal scores are ordered by id, ascending.
  • An empty ranking, or no rankings at all, contributes nothing.
  • Raise ValueError when k is 0 or less.
  • Do not change the lists you are given.
fuse([["a", "b"], ["b", "c"]])
# b scores 1/62 + 1/61, a scores 1/61, c scores 1/62
# ["b", "a", "c"]

Starter code

def fuse(rankings, k=60, limit=10):
    # Return the chunk ids, best first, by reciprocal rank fusion.
    return []

Example tests

def test_example_two_rankings():
    assert fuse([["a", "b"], ["b", "c"]]) == ["b", "a", "c"]


def test_example_limit():
    assert fuse([["a", "b", "c"]], limit=2) == ["a", "b"]

Hidden tests (12 of them for this task) check the edge cases the statement names. You never see them, as on a real screen.

A sample report

A real graded submission with mistakes: its test results come from the harness run by a local Python 3.9.6 (npm run assessment:anchors:local) on 2026-11-22; its review was written by hand as the sample review, for a submission whose test results come from a real run of the harness; not a live model run.

Not yet ready to write RAG code in Python

15 of 27 hidden tests passed. Ready means at most one hidden test failed on every task; close means at least 60% of them passed overall.

Both answers handle the main case, and both trust their input: the fusion ignores three rules of the statement, and the grader lets malformed lines through instead of naming them. Not yet, but each fix is a few lines.

Task 1: Fuse search rankings

8 of 12 hidden tests passed.

  • test_repeat_in_one_ranking_counts_once: AssertionError
  • test_ties_ordered_by_id: AssertionError
  • test_limit_zero_or_less_is_empty: AssertionError
  • test_k_zero_or_less_raises: AssertionError: no ValueError for k=0

Summary. The scoring formula and the ordering by score are right. A repeated id is scored every time it appears, ties are left in the order they were first seen, and the limit and k are not checked.

What failed and why, most important first:

  1. test_repeat_in_one_ranking_counts_once: b appears three times in one ranking and is scored three times, so it jumps to the top. Keep a set of the ids already seen in the current ranking and skip a repeat.
  2. test_ties_ordered_by_id: sorted by score alone keeps equal scores in insertion order, so b comes before a. Sort on a key of (-score, id) to order ties by id.
  3. test_limit_zero_or_less_is_empty: A slice with limit -1 is [:-1], which drops only the last item. Return [] when limit is 0 or less.
  4. test_k_zero_or_less_raises: The statement asks for ValueError when k is 0 or less; with k = 0 the first rank's score is 1 / 1 and a negative k can divide by zero.

Edge cases. Empty rankings, the k parameter and agreement across rankings work. Repeats, ties, a limit of 0 or less and a bad k are missed.

Complexity. One pass over every ranking and one sort of the distinct ids: O(n + m log m), which is right, and it passed the timing test with 100,000 entries.

Readability. Short and clear. The comprehension that unpacks (chunk, score) only to drop the score could be sorted(scores, key=...) over the ids directly.

Your code
def fuse(rankings, k=60, limit=10):
    scores = {}
    for ranking in rankings:
        for rank, chunk in enumerate(ranking, 1):
            scores[chunk] = scores.get(chunk, 0) + 1 / (k + rank)
    ordered = sorted(scores.items(), key=lambda item: item[1], reverse=True)
    return [chunk for chunk, score in ordered][:limit]
A reference solution
def fuse(rankings, k=60, limit=10):
    if k <= 0:
        raise ValueError("k must be positive")
    scores = {}
    for ranking in rankings:
        seen = set()
        for rank, chunk in enumerate(ranking, 1):
            if chunk in seen:
                continue
            seen.add(chunk)
            scores[chunk] = scores.get(chunk, 0.0) + 1 / (k + rank)
    if limit <= 0:
        return []
    best = sorted(scores, key=lambda chunk: (-scores[chunk], chunk))
    return best[:limit]

Task 2: Grade replies against a golden set

7 of 15 hidden tests passed.

  • test_answer_with_every_fact_passes_ignoring_case: AssertionError
  • test_no_reply_fails: AssertionError
  • test_blank_lines_skipped_but_counted: AssertionError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
  • test_bad_json_names_its_line: AssertionError: Expecting property name enclosed in double quotes: line 1 column 13 (char 12)
  • test_not_an_object_raises: AttributeError: 'list' object has no attribute 'get'
  • test_facts_of_the_wrong_shape_raise: AssertionError: no ValueError
  • test_answer_case_without_facts_raises: AssertionError: no ValueError
  • test_repeated_id_raises: AssertionError: no ValueError

Summary. Fallback detection and the basic answer check work. Facts are compared without lowering their phrasings, a missing reply is scored as an empty one, and most malformed lines are not rejected with their line number.

What failed and why, most important first:

  1. test_answer_with_every_fact_passes_ignoring_case: The reply is lowered but the phrasings are not, so "30 Days" is never found in "within 30 days". Lower both sides: p.lower() in reply.
  2. test_no_reply_fails: replies.get(id, "") turns a missing reply into an empty one, so a fallback case becomes review instead of fail. Check for a missing reply first and mark it fail.
  3. test_bad_json_names_its_line: json.loads raises its own error, whose message starts "Expecting ...", not "line 2:". Catch ValueError around the parse and raise again with the line number in front (test_blank_lines_skipped_but_counted fails the same way).
  4. test_not_an_object_raises: A line holding a JSON list reaches case.get and raises AttributeError. Check isinstance(case, dict) before reading fields.
  5. test_facts_of_the_wrong_shape_raise: facts is never validated, so a list of strings is read character by character and an empty fact silently fails. Check that facts is a list of non-empty lists of strings.
  6. test_repeated_id_raises: A repeated id overwrites the first case's status. Raise when the id is already in the result (test_answer_case_without_facts_raises is the same kind of missing check).

Edge cases. Blank lines are skipped and the line numbers count them, a missing or empty id and an unknown expected are rejected. Lists, wrong fact shapes, empty answer facts and repeated ids are not.

Complexity. Linear in the lines and the reply lengths, which is right for a golden set.

Readability. One loop doing parsing, validation and scoring at once is where the missing checks hide. A small parse_case(line) that validates and raises, called inside a try that adds the line number, keeps the scoring short.

Your code
import json


def grade(lines, replies):
    result = {}
    for i, line in enumerate(lines):
        if line.strip() == "":
            continue
        case = json.loads(line)
        if case.get("expected") not in ("answer", "fallback"):
            raise ValueError(f"line {i + 1}: bad expected")
        if not case.get("id"):
            raise ValueError(f"line {i + 1}: no id")
        reply = replies.get(case["id"], "").lower()
        if case["expected"] == "fallback":
            if "don't know" in reply or "do not know" in reply:
                result[case["id"]] = "pass"
            else:
                result[case["id"]] = "review"
            continue
        ok = True
        for fact in case["facts"]:
            if not any(p in reply for p in fact):
                ok = False
        result[case["id"]] = "pass" if ok else "fail"
    return result
A reference solution
import json

FALLBACK = ("don't know", "do not know")


def parse_case(line):
    case = json.loads(line)
    if not isinstance(case, dict):
        raise ValueError("not a JSON object")
    if not isinstance(case.get("id"), str) or not case["id"]:
        raise ValueError("id must be a non-empty string")
    if case.get("expected") not in ("answer", "fallback"):
        raise ValueError("expected must be answer or fallback")
    facts = case.get("facts")
    good = isinstance(facts, list) and all(
        isinstance(f, list) and f and all(isinstance(p, str) for p in f) for f in facts)
    if not good:
        raise ValueError("facts must be a list of lists of strings")
    if case["expected"] == "answer" and not facts:
        raise ValueError("an answer case needs at least one fact")
    return case


def grade(lines, replies):
    result = {}
    for number, line in enumerate(lines, 1):
        if not line.strip():
            continue
        try:
            case = parse_case(line)
        except ValueError as e:
            raise ValueError(f"line {number}: {e}") from None
        if case["id"] in result:
            raise ValueError(f"line {number}: id {case['id']} is repeated")
        reply = replies.get(case["id"])
        if reply is None:
            result[case["id"]] = "fail"
        elif case["expected"] == "fallback":
            result[case["id"]] = "pass" if any(p in reply.lower() for p in FALLBACK) else "review"
        else:
            held = all(any(p.lower() in reply.lower() for p in fact) for fact in case["facts"])
            result[case["id"]] = "pass" if held else "fail"
    return result

A proctored screen would have flagged 0 pastes into the editor and 1 time the tab was left. Nothing was blocked here; on a real screen these are often reviewed by a person.

What to practise

Start a test

All four levels and the questions people ask: the Python readiness check.