Sorting a list is easy until the list contains tied scores, missing values, differently capitalized names, and records arriving in a different order each day. A short Python expression can produce plausible results while leaving those decisions unresolved. DeepSeek can help you expose the decisions, suggest counterexamples, and review an implementation. The reliable starting point is a written ordering contract that another person can check without asking the model what it meant.

This guide builds a small record sorter with a deliberately narrow scope. It puts available scores first, orders those scores from highest to lowest, compares normalized names, and uses a unique identifier to settle remaining ties. It rejects invalid inputs instead of silently coercing them. The complete standard-library lab was run locally; the suggested DeepSeek prompts are unexecuted templates. No live DeepSeek model or API was tested, and the results below are evidence about this Python implementation rather than a claim about model performance.

Download the original Python sorting lab, including implementation, demonstration and reproducible local tests. Tested with Python 3.12 and 3.13; standard library only.

Write the sorting contract before the key

Imagine an internal report containing records with an identifier, a display name, and an optional numeric score. Two imports contain the same records but arrive in different orders. The report should show the same identifier sequence in both cases. It must also preserve the original import order for a separate audit view. These requirements immediately tell us that relying on arrival order to break ties is insufficient, and that rearranging the caller’s list in place would be an unwanted side effect.

The lab accepts a plain Python list of plain dictionaries. Every record needs a nonempty plain string identifier and a nonempty plain string name. A score may be a built-in integer, a finite built-in float, or missing. Missing means either an absent score field or an explicit None value. Extra fields are retained but do not influence order. This narrow input boundary makes the example inspectable; it deliberately excludes custom mapping classes and objects with user-defined comparison behavior. It imposes no maximum record count or string length.

The priority order is precise. First separate available scores from missing scores. Within available scores, larger numbers come first. Then compare names using the lab’s normalization and casefolding policy. Finally compare the original identifiers in ascending, case-sensitive string order. Identifiers must be unique across the whole input batch, including records whose other fields differ. The result is a new list containing the original dictionaries, with no modifications to the input list or its records during the call.

Notice which questions this contract answers without touching Python syntax. A negative score still precedes a missing score. Two records named Alice can both remain in the output. A duplicate identifier is an error even if the corresponding scores are different. Changing a display name may change a record’s position among equal scores. These are application decisions. Ask DeepSeek to identify missing decisions before asking it to compress them into a clever expression.

Stable sorting and deterministic results answer different questions

Python documents its sorting operations as stable: elements with equal comparison keys retain their input order. That is useful when arrival order has meaning. In our lab, however, two equal-score records may arrive in either sequence, and the desired report order should survive that change. A stable score-only sort preserves whichever sequence it receives. Running it repeatedly on one unchanged list can therefore look reassuring while failing the actual cross-import requirement.

Consider two records with identifiers a and b, both named Alice and both scoring ten. A score-only sort of b followed by a keeps b followed by a. Giving it a followed by b keeps that different sequence. The implementation in this guide ends its key with the identifier, so both inputs produce a followed by b. The test suite contains this exact comparison. It makes the distinction visible using two records rather than relying on a large, distracting dataset.

Equal score and name keys preserve input ID order B, A, C; adding the unique ID key produces A, B, C.
Stability preserves arrival order among equal keys. An explicit unique final key makes the result independent of that arrival order.

A unique identifier also explains why the word deterministic needs a boundary. Here it means that permutations of the same valid records produce the same identifier sequence under the same comparison policy and runtime behavior. It does not mean a renamed record stays in its previous position, or that every system uses the same Unicode rules forever. The inputs and policy must be held fixed when evaluating the guarantee. Recording those assumptions is more useful than claiming universal reproducibility.

There are valid products where preserving arrival order is exactly right. A queue may already carry a trusted event sequence, for example. In that product, adding an identifier tie-breaker could change intended behavior. Our report deliberately chooses input-order independence. If your requirement instead says first received wins, retain or explicitly model that sequence. A review should judge the implementation against the selected policy, rather than treating one tie-handling approach as automatically superior in every application.

Missing values need their own position

