Sorting like at work
Python · Unit 23: Searching and sorting
- Full plan
- Python
- 8 exercises
At work nobody writes their own sort: sorted is already written and tested. What you do write is the criterion.
To sort by two things, the key returns a tuple. The first values get compared first and, only on a tie, the second ones.
people = [
("Ana", 3),
("Luke", 1),
("Sophie", 3),
]
def rule(p):
return (p[1], p[0])
print(sorted(people, key=rule))Prints
[('Luke', 1), ('Ana', 3), ('Sophie', 3)]The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete it so they go from most points to fewest, and ties alphabetically.
3. Multiple choice
You want most points first and, on a tie, names from A to Z. Why is
reverse=Truenot enough?4. Find the bug
It should print the grades in order, but it prints
None. Which line has the error?5. Predict the output
What does this code print?
6. Put the lines in order
Build the function that returns the names from most points to fewest, and ties from A to Z.
7. Predict the output
What does this code print?
8. Multiple choice
You can write selection sort and merge sort now. When is it worth using them in a real program?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.