Course 4.2Lesson 3 of 5
A class report summarises the marks, ranks the students, answers a question such as who is above the mean, and searches for a mark. The marks are in a dictionary with the name as the key. The statistics module gives the mean, the median and the standard deviation, and an empty list raises a StatisticsError, which the function catches and answers with None. The ranking sorts by two things with a key that is a tuple, the mark with a minus sign and then the name. Binary search needs a sorted list, and is fast. We plan the expected numbers by hand, put each job in a function, and test the edges, such as an empty class, one student and equal marks.
Try the code and the simulations beside the lesson.
After this lesson you can
statistics module, sorting and searching in one tool,A class report has to do four jobs: summarise the marks, rank the students, answer a question such as "who is above the mean?", and search for a mark. The marks live in a dictionary: the key is the name, and the value is the mark.
Five students have the marks Asha 92, Ravi 78, Meera 85, Kabir 64 and Zoya 78. Work out by hand.
R comes before Z), then Kabir 64.Predict first. Will the mean be higher or lower than the median? What will the program say about an empty class? Then run it.
A sorted list can be searched fast. Binary search looks at the middle and throws away half of the list in each step.
sorted() makes a new list, so the marks as typed stay in their order for the rest of the report.
| Test | Expected |
|---|---|
| an empty class | summary gives None, the ranking is empty |
| one student | the mean and the median are the mark, the spread is 0 |
| everyone with the same mark | the spread is 0, everyone is rank 1 or tied |
| two equal marks | the names decide the order |
| nobody above the mean | an empty list (it can happen when all marks are equal) |
| a mark that is not there | None from the binary search |
The last-but-one row is a surprise: if all the marks are equal, then nobody is more than the mean, so the list of those above is empty. That is the correct answer, but a user may not expect it.
Pick one or two, and do them without looking at a solution. Write the expected answers first.
Dev with 70, and say who is above the mean now (hand first!).mean) for an empty class. Catch the StatisticsError.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
statistics gives the mean, the median and the standard deviation. An empty list raises StatisticsError.sorted(..., key=...) ranks, and a minus sign reverses a number.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
-pair[1] used in the key of the ranking?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.