Typorithm · medium

Capstone: an aligned technical-role report

pythonnumpynumerical-computingindependent-practice
Saved on this device
Full lesson · 4 learning steps Open any exercise for focused practice
1

Step 1 of 4 · intro card

Capstone: an aligned technical-role report

0%

Concept and contract

Combine canonical identity checks, one eligibility mask, stable ranking and population-consistent summaries.

The capstone turns a small collection of owned technical-role fixtures into a bounded report for one country. Each input record has a canonical identifier, country, synthetic numerical score and technical-role flag. The function rejects duplicated identifiers and malformed records, excludes missing or negative scores, filters the requested population, and reports its count, mean score and a limited list of top identifiers.

These fixtures are not live vacancies, licensed source receipts or model predictions. The technical flag is supplied test data, not a technique for deciding whether an arbitrary real role belongs in a production catalog. The purpose is to make numerical alignment, selection and reporting contracts independently observable.

Mechanism and worked example

The worked function validates structural fields before constructing aligned arrays.

The worked function validates structural fields before constructing aligned arrays. It then creates one combined mask for country, technical eligibility, finite score and nonnegative scope. It applies that mask to both identifiers and scores. A shared lexsort permutation ranks decreasing scores with increasing identifier tie-breaks, and only the displayed top identifier list is limited. The mean and count still describe every eligible observation.

This order matters: validate, select, summarize the selected population, rank aligned identities, then bound the presentation. A page-size limit is not a sampling design and must not quietly become the denominator for a whole-population report.

Complete worked example

python

import numpy as np

def inspect_example(records, country, limit=2):
    def valid_country(value):
        return type(value) is str and len(value) == 2 and value.isascii() and value.isalpha() and value.isupper()
    if not valid_country(country) or type(limit) is not int or not 1 <= limit <= 20:
        raise ValueError("expected a country code and bounded display limit")
    required = {"id", "country", "score", "technical"}
    for row in records:
        if type(row) is not dict or set(row) != required:
            raise ValueError("unexpected record structure")
        if type(row["id"]) is not int or row["id"] < 1 or not valid_country(row["country"]):
            raise ValueError("invalid canonical identity or country")
        if type(row["technical"]) is not bool or (row["score"] is not None and type(row["score"]) not in (int, float)):
            raise ValueError("invalid technical flag or numerical score")
    ids = np.asarray([row["id"] for row in records], dtype=np.int64)
    if np.unique(ids).size != ids.size:
        raise ValueError("duplicate canonical identifier")
    countries = np.asarray([row["country"] for row in records], dtype=np.str_)
    technical = np.asarray([row["technical"] for row in records], dtype=np.bool_)
    scores = np.asarray([row["score"] for row in records], dtype=np.float64)
    mask = (countries == country) & technical & np.isfinite(scores) & (scores >= 0)
    selected_ids = ids[mask]
    values = scores[mask]
    order = np.lexsort((selected_ids, -values))
    return {"country": country, "count": int(values.size),
            "meanScore": float(values.mean()) if values.size else None,
            "topIds": selected_ids[order][:limit].tolist()}
Reasoning
The worked function validates structural fields before constructing aligned arrays. It then creates one combined mask for country, technical eligibility, finite score and nonnegative scope. It applies that mask to both identifiers and scores. A shared lexsort permutation ranks decreasing scores with increasing identifier tie-breaks, and only the displayed top identifier list is limited. The mean and count still describe every eligible observation. This order matters: validate, select, summarize the selected population, rank aligned identities, then bound the presentation. A page-size limit is not a sampling design and must not quietly become the denominator for a whole-population report.
Open in local Python playground ↗

Focused decision: context is in the complete example

python

mask = (countries == country) & technical & np.isfinite(scores) & (scores >= 0)
selected_ids = ids[mask]
values = scores[mask]
order = np.lexsort((selected_ids, -values))
Focused decision
Type this short numerical decision after reading its complete context. The complete imports, array construction, validation, and result checks remain in the worked example. Typing records practice; only the downloadable computer lab executes Python.

Counterexamples and common mistakes

The controlled mistake computes the mean only from the displayed top rows.

The controlled mistake computes the mean only from the displayed top rows. The output remains finite and the top identifiers are correct, but the summary now describes a favored subset instead of the declared eligible population. Other plausible failures include counting rows before filtering, sorting score and identifier arrays independently, or silently accepting repeated canonical identifiers as additional observations.

