Course 3.1Lesson 5 of 5
In this project we rank a class. The students are pairs of a name and a mark, and the ranking sorts by mark with the biggest first, and by name for equal marks, using a key that is a tuple. Ties get the same rank, and the next rank is skipped, as in a race. The program also shows the top three and uses binary search on the sorted marks to ask whether a mark is there. We plan the table of expected ranks by hand, build the program in steps, test the ties and the edges, and extend the ranking with a search by name and a median.
Try the code and the simulations beside the lesson.
After this lesson you can
A class has six students, each with a mark. The teacher wants a ranking:
The data is Asha 72, Ravi 85, Meera 72, Kabir 90, Ana 58 and Dev 85. Work out the table by hand.
| Rank | Name | Mark |
|---|---|---|
| 1 | Kabir | 90 |
| 2 | Dev | 85 |
| 2 | Ravi | 85 |
| 4 | Asha | 72 |
| 4 | Meera | 72 |
| 6 | Ana | 58 |
Look at the ranks. Dev and Ravi share rank 2. The next rank is 4, not 3, because three students are above Asha and Meera (Kabir, Dev and Ravi), so they are in fourth place. This is how a race works: if two runners tie for second, nobody is third, and the next runner is fourth. Ana is sixth, because five students are above her.
Test the data that breaks the rules.
| Test | Expected |
|---|---|
| everyone has the same mark | everyone has rank 1, in alphabetical order |
| one student only | rank 1, and the top three has one name |
| no ties at all | ranks 1, 2, 3, ... |
| a mark that is not there (such as 77) | False |
| the first and the last mark of the sorted list | True |
The first row is the real test of the rank rule. If all the marks are equal, every student must have rank 1, and the program must not give rank 6 to the last one.
Give two students the same top mark. Both are rank 1, and the next student is rank 3, not 2.
Pick one or two, and do them without looking at a solution. Write the expected answers first.
find_rank(ranked, name) that gives the rank of a name, or None.statistics.median.reverse=True with the name: it reverses the names too, and Z comes before A for equal marks.students with .sort() when you still need the old order.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:
Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
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.