A tempting shortcut replaces a missing score with zero. That changes the meaning of the data. In our contract, zero is an available score, and negative two is also available. Both belong ahead of an unknown score. A replacement of zero would mix missing records with real zeros and could place them above negative values. A missingness flag avoids that ambiguity by putting category membership ahead of numeric magnitude in the comparison key.

The key’s first component is false for a present score and true for a missing score. Its second component holds the negated score when present and a harmless zero placeholder when missing. The placeholder does not compete with real scores across categories because the first component has already decided which category comes first. Among missing records, the first two components match, leaving the name and identifier components to determine the final sequence.

The implementation uses an explicit None check. It does not ask whether the score is truthy. A truthiness check would confuse zero with absence, exactly the case the zero test is intended to catch. It also treats an absent score field and an explicit None as equivalent only for ordering. It never rewrites the original dictionary to add a missing field, so another part of the application can still inspect which representation was supplied.

Other systems need different missing-value policies. A dashboard might put incomplete records first for correction, or reject them before generating the report. Some distinguish not measured from not applicable. Changing to one of those policies requires changing the contract and expected examples together. The current lab has two categories because its stated task needs two. It should not quietly become a general data-cleaning function that invents scores, drops incomplete records, or interprets arbitrary status strings.

Keep numeric validation separate from numeric convenience

The accepted score domain is intentionally concrete: built-in integers and finite built-in floats. Boolean values are rejected even though Python’s type hierarchy makes them easy to accept accidentally as integers. A score of true can otherwise look like a score of one and travel a long way before anyone notices an upstream schema mistake. Checking exact built-in types gives this lab a predictable boundary and also rejects custom numeric subclasses whose operations could have additional behavior.

NaN and positive or negative infinity are rejected. The finite-value check is applied to floats, and the test suite supplies all three nonfinite cases. NaN is especially unsuitable for the ordinary ordered comparisons this example expects. The implementation does not discard offending records or move them into the missing bucket. A supplied but invalid score is an error, while a missing score is an accepted state. Keeping those outcomes distinct helps callers discover malformed data.

The function does not convert integers to floats. This matters even in a small tutorial: the tests include an integer larger than ordinary floating-point ranges and two neighboring large integers that must remain distinguishable. Negating an accepted integer keeps it in the integer domain. A separate case compares a large integer with a float near a precision boundary. These examples establish the behavior actually exercised by the lab rather than assuming that a conversion described as convenient would be harmless.

Equal numeric values, such as ten and ten represented as a float, proceed to the name and identifier tie-breakers. Positive and negative floating-point zero do the same. This sorter does not implement a measurement tolerance, round scores for display, or decide whether two nearby calculations should count as equal. If the application needs those decisions, define them upstream and test the resulting score representation. For exact monetary work, the separate DeepSeek decimal calculations guide addresses a different numeric contract.

Name normalization creates deliberate comparison ties

The name component follows three steps: normalize to NFC, casefold, then normalize to NFC again. The original display name is preserved. The resulting comparison text is used only inside the key. This gives the example a documented caseless comparison policy without asking callers to replace their stored strings. The final normalization also makes the shape of the comparison text explicit after the casefolding transformation, instead of leaving that intermediate representation implicit.

Two examples show why the policy matters. A composed accented character and its equivalent decomposed representation should reach the identifier tie-breaker when scores match. The words Straße and STRASSE also reach that tie-breaker under the selected casefolding policy. Tests cover both situations. Neither result means the records are duplicates. Their identifiers still distinguish them, and both original names remain available for display and inspection. A comparison collision is not permission to delete data.

The lab does not strip accents, trim spaces, apply a national alphabet, or interpret embedded numbers naturally. A leading space remains part of the comparison text. Nonempty whitespace-only strings, control characters, and lone surrogate code points are accepted too; this is not a text-sanitization boundary. An accented letter remains distinct from its unaccented counterpart. The resulting order is a technical string order over the transformed names. If a user expects a locale-specific address book or a product list where item two precedes item ten, this contract must change before the implementation can promise that behavior.

Identifiers intentionally follow a different policy. They are case-sensitive, unnormalized strings. An uppercase A and lowercase a are distinct identifiers, and canonically equivalent Unicode spellings are also distinct identifiers. Those choices are tested rather than hidden. In a real system, identifiers should normally arrive from an established identity contract. Applying the display-name transformation to them inside a sorter could merge identities unexpectedly. The DeepSeek Unicode handling guide explores how to keep transformation purposes separate.

