Algorithms and Decomposition in Python: Worked Trace and Exam Traps
Learn how to turn a problem contract into small responsibilities, trace every state change, and implement the verified algorithm cleanly in Python.
KnowledgeGate Team
Exam prep & CS education

Beginners often type Python before stating the input, output, and decisions, then patch until one sample works. A safer method defines the contract, splits the task, writes pseudocode, dry-runs it, then implements verified Python. The running example uses six quiz scores, [42, 67, 58, 81, 36, 66], with a teaching threshold of 50. This value is only for the example, not an official cutoff. The Coding & DSA Courses for Placements page provides a broader learning route.
Algorithm, program and decomposition: three ideas, three jobs
An algorithm is a finite, ordered, unambiguous procedure from stated inputs to stated outputs. Decomposition splits it into subproblems with clear responsibilities. A Python program is an executable implementation. The terms are related but not synonymous.
For numbers = [4, 7, 2], the goal is its sum. One decomposition is accept input -> validate values -> accumulate values -> report result; the algorithm updates total through 0 -> 4 -> 11 -> 13; Python implements those steps.
Decomposition exposes the top-level flow and lets each subproblem be tested. It does not require a function per line. If the syntax is unfamiliar, follow the Python Tutorial: 13-Step Self-Study Path to DSA before implementing this plan.
Turn the running problem into a precise contract
The input is scores = [42, 67, 58, 81, 36, 66]. It must be non-empty, with integer elements from 0 through 100. Set threshold = 50; a score passes when score >= threshold.
Define the outputs first: total, arithmetic average, number passed, number failed, and highest. Expected values are total = 350, average = 350 / 6 = 58.333..., displayed average 58.33, passed = 4, failed = 2, and highest = 81.
The contract also fixes these edges:
An empty list raises
ValueError("scores must not be empty").A non-integer or out-of-range value such as
"67"or105raisesValueError("each score must be an integer from 0 to 100").A score equal to
50passes because the comparison is>=.
Decompose by responsibility, then define each interface
Use exactly four responsibilities:
validate_scores(scores)checks the input and either returns normally or raises the specified error.compute_summary(scores, threshold)scans once and returnstotal, unroundedaverage,passed,failed, andhighest.format_summary(summary)rounds only the displayed average to two decimal places.analyse_scores(scores, threshold)coordinates those three stages and returns the formatted result.
For the running input, validation succeeds. Computation returns {total: 350, average: 58.333..., passed: 4, failed: 2, highest: 81}. Formatting returns Total=350, Average=58.33, Passed=4, Failed=2, Highest=81.
The boundaries are deliberate. Validation owns validity, computation owns arithmetic and counting, formatting owns presentation, and orchestration owns order. Invalid input fails before the scan. Display rounding cannot corrupt later calculations.

Fully worked algorithm: pseudocode and one complete dry run
Write the operations before translating them:
scores <- [42, 67, 58, 81, 36, 66]
threshold <- 50
total <- 0
passed <- 0
highest <- scores[0]
FOR each score IN scores
total <- total + score
IF score >= threshold THEN
passed <- passed + 1
END IF
IF score > highest THEN
highest <- score
END IF
END FOR
failed <- LENGTH(scores) - passed
average <- total / LENGTH(scores)Trace each state change.
Iteration | Score | Total after addition | Passed after test | Highest after test |
|---|---|---|---|---|
1 | 42 | 42 | 0 | 42 |
2 | 67 | 109 | 1 | 67 |
3 | 58 | 167 | 2 | 67 |
4 | 81 | 248 | 3 | 81 |
5 | 36 | 284 | 3 | 81 |
6 | 66 | 350 | 4 | 81 |
After the scan, failed = 6 - 4 = 2 and average = 350 / 6 = 58.333..., displayed as 58.33. At each row, total sums processed scores, passed counts those meeting >= 50, and highest is their largest value. Six iterations process every input once. Practise with Pseudocode Questions for Placements: 3 Solved Traces.

