Transforming and Combining Data · practice
Summarize Meaningful Data
The previous lesson arranged attempt records into a useful order. A program often needs another view of the same collection: a few facts such as the total, lowest, and highest score.
We could calculate each fact with a
scores = [8, 6, 9]
sum(scores) # 23
min(scores) # 6
max(scores) # 9
Their names state the requested result directly, which keeps the purpose of the calculation visible.
Select meaningful data first
An attempt record contains several numbers:
{
"score": 8,
"total": 10,
"seconds": 75,
}
Do not pass whole
scores = []
for attempt in attempts:
scores.append(attempt["score"])
Then summarize scores.
Decide what an empty collection means
sum([]) returns 0, but min([]) and max([]) raise
Your function’s contract must choose a meaning. For this lesson, an empty attempt
{
"total": 0,
"lowest": None,
"highest": None,
}
None makes the absence of a lowest or highest score explicit.
The empty list is falsy, so the function can handle it directly:
if not scores:
return {
"total": 0,
"lowest": None,
"highest": None,
}
Why should lowest be None for an empty score list?
Summarize attempt scores
Build one list of score values. Return total, lowest, and highest, with the documented empty result.
Task
Complete score_summary.
Collect each attempt’s
score.For an empty
, return total: 0,lowest: None, andhighest: None.Otherwise use
sum,min, andmax.Return a new summary
.
Do not modify the attempt records.