A complete, narrow implementation

The core module below is the complete implementation used for the reported tests. Save it as sorting_lab.py alongside the demo and test module in the downloadable lab. The module contains a single-record key function and a batch sorting function. The key function validates the record and builds comparison data. The batch function adds the collection-wide uniqueness check, gathers the keys, and returns the records in their selected order.

"""A deliberately narrow, nonmutating record-sort contract (Python 3.10+)."""
from math import isfinite
from unicodedata import normalize

Record = dict[str, object]
SortKey = tuple[bool, int | float, str, str]


def record_key(row: Record) -> SortKey:
    """Validate one plain dictionary and return its comparison-only key."""
    if type(row) is not dict:
        raise ValueError("each record must be a plain dict")
    identifier = row.get("id")
    name = row.get("name")
    score = row.get("score")
    if type(identifier) is not str or not identifier:
        raise ValueError("id must be a nonempty plain string")
    if type(name) is not str or not name:
        raise ValueError("name must be a nonempty plain string")
    if score is not None:
        if type(score) not in (int, float):
            raise ValueError("score must be int, finite float, or None")
        if type(score) is float and not isfinite(score):
            raise ValueError("score must be finite")
    folded_name = normalize("NFC", normalize("NFC", name).casefold())
    return (score is None, 0 if score is None else -score,
            folded_name, identifier)


def sort_records(records: list[Record]) -> list[Record]:
    """Sort a plain list by score DESC, folded name ASC, unique id ASC.

    Absent/None scores sort last. Return a new list of original dictionaries.
    IDs are unique, case-sensitive, unnormalized strings. Extra fields survive.
    Invalid inputs raise ValueError; this function never edits the input.
    """
    if type(records) is not list:
        raise ValueError("records must be a plain list")
    seen: set[str] = set()
    keyed: list[tuple[SortKey, Record]] = []
    for row in records:
        key = record_key(row)
        identifier = key[3]
        if identifier in seen:
            raise ValueError("duplicate id")
        seen.add(identifier)
        keyed.append((key, row))
    return [row for _, row in sorted(keyed, key=lambda pair: pair[0])]

Validation happens while the batch function constructs a separate list of key-and-record pairs. A repeated identifier raises an error before any sorted result is returned. Sorting then considers only each pair’s key, because an explicit extraction function is supplied. This last detail prevents the record dictionaries themselves from becoming an accidental fallback comparison target. The design is slightly more explicit than a one-line sort, which makes its validation boundary easier to trace and review.

Every accepted row contributes one pair and exactly one returned record. No filtering, merging, deduplication, or field rewriting occurs. A duplicate identifier is rejected rather than resolved by keeping whichever row appeared first. The function uses the same error class for its deliberately narrow set of invalid inputs, with messages identifying the failed requirement. An application can wrap those errors with import context, but the tutorial does not build a logging, quarantine, or recovery system around them.

The return value is a new outer list, not a deep copy of the records. This is a useful distinction when interpreting the nonmutation guarantee. Calling the sorter leaves its input unchanged, but editing a dictionary through the returned list afterward also changes that dictionary as seen through the original list. Both lists refer to the same object. If isolated editable copies are required, copying must be a separate, explicit decision with its own treatment of nested values.

Read the tuple from left to right

A tuple key is a compact expression of priorities, but it should remain explainable one component at a time. For a record scoring ten with name ALICE and identifier r02, the key is false, negative ten, alice, and r02. For a missing score with name Bob and identifier r06, it is true, zero, bob, and r06. The keys have the same structure even though the original records have different score availability.

Four ordered key fields: missing-score flag, negated score, normalized casefolded name, and unique case-sensitive ID.
The first differing field decides the order. Higher numeric scores sort first; the unique ID resolves remaining ties.

When comparing two keys, the earliest differing component decides. That is why changing the identifier cannot move a low-scoring record above a high-scoring record. It can only settle a tie left by the earlier components. A useful review exercise is to ask which components are inspected for a particular pair of records. If the score differs, arguing about their name order is irrelevant to their relative positions in this contract.