Zero is a valid score in the baseline contract and differs from a missing value. A record outside the selected country must not affect the selected count or mean. Nontechnical fixture records must also remain outside the report even when their scores are much larger than eligible rows.

Controlled mistake: inspect the failing numerical contract

python

import numpy as np

def inspect_example(records, country, limit=2):
    def valid_country(value):
        return type(value) is str and len(value) == 2 and value.isascii() and value.isalpha() and value.isupper()
    if not valid_country(country) or type(limit) is not int or not 1 <= limit <= 20:
        raise ValueError("expected a country code and bounded display limit")
    required = {"id", "country", "score", "technical"}
    for row in records:
        if type(row) is not dict or set(row) != required:
            raise ValueError("unexpected record structure")
        if type(row["id"]) is not int or row["id"] < 1 or not valid_country(row["country"]):
            raise ValueError("invalid canonical identity or country")
        if type(row["technical"]) is not bool or (row["score"] is not None and type(row["score"]) not in (int, float)):
            raise ValueError("invalid technical flag or numerical score")
    ids = np.asarray([row["id"] for row in records], dtype=np.int64)
    if np.unique(ids).size != ids.size:
        raise ValueError("duplicate canonical identifier")
    countries = np.asarray([row["country"] for row in records], dtype=np.str_)
    technical = np.asarray([row["technical"] for row in records], dtype=np.bool_)
    scores = np.asarray([row["score"] for row in records], dtype=np.float64)
    mask = (countries == country) & technical & np.isfinite(scores) & (scores >= 0)
    selected_ids = ids[mask]
    values = scores[mask]
    order = np.lexsort((selected_ids, -values))
    return {"country": country, "count": int(values.size),
            "meanScore": float(values[order][:limit].mean()) if values.size else None,
            "topIds": selected_ids[order][:limit].tolist()}
Reasoning
The controlled mistake computes the mean only from the displayed top rows. The output remains finite and the top identifiers are correct, but the summary now describes a favored subset instead of the declared eligible population. Other plausible failures include counting rows before filtering, sorting score and identifier arrays independently, or silently accepting repeated canonical identifiers as additional observations. Zero is a valid score in the baseline contract and differs from a missing value. A record outside the selected country must not affect the selected count or mean. Nontechnical fixture records must also remain outside the report even when their scores are much larger than eligible rows.
Open in local Python playground ↗

Independent practice

Change the eligibility policy to strictly positive scores.

Change the eligibility policy to strictly positive scores. Preserve country matching, technical-role selection, canonical uniqueness, tie-breaking and the independent display limit. This is one mask change after a longer worked example, allowing the learner to reason about its consequences without rewriting the whole pipeline.

Predict how removing a zero-score record changes count and mean while leaving the top two identifiers unchanged in the main fixture. This is why checking the displayed list alone would be insufficient evidence. Test a country with no matching records and a repeated identifier that must still be rejected.

Step 1: Include strictly positive scores only, keeping summaries over the full eligible population. Step 2: Retain the working imports, input validation and array shapes. Change the stated policy, run the supplied practice cases, then explain the newly accepted or rejected boundary.

Practice starter: solve before reading the solution

python

import numpy as np

def inspect_example(records, country, limit=2):
    def valid_country(value):
        return type(value) is str and len(value) == 2 and value.isascii() and value.isalpha() and value.isupper()
    if not valid_country(country) or type(limit) is not int or not 1 <= limit <= 20:
        raise ValueError("expected a country code and bounded display limit")
    required = {"id", "country", "score", "technical"}
    for row in records:
        if type(row) is not dict or set(row) != required:
            raise ValueError("unexpected record structure")
        if type(row["id"]) is not int or row["id"] < 1 or not valid_country(row["country"]):
            raise ValueError("invalid canonical identity or country")
        if type(row["technical"]) is not bool or (row["score"] is not None and type(row["score"]) not in (int, float)):
            raise ValueError("invalid technical flag or numerical score")
    ids = np.asarray([row["id"] for row in records], dtype=np.int64)
    if np.unique(ids).size != ids.size:
        raise ValueError("duplicate canonical identifier")
    countries = np.asarray([row["country"] for row in records], dtype=np.str_)
    technical = np.asarray([row["technical"] for row in records], dtype=np.bool_)
    scores = np.asarray([row["score"] for row in records], dtype=np.float64)
    mask = (countries == country) & technical & np.isfinite(scores) & (scores >= 0)
    selected_ids = ids[mask]
    values = scores[mask]
    order = np.lexsort((selected_ids, -values))
    return {"country": country, "count": int(values.size),
            "meanScore": float(values.mean()) if values.size else None,
            "topIds": selected_ids[order][:limit].tolist()}