Translate the plan into Python and test the boundaries
Computation keeps raw values; formatting applies presentation rules.
def validate_scores(scores):
if not scores:
raise ValueError("scores must not be empty")
if any(type(score) is not int or score < 0 or score > 100 for score in scores):
raise ValueError("each score must be an integer from 0 to 100")
def compute_summary(scores, threshold):
total = 0
passed = 0
highest = scores[0]
for score in scores:
total += score
if score >= threshold:
passed += 1
if score > highest:
highest = score
failed = len(scores) - passed
average = total / len(scores)
return {"total": total, "average": average, "passed": passed,
"failed": failed, "highest": highest}
def format_summary(summary):
return (f"Total={summary['total']}, Average={summary['average']:.2f}, "
f"Passed={summary['passed']}, Failed={summary['failed']}, "
f"Highest={summary['highest']}")
def analyse_scores(scores, threshold):
validate_scores(scores)
summary = compute_summary(scores, threshold)
return format_summary(summary)The main call produces Total=350, Average=58.33, Passed=4, Failed=2, Highest=81. The boundary call analyse_scores([50], 50) produces Total=50, Average=50.00, Passed=1, Failed=0, Highest=50. Calls with [] and [42, 105] raise the two specified messages. One scan of n scores takes O(n) time and O(1) auxiliary space, apart from the input and returned summary.
Common decomposition and tracing traps, with exact repairs
Trap | What goes wrong | Repair |
|---|---|---|
Coding before fixing the contract | Empty and invalid inputs have accidental behaviour | Write input, output, and error rules first |
One do-everything function | Validation, arithmetic, and display failures are tangled | Split by the four responsibilities |
A function for every line | Data flow becomes harder to follow | Split only where a responsibility or test boundary changes |
Rounding average inside computation | Later calculations lose precision | Keep |
Starting highest at 0 | The method silently assumes a value range | Initialise from |
Using | The boundary score | Copy the comparison from the contract |
If a boundary variant reports passed = 3, the comparison probably excludes equality with 50. If the running example reports average = 58, check for integer truncation or early rounding. Repair the faulty step, not just the final number. Functions should receive their inputs and return a result or raise a defined error. Avoid global total, passed, or highest values.
How exam-style questions test algorithms and decomposition
Questions may ask you to identify a valid algorithm, order dependent steps, trace accumulators, find an edge case, match a subproblem to a function, predict a changed condition, or give time and auxiliary-space complexity. These are reasoning forms, not claims about a named examination.
For scores = [55, 48, 70] and threshold = 50, after iteration two, total = 103, passed = 1, highest = 55. The final result is total = 173, average = 57.666..., displayed as 57.67, passed = 2, failed = 1, highest = 70. Change only the threshold to 60: passed = 1, failed = 2; total, average, and highest stay unchanged.
For named-exam claims about marks, weightage, frequency, dates, or syllabus coverage, consult the current official notice.
The short version and the next step
Use five steps: define the contract, split responsibilities, write pseudocode, dry-run every state change, then implement and test boundaries. For a 60-second check, [64, 40, 76, 50] gives total = 230, average = 57.5, displayed as 57.50, passed = 3, failed = 1, highest = 76. Replacing 40 with "40" must fail validation.
For implementation basics, start with the Python Course; readers ready for applications can continue with DSA Using Python. Both are optional.
Keep learning
Randomized Algorithms Explained: Las Vegas, Monte Carlo and a Worked Quicksort Trace
Learn what random choices change in an algorithm, then trace randomized quicksort and calculate its expected comparisons and repeated-trial error.
Python Binary Files Explained: Bytes, Pickle and a Worked Record Trace
Trace five raw bytes, then follow three pickled student records through loading, filtering, searching and a safe marks update.
Introduction to Python: Core Concepts, Worked Trace and Exam Patterns
Build a reliable Python tracing method from names and types to loops and mutable lists. Follow one function across every iteration and check its exact output.
Python Decorators and Generators: yield, Closures and the Trace-the-Output Interview Questions
See decorators and generators as functions that retain state. Trace a wrapped call, expand @repeat(3), and follow countdown(3) through StopIteration.