The score component is negated because the overall key is sorted in ascending order while scores need descending order. Setting reverse to true on the entire tuple would reverse every component, including the missing-value bucket, names, and identifiers. That would violate several requirements at once. Mixed directions deserve explicit treatment. For this numeric field, negation is simple; it is not a general recipe for descending arbitrary strings or every possible custom numeric type.

Stable multi-pass sorting is another possible design, with lower-priority fields handled before higher-priority fields. This article stays with one composite key so the whole policy is visible in a single place. If DeepSeek proposes a multi-pass alternative, ask it to show why the pass order implements the same priorities and how missing scores retain their required position. Compare the alternatives using the same fixtures before deciding that a shorter implementation is equivalent.

Trace six records without guessing

The demo intentionally combines several decisions in a small input. It includes two equal-score names that become equal after casefolding, two missing-score representations, a negative score, and a higher fractional score. The input begins with a missing record, so a successful run visibly moves it. The output also prints the original list’s identifier order, making it possible to see that the caller’s list was not rearranged as a side effect.

from sorting_lab import record_key, sort_records

records = [
    {"id": "r04", "name": "Zoë", "score": None},
    {"id": "r03", "name": "alice", "score": 10},
    {"id": "r02", "name": "ALICE", "score": 10},
    {"id": "r06", "name": "Bob"},
    {"id": "r05", "name": "Charlie", "score": -2},
    {"id": "r01", "name": "Bob", "score": 12.5},
]
result = sort_records(records)
print("result:", [row["id"] for row in result])
print("input: ", [row["id"] for row in records])
for row in result:
    print(row["id"], record_key(row))

Actual local demonstration output:

result: ['r01', 'r02', 'r03', 'r05', 'r06', 'r04']
input:  ['r04', 'r03', 'r02', 'r06', 'r05', 'r01']
r01 (False, -12.5, 'bob', 'r01')
r02 (False, -10, 'alice', 'r02')
r03 (False, -10, 'alice', 'r03')
r05 (False, 2, 'charlie', 'r05')
r06 (True, 0, 'bob', 'r06')
r04 (True, 0, 'zoë', 'r04')

The resulting identifier sequence is r01, r02, r03, r05, r06, r04. Record r01 wins on score alone. Records r02 and r03 share a score and a folded name, so their identifiers decide their order. Record r05 has a negative score but still precedes both missing-score records. Records r06 and r04 then compare by folded name, placing Bob before Zoë. Each transition has a reason stated in the contract.

The original identifier sequence remains r04, r03, r02, r06, r05, r01. That check is useful, but it is weaker than the full nonmutation test: a function could preserve list order while editing the dictionaries. The test suite therefore also snapshots representative nested data and checks that the original structure remains equal after sorting. It separately checks object identity to establish the promised shallow-reference behavior. Value equality and object identity answer different questions here.

After extracting the download, enter the python_sorting_lab folder. Run the demo with python demo.py and run the suite with python -m unittest discover -v from that folder. The supplied files use only the Python standard library. The implementation uses syntax available in Python 3.10 and later; the executions reported here were on Python 3.12.14 and Python 3.13.5. A syntax compatibility statement should not be mistaken for evidence that every supported runtime was actually exercised.

Test expected order, then test the surrounding guarantees

The author suite contains 34 unittest methods. A separate review added 25 independent tests, and the combined 59 methods passed on each of the two recorded Python versions. Some methods contain multiple subcases, so this is not a count of individual input records or distinct assertions. The saved runtime logs include the version, test names, and completion result. This is a small reproducible verification package, not a performance benchmark or exhaustive proof of every possible input.

Start with hand-written expected sequences. Separate fixtures establish descending score order, ascending names within tied scores, and ascending identifiers within tied normalized names. A conflicting fixture makes a higher-scoring Zoe precede a lower-scoring Amy. Without that conflict, an implementation that accidentally prioritized names could still pass examples whose fields happened to agree. Good fixtures make the priorities compete, so the wrong priority produces an observable failure.

Missing-value tests distinguish absence from zero, place negative scores before missing values, and verify that names still order the missing bucket. Numeric tests cover equal integers and floats, signed zero, very large integers, and a mixed integer-float comparison. Text tests cover canonical equivalence, casefold expansion, preserved accents, and preserved whitespace. These cases were selected from the written contract rather than generated merely to make the output look varied.

