Print statistics
- Algorithms course
- Intermediate
- Lesson 24/80
- 4 min
Print the lowest, highest and median score.
Print statistics
In the last step we print the lowest and highest scores from the sorted array. If the sorted array is [78, 85, 88, 90, 92] then min is 78, max is 92.
In a sorted array min is the first element sorted[0], max is the last sorted[-1]. We can print them on separate lines.
This is the final piece of the project; all functions work together.
Min and max
In a sorted array the smallest value is the first element sorted[0], the largest is the last sorted[-1]. No search is needed.
This is a side benefit of sorting: min/max queries on sorted data are O(1). On unsorted data they are O(n).
This difference matters in statistics; keeping data sorted brings speed.
Practice Print statistics
Write print_stats(scores). Sort, print min and max. Print 78 92 with print_stats(init_scores()).
Starter code
def init_scores():
# Return score array
return [85, 92, 78, 90, 88]
def merge_sort_scores(scores):
# Sort scores
if len(scores) <= 1:
return scores
mid = len(scores) // 2
left = merge_sort_scores(scores[:mid])
right = merge_sort_scores(scores[mid:])
return merge(left, right)
def top_k(scores, k):
# Take top k
sorted_scores = merge_sort_scores(scores)
return sorted_scores[-k:]
def print_stats(scores):
# Print statisticsSample solution
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i]); i += 1
else:
result.append(right[j]); j += 1
result.extend(left[i:]); result.extend(right[j:])
return result
def init_scores():
# Return score array
return [85, 92, 78, 90, 88]
def merge_sort_scores(scores):
# Sort scores
if len(scores) <= 1:
return scores
mid = len(scores) // 2
left = merge_sort_scores(scores[:mid])
right = merge_sort_scores(scores[mid:])
return merge(left, right)
def top_k(scores, k):
# Take top k
sorted_scores = merge_sort_scores(scores)
return sorted_scores[-k:]
def print_stats(scores):
# Print statistics
sorted_scores = merge_sort_scores(scores)
print(sorted_scores[0], sorted_scores[-1])
print_stats(init_scores())Expected output
78 92
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Print statistics: match the terms
| Term | Meaning |
|---|---|
Min |
sorted[0] |
Max |
sorted[-1] |
Sort |
merge_sort_scores |
Top N |
[-k:] |
2 Where is max in a sorted array?
- The last element Correct answer
- The median
- Random
- The first element
Explanation: The last element
3 Min access
print(sorted_scores[____])
print(sorted_scores[0])
Explanation: 0 is right.