smartyfy.mrindigi.com

Python Master Course V2 — 050. Data Modelling Capstone Project

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 05 · LESSON 050/200

Data Modelling Capstone Project

Study time: 90–120 minutes · Prerequisite: Lesson 049.

Video lesson

Video not yet available. Reserved area for a verified video link/player.

Learning outcomes

  • Explain the concepts of data modelling capstone project.
  • Evaluate data structure choices and performance implications.
  • Write Python code that produces deterministic results.
  • Build and test a practical project with meaningful edge cases.

Detailed explanation

Reliable data modelling combines dictionaries, lists, tuples and sets to represent entities and relationships. Define schemas, validate required fields, reconcile keys from both sources, and distinguish a missing record from a recorded zero. This capstone builds a multi-office inventory audit.

Before writing a solution, identify the data volume, operations required, validation rules, and reporting requirements. Keep the input contract explicit and avoid silently changing the meaning of missing values. For production use, add schema validation, logging and independent automated tests.

Understand Data Modelling Capstone Project

Write the audit contract before the implementation

This capstone compares two snapshots of inventory. Each snapshot is a dictionary mapping office names to dictionaries of item names and nonnegative integer quantities. Office and item names must be nonempty strings. A recorded zero means the item was counted and none were present. An absent office or item means there is no observation on that side. This contract makes missing information visible instead of converting it into a plausible amount.

The report below is a list of findings. Each finding contains office, item, status and difference. Office-level findings use None for item and difference. Item-level findings use missing_actual, unexpected_actual or variance; a numeric difference is calculated only when both quantities exist. Exact matches produce no finding. Sorted office and item names give deterministic output. The implementation reads both snapshots and constructs a separate report, preserving the evidence.

Python
def validate_snapshot(snapshot):
    if not isinstance(snapshot, dict):
        raise TypeError("snapshot must be a dictionary")
    for office, items in snapshot.items():
        if not isinstance(office, str) or not office.strip():
            raise ValueError("office must be nonempty text")
        if not isinstance(items, dict):
            raise TypeError("office items must be a dictionary")
        for item, quantity in items.items():
            if not isinstance(item, str) or not item.strip():
                raise ValueError("item must be nonempty text")
            if type(quantity) is not int or quantity < 0:
                raise ValueError("quantity must be a nonnegative integer")


def reconcile(expected, actual):
    validate_snapshot(expected)
    validate_snapshot(actual)
    findings = []
    for office in sorted(expected.keys() | actual.keys()):
        if office not in actual:
            findings.append((office, None, "missing_office", None))
            continue
        if office not in expected:
            findings.append((office, None, "unexpected_office", None))
            continue
        left, right = expected[office], actual[office]
        for item in sorted(left.keys() | right.keys()):
            if item not in right:
                findings.append((office, item, "missing_actual", None))
            elif item not in left:
                findings.append((office, item, "unexpected_actual", None))
            elif right[item] != left[item]:
                findings.append((office, item, "variance", right[item] - left[item]))
    return findings

expected = {"A": {"Pen": 10, "Book": 5, "Eraser": 0}, "B": {}}
actual = {"A": {"Pen": 8, "Book": 7, "Ruler": 0}, "C": {}}
for finding in reconcile(expected, actual):
    print(finding)
Expected output
('A', 'Book', 'variance', 2)
('A', 'Eraser', 'missing_actual', None)
('A', 'Pen', 'variance', -2)
('A', 'Ruler', 'unexpected_actual', None)
('B', None, 'missing_office', None)
('C', None, 'unexpected_office', None)

Trace the decisions, not only the totals

Validation runs before reconciliation, so a malformed quantity cannot partly contaminate the report. For each office, membership is checked before any default mapping is created. This catches B and C even though their available item dictionaries are empty. For shared office A, the union includes every item on either side. Eraser and Ruler become missing-side findings despite their zero quantities. Book and Pen are compared numerically, yielding +2 and −2.

The numeric findings sum to zero, but their absolute differences sum to four. Neither aggregate resolves the two missing-item findings or the two office-level findings. Report counts by status alongside any totals; do not include None differences in arithmetic or change them to zero. A blank or zero net total must never be presented as “all records match”. A complete match is represented by an empty findings list after successful validation.

Acceptance checks for the finished project

Append these checks to the complete worked script above; this fragment requires its reconcile function.

Python
assert reconcile({}, {}) == []
assert reconcile({"A": {"Pen": 0}}, {"A": {"Pen": 0}}) == []
assert reconcile({"A": {"Pen": 0}}, {"A": {}}) == [
    ("A", "Pen", "missing_actual", None)
]
assert reconcile({"A": {}}, {}) == [
    ("A", None, "missing_office", None)
]

Successful assertions produce no output. Add one rejected-input check for a negative quantity and another for True, plus the offsetting-variance sample above. Keep export as a separate step so writing a CSV cannot change the calculation. Before adding a user interface, be able to explain each report field and why all six findings exist. Functions are previewed here: def names the steps, parameters receive the snapshots, and return passes the finished report to the caller.

Also keep a snapshot of each input before calling reconcile and compare it afterward. A reporting function that quietly corrects the actual quantities would destroy the evidence needed to investigate a variance. Calculation and authorized data correction are separate operations.

Progressive runnable examples

Setup: Python 3.10+; standard library only. Save each snippet separately and run using python filename.py. Outputs below are expected results, not claims of live execution.