Rejection tests exercise malformed containers, malformed required fields, unsupported score types, nonfinite values, duplicate identifiers, and relevant subclasses. A separate late-failure test places an invalid record after valid records and checks that the input remains unchanged. That position matters: a function might behave safely on the first invalid record yet partially edit earlier records before discovering a later problem. Testing the error path is part of verifying the nonmutation contract.

Use permutation tests to challenge arrival-order dependence

The six-record demo has 720 input permutations. The suite tries every one and requires the same manually specified identifier sequence each time. This directly targets the report’s input-order-independence requirement. It is stronger than calling the function twice on the original demo, which never changes the disputed condition. The fixture is deliberately small enough that exhaustive permutation testing remains a practical teaching example rather than an expensive test-generation exercise.

Permutation testing also has a clear limit. The 720 arrangements contain exactly the same six records and therefore cannot discover every unsupported type or every normalization case. That is why the suite retains focused rejection and text tests. Different test families examine different dimensions: permutations vary arrival order, boundary fixtures vary values, and invalid-input fixtures challenge the acceptance boundary. None should be presented as a substitute for all the others.

The suite additionally constructs 200 seeded batches containing combinations of tied names, mixed numeric values, and both missing-score representations. It compares the implementation against a separate branch-based comparator, checks idempotence, verifies that original record objects are retained, and reshuffles the input before checking the sequence again. A fixed seed makes this particular exploration repeatable. It does not mean the samples cover every relevant batch or justify a statistical reliability claim.

The comparator does not call the production key function or sort by the same tuple. It decides missingness, score, name, and identifier order with explicit branches. That gives it useful structural independence, although both implementations still share the written policy and standard Unicode transformations. The hand-written expected sequences remain important because two implementations can share a mistaken interpretation. The DeepSeek property-based testing guide develops that broader testing approach.

Know what each property can and cannot establish

Idempotence means sorting an already sorted result gives the same identifier sequence. It is a useful check, but many wrong sorts are idempotent. A sorter that consistently orders names before scores may pass it perfectly. Input nonmutation is similarly necessary without saying anything about whether the final order is right. Tests become more informative when their names identify the specific promise they examine and the review does not overstate what a passing result proves.

Record preservation is another separate promise. A deduplicating implementation could return a beautifully ordered list while losing data. The generated-batch tests compare the identities of input and output dictionaries, and the uniqueness rule ensures that valid batches contain distinct identified records. Hand-written cases also cover a repeated reference to the same dictionary, which is rejected as a duplicate identifier. Together these checks make accidental dropping and identity confusion easier to notice.

When a test fails, reduce the example before changing the policy. Two records are often enough to reveal a reversed direction, and three may expose a misplaced missing-value category. Keep the failing example in the suite after the repair. Ask DeepSeek to explain which contract sentence the example contradicts. If it proposes changing the expected sequence instead, require an explicit policy decision from the owner of that requirement rather than letting a repair silently redefine correctness.

Give DeepSeek a bounded review task

The most useful initial prompt supplies the data boundary and asks for unresolved decisions. It should avoid presenting the current implementation as authoritative. A model that sees only a compact sorting expression may spend its response explaining that expression, even when its assumptions are wrong for the application. Give it the report’s required behavior and ask for small counterexamples before requesting a rewrite. The following template has not been executed against DeepSeek.

Review this proposed Python sorting contract before writing code. Input is a plain list of plain dictionaries. Each record has a unique nonempty plain-string id, a nonempty plain-string name, and an optional score. Scores are built-in int, finite built-in float, None, or absent. Present scores precede missing scores; present scores descend. Names compare ascending after NFC, casefold, NFC. Original ids compare ascending and case-sensitively as the last tie-breaker. Preserve every record, return a new list of original objects, and never edit input. Reject invalid data and duplicate ids. Identify unresolved assumptions, then propose minimal examples with expected id sequences. Do not claim you ran code.

A second prompt can focus on the implementation boundary. Provide the core module and the contract, but ask for findings supported by concrete inputs. Require the reviewer to distinguish a policy disagreement from a coding defect. For example, wanting locale-specific name order is a possible new requirement; observing that a missing score overtakes a negative score would be a defect under this contract. That distinction keeps reviews from turning into unbounded rewrites.

