Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A class Dog has the attributes name and age. Make a list of four dogs and show their names from the oldest to the youngest, and for dogs of the same age, in alphabetical order.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Use sorted with a key function that returns a tuple: the age with a minus sign (so that the oldest comes first), and then the name.
Check. The two dogs of age 5 come first, Bella and Coco in alphabetical order, then the two of age 3, Max and Rex. The output is Bella 5, Coco 5, Max 3, Rex 3.
Answer: Bella, Coco, Max, Rex.
Log in to join the discussion.
Loading…