# Independent task: Include strictly positive scores only, keeping summaries over the full eligible population.
Reasoning
Include strictly positive scores only, keeping summaries over the full eligible population.
Open in local Python playground ↗
  • Hint 1: Change the shared score eligibility mask, not the mean denominator.
  • Hint 2: Use scores > 0 while retaining every other mask term and the later display limit.

Solution, tests and trade-offs

The solution changes scores >= 0 to scores > 0 in the shared eligibility mask.

The solution changes scores >= 0 to scores > 0 in the shared eligibility mask. Both count and mean then use exactly the newly selected score vector. The display limit is applied afterwards to the shared ordering of eligible identifiers. The suite includes an empty catalog, a one-row zero-score population and malformed identities, so neither fake zero means nor silent duplicate inflation can pass.

The report is a deterministic analysis of these supplied rows, not an estimate of all technical hiring in a country. Real market reporting additionally needs source coverage, deduplication history, observation dates and comparable populations. Numerical precision does not create missing evidence about those external facts.

Practice solution and acceptance checks

python

import numpy as np

def inspect_example(records, country, limit=2):
    def valid_country(value):
        return type(value) is str and len(value) == 2 and value.isascii() and value.isalpha() and value.isupper()
    if not valid_country(country) or type(limit) is not int or not 1 <= limit <= 20:
        raise ValueError("expected a country code and bounded display limit")
    required = {"id", "country", "score", "technical"}
    for row in records:
        if type(row) is not dict or set(row) != required:
            raise ValueError("unexpected record structure")
        if type(row["id"]) is not int or row["id"] < 1 or not valid_country(row["country"]):
            raise ValueError("invalid canonical identity or country")
        if type(row["technical"]) is not bool or (row["score"] is not None and type(row["score"]) not in (int, float)):
            raise ValueError("invalid technical flag or numerical score")
    ids = np.asarray([row["id"] for row in records], dtype=np.int64)
    if np.unique(ids).size != ids.size:
        raise ValueError("duplicate canonical identifier")
    countries = np.asarray([row["country"] for row in records], dtype=np.str_)
    technical = np.asarray([row["technical"] for row in records], dtype=np.bool_)
    scores = np.asarray([row["score"] for row in records], dtype=np.float64)
    mask = (countries == country) & technical & np.isfinite(scores) & (scores > 0)
    selected_ids = ids[mask]
    values = scores[mask]
    order = np.lexsort((selected_ids, -values))
    return {"country": country, "count": int(values.size),
            "meanScore": float(values.mean()) if values.size else None,
            "topIds": selected_ids[order][:limit].tolist()}
Reasoning
The solution changes scores >= 0 to scores > 0 in the shared eligibility mask. Both count and mean then use exactly the newly selected score vector. The display limit is applied afterwards to the shared ordering of eligible identifiers. The suite includes an empty catalog, a one-row zero-score population and malformed identities, so neither fake zero means nor silent duplicate inflation can pass. The report is a deterministic analysis of these supplied rows, not an estimate of all technical hiring in a country. Real market reporting additionally needs source coverage, deduplication history, observation dates and comparable populations. Numerical precision does not create missing evidence about those external facts.
Open in local Python playground ↗

Interview reasoning and next step

Explain the entire pipeline with one row traced from input through the mask into either the report or exclusion.

Explain the entire pipeline with one row traced from input through the mask into either the report or exclusion. Identify why a correct top list does not establish a correct denominator. Show how duplicate identifiers, missing scores, ties and an empty selected population are handled. These are transferable data-engineering skills rather than facts about one fixture name.

On the PC, type the focused selection and aligned ranking decisions, then reconstruct them without answer choices. In the app, use the reasoning questions and saved progress. Continue with pandas for labeled tables, then dedicated statistics and classical ML before drawing stronger conclusions from numerical summaries.

Optional stretch — after the core task works: Add one independently reasoned boundary case and explain its expected value before running it.

Computer practice: https://applydjinn.com/typorithm/numpy-lab-20261106.zip. Install pinned dependencies in an isolated Python environment. Run verify.py, then change the working exercise baseline and run --practice np-capstone. The real NumPy arrays, numerical contracts, random state checks and temporary numeric files use owned fixtures only. No production database, feed, account or paid service is used. This lab executes Python; the PC typing trainer and native reading progress do not execute it.

Combine canonical identity checks, one eligibility mask, stable ranking and population-consistent summaries.