Review the attached sorting_lab.py against the stated contract. For each suspected defect, identify the relevant function, give the smallest valid or invalid input that demonstrates it, state the expected outcome, and explain the actual path through the code. Check missing versus zero, descending score with ascending name, NaN and booleans, duplicate ids, canonical-equivalent names, and input nonmutation. Separate definite defects from policy alternatives. Do not invent execution results or add coercion, filtering, or dependencies.

A third prompt can critique the tests rather than generate more implementation. Supply the suite and ask which incorrect implementations would still pass. This encourages specific missing fixtures: a global reverse flag, a score-or-zero fallback, an omitted identifier component, or accidental in-place sorting. The DeepSeek code review guide offers a useful discipline for turning those suggestions into reproducible findings. A plausible explanation becomes stronger evidence only after the proposed example is actually run.

Inspect this sorting test suite. Propose five plausible incorrect implementations and identify which existing test should reject each. If a mutation appears able to survive, propose one minimal additional test with a manually justified expected outcome. Keep the oracle independent of record_key. Report proposed tests as unexecuted unless you have actual execution evidence. Do not report a mutation score without running a defined mutation set.

Review model suggestions as changes to a contract

Several suggestions deserve extra scrutiny because they sound harmless. Converting every score to a float broadens acceptance and can lose distinctions between large integers. Converting names with a generic string constructor accepts malformed fields that the contract rejects. Removing repeated identifiers changes an error into data loss. Replacing missing values with zero changes their meaning. Adding an original-position index settles ties within one input, but preserves the arrival-order dependence this report was designed to remove.

Do not reject such suggestions merely because a model proposed them. Evaluate them against the intended application. There are import pipelines where coercion is appropriate, and interfaces where arrival order must survive. The problem is silently combining those choices with a sorting helper whose callers expect different behavior. Keep cleaning, identity resolution, and ordering as explicit steps when their policies differ. That makes failures easier to explain and future changes easier to approve.

If the model produces a revised key, trace at least one conflicting pair through every component before running the complete suite. Then compare the patch with the stated acceptance boundary. A passing demo should not conceal that the revised function now accepts a decimal object, normalizes identifiers, trims names, or clones nested data. These are observable changes even when the six demonstration records happen to produce the same printed order.

The boundaries of this implementation

This is an in-memory batch sorter. It materializes keys and an output list, and it expects the full input list to be available. It is not a streaming external sort and makes no measured throughput or memory-use claim. For large datasets, establish the actual resource constraints and benchmark representative inputs in the intended environment. The presence of a short key function is not evidence that the surrounding application can safely load an arbitrarily large report.

The function also assumes records are not being modified concurrently while it validates and sorts them. It does not freeze objects, coordinate writers, or produce an isolated snapshot. Because it returns shared record references, later edits may make the displayed list appear inconsistent with the old comparison keys. Applications that need a durable snapshot should define when values are captured and who can change them, rather than expecting sorting itself to provide concurrency control.

Cross-runtime and cross-system ordering needs additional agreement. The tests passed on the two reported interpreters, while other languages, databases, or Unicode versions may use different text comparison policies. A database query that appears to list the same fields is not automatically equivalent to this Python key. If the order feeds continuation tokens or paginated exports, verify the storage system’s comparison behavior and snapshot rules as well. The DeepSeek cursor pagination guide covers those additional concerns.

The practical result is a sorter whose small scope is visible, testable, and easy to challenge. Its decisions about missing values, mixed directions, transformed names, and ties can be explained with individual record pairs. DeepSeek can contribute review questions and candidate counterexamples within that scope. Keep the written contract, the exact implementation, the expected sequences, and the actual runtime output together so future edits can be judged against evidence instead of confidence.

Sources and References

The implementation, fixtures, and test outcomes in this article are original local work. The Python documentation below was checked on October 5, 2026 for the language and standard-library behavior used by the lab. The unexecuted prompts do not establish any DeepSeek model capability, response quality, or comparative performance.

Shares:
3 Comments
Leave a Reply

Your email address will not be published. Required fields are marked *