Example 1

stock={"A":{"Pen":10},"B":{"Pen":5}}
print(stock["A"]["Pen"])
print(sorted(stock))

Expected output:

10
['A', 'B']

Example 2

a = {"Pen": 10, "Book": 5}
b = {"Pen": 8, "Book": 7}
for item in sorted(a.keys() | b.keys()):
    if item not in b:
        print(item, "missing_actual", None)
    elif item not in a:
        print(item, "unexpected_actual", None)
    elif b[item] != a[item]:
        print(item, "variance", b[item] - a[item])

Expected output:

Book variance 2
Pen variance -2

Example 3

codes=["A","B","A"]
print(sorted(set(codes)))

Expected output:

['A', 'B']

Real-world project — Validated inventory reconciliation

Use the same validated finding schema as the worked explanation. This fixture preserves the original A and B quantities. Exact matches add no finding, so office B is omitted from the report. Inventory quantities are nonnegative built-in integers, including legitimate recorded zeros; absent offices and items have explicit statuses and unknown differences.

def validate_snapshot(snapshot):
    if not isinstance(snapshot, dict):
        raise TypeError("snapshot must be a dictionary")
    for office, items in snapshot.items():
        if not isinstance(office, str) or not office.strip():
            raise ValueError("office must be nonempty text")
        if not isinstance(items, dict):
            raise TypeError("office items must be a dictionary")
        for item, quantity in items.items():
            if not isinstance(item, str) or not item.strip():
                raise ValueError("item must be nonempty text")
            if type(quantity) is not int or quantity < 0:
                raise ValueError("quantity must be a nonnegative integer")


def reconcile(expected, actual):
    validate_snapshot(expected)
    validate_snapshot(actual)
    findings = []
    for office in sorted(expected.keys() | actual.keys()):
        if office not in actual:
            findings.append((office, None, "missing_office", None))
            continue
        if office not in expected:
            findings.append((office, None, "unexpected_office", None))
            continue
        left, right = expected[office], actual[office]
        for item in sorted(left.keys() | right.keys()):
            if item not in right:
                findings.append((office, item, "missing_actual", None))
            elif item not in left:
                findings.append((office, item, "unexpected_actual", None))
            elif right[item] != left[item]:
                findings.append((office, item, "variance", right[item] - left[item]))
    return findings

expected = {"A": {"Pen": 10, "Book": 5}, "B": {"Pen": 8}}
actual = {"A": {"Pen": 8, "Book": 7}, "B": {"Pen": 8}}
for finding in reconcile(expected, actual):
    print(finding)

assert reconcile({}, {}) == []
assert reconcile({"A": {"Pen": 0}}, {"A": {"Pen": 0}}) == []
assert reconcile({"A": {"Pen": 0}}, {"A": {}}) == [
    ("A", "Pen", "missing_actual", None)
]
assert reconcile({"A": {}}, {}) == [
    ("A", None, "missing_office", None)
]
for invalid in (-1, True, 0.5, "2"):
    try:
        reconcile({"A": {"Pen": invalid}}, {})
    except ValueError:
        pass
    else:
        raise AssertionError("invalid quantity was accepted")

Expected output:

('A', 'Book', 'variance', 2)
('A', 'Pen', 'variance', -2)

The acceptance assertions check empty snapshots, recorded zero, missing items, missing offices, and rejection of negative, boolean, fractional and text quantities. Passing assertions produce no extra output.

Extra project: Export findings as CSV, count each status, and calculate signed and absolute totals only for numeric variance findings. Preserve the snapshots, test offsetting differences and missing offices separately, and explain time and auxiliary-space costs. A zero net variance alone never proves that all records match.

Common mistakes and professional practices

  • Assuming every collection has elements.
  • Using inefficient repeated membership checks.
  • Confusing missing data with numeric zero.
  • Relying on aggregate totals rather than per-item validation.
  • Not testing input boundaries and failure paths.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

Establish whether the observation exists before comparing its numeric value.

1. What should expected Pen=0 and an absent actual Pen produce?

Answer and reasoning:

A missing_actual finding with difference None. The actual count is unknown; subtracting a fabricated zero would incorrectly turn missing evidence into a match.

2. Why test an absent office whose expected item mapping is empty?

Answer and reasoning:

An item-only loop would have no keys to examine and could miss the absent office. The explicit office membership branch produces missing_office even when that office has no item entries.

3. How should +2 and −2 variances be summarized?

Answer and reasoning:

Net numeric variance is 0 and absolute numeric variance is 4, with two variance findings. Both item differences remain in the report. Missing-side findings need separate counts and cannot be summarized as known numeric differences.

4. Why does the validator use type(quantity) is int?

Answer and reasoning:

It deliberately rejects booleans, fractional numbers and numeric strings. The snapshot contract accepts nonnegative plain integer quantities only. Parsing text into integers belongs before this validated calculation.

5. Show a concrete rejected-input test.

Answer and reasoning:

Python — append to the completed project script
try:
    reconcile({"A": {"Pen": -1}}, {})
except ValueError as error:
    print(str(error))
else:
    raise AssertionError("negative quantity was accepted")
Expected output
quantity must be a nonnegative integer

The else branch makes the test fail if no exception occurs. Merely calling invalid input without checking the result would not demonstrate the required rejection behavior.

Mastery checkpoint

Explain the design decisions, predict the examples, run the project, and provide three independent tests including one boundary case.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.