Sorting and Comparing Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
This checkpoint mixes everything from the module on data like customer orders, marks and staff records. Decide first which tool fits, then write it.
Rank with sorted, key and reverse
Ranking is ordering records by a score, usually highest first, with a second field to break ties. In Python it is sorted with a tuple key.
A leaderboard lists customers by total spend, highest first, and breaks ties by name. One key and one sorted call do it.
spend = {"Asha": 370, "Ravi": 400, "Meena": 400, "Diya": 50}ranked = sorted(spend.items(), key=lambda pair: (-pair[1], pair[0]))for place, (name, total) in enumerate(ranked, start=1): print(place, name, total)Example 1 · Top three earners
from operator import itemgetter
pay = [("Asha", 52000), ("Ravi", 61000), ("Meena", 47000), ("Kiran", 58000)]top = sorted(pay, key=itemgetter(1), reverse=True)[:3]print(top)[('Ravi', 61000), ('Kiran', 58000), ('Asha', 52000)]What this code does
- itemgetter(1) sorts by pay and reverse=True puts the highest first.
- The slice keeps the first three.
The key (-total, name) sorts highest total first and then alphabetically on a tie.
Pick the right tool
Do you need the whole order, one extreme, or a position? The answer decides between sorted, min or max, and bisect.
from bisect import bisect_right
amounts = [250, 40, 900, 120]print(sorted(amounts))print(max(amounts), min(amounts))print(bisect_right(sorted(amounts), 200))Example 2 · Grade bands
from bisect import bisect_right
cutoffs = [40, 60, 75, 90]print([ "FDCBA"[bisect_right(cutoffs, m)] for m in [95, 82, 67, 45, 30]])['A', 'B', 'C', 'D', 'F']
What this code does
- Each mark is placed among the cutoffs and the position picks the letter.
- A mark equal to a cutoff, such as 75, lands in the higher band.
sorted gives the full order, max and min scan once, and bisect needs a list that is already sorted.
Make your own objects sortable
A support team works on tickets by priority, then by title. A dataclass with order=True gives that order for free.
from dataclasses import dataclass
@dataclass(order=True)class Ticket: priority: int title: str
queue = [Ticket(2, "Login"), Ticket(1, "Refund"), Ticket(2, "Export")]print(min(queue))print([t.title for t in sorted(queue)])Example 3 · Department report
staff = [("Asha", "Sales", 52000), ("Ravi", "IT", 61000), ("Meena", "Sales", 47000), ("Kiran", "IT", 58000)]for name, dept, pay in sorted(staff, key=lambda s: (s[1], -s[2])): print(dept, name, pay)IT Ravi 61000 IT Kiran 58000 Sales Asha 52000 Sales Meena 47000
What this code does
- The key sorts by department and then by pay from highest to lowest.
- Tuple unpacking in the loop gives readable names.
min and sorted both use the order that order=True generated.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Print marks = [72, 95, 88, 60, 95] from highest to lowest as a list, without changing the original list.
[95, 95, 88, 72, 60]
Exercise 2· Easy
prices = [("Keyboard", 45), ("Monitor", 210), ("Cable", 8)]. Print the name of the cheapest product, then of the most expensive.
Cable Monitor
Exercise 3· Medium
staff = [("Asha", "Sales", 52000), ("Ravi", "IT", 61000), ("Meena", "Sales", 47000), ("Kiran", "IT", 58000)]. Print lines like IT Ravi 61000, ordered by department, then pay from highest to lowest.
IT Ravi 61000 IT Kiran 58000 Sales Asha 52000 Sales Meena 47000
Exercise 4· Medium
Create @dataclass(order=True) class Ticket with priority (int) and title (str). Sort Ticket(3, "Export"), Ticket(1, "Refund"), Ticket(3, "Login") and print the titles as a list.
['Refund', 'Export', 'Login']
Exercise 5· Medium
Cutoffs are [40, 60, 75, 90], grades "FDCBA". Write grade(mark) using bisect_right and print grade(75), grade(74) and grade(100) on separate lines.
B C A
Exercise 6· Hard
Orders: [("Asha", 250), ("Ravi", 90), ("Asha", 120), ("Meena", 400), ("Ravi", 310), ("Diya", 50)]. Add up the total per customer, then print the top three customers, highest total first and alphabetical on a tie, as Meena 400.
Meena 400 Ravi 400 Asha 370
Exercise 7· Hard
Write EventLog that keeps timestamps sorted with insort. count_between(low, high) returns how many timestamps lie between low and high inclusive. Add 50, 10, 30, 20, 40 and print count_between(15, 40) and count_between(0, 10).
3 1
Exercise 8· Hard
Marks: {"Asha": 95, "Ravi": 88, "Meena": 95, "Diya": 70, "Kiran": 88}. Print rank name mark per student, highest mark first, alphabetical on a tie. Students with the same mark share a rank, and the next rank skips ahead (1, 1, 3, 3, 5).
1 Asha 95 1 Meena 95 3 Kiran 88 3 Ravi 88 5 Diya 70
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of Sorting & Comparing
Python Programming has 21 sections, 110 modules and 609 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: Double-Ended Queues with collections.deque