16. Second largest
Write a function second_largest(numbers) that takes a list of whole numbers and returns the second largest
different number in it. Repeats count once: in [5, 5, 3] the largest is 5 and the second largest is 3.
If the list has fewer than two different numbers (it is empty, has one number, or every number is the same), return
None.
Example 1
numbers = [4, 9, 2, 7]7Example 2
numbers = [5, 5, 3]3Example 3
numbers = [8]NoneConstraints
numbershas 0 to 100 items, in any order.- Each item is a whole number from -1000 to 1000. Numbers can repeat.
Submit also runs 4 more tests you can't see.
Practises Lists (lesson 9).
- Repeats count once, so remove them first:
set(numbers)keeps one of each. sorted(set(numbers))gives the different numbers from smallest to largest, so the second largest is the one at index-2.- Check the length before you take index
-2: with fewer than 2 different numbers (an empty list,[8],[1, 1, 1]), returnNone.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def second_largest(numbers):
"""Find the second largest different number.
numbers: list of int; may be empty, may repeat
Returns: int, or None if there are fewer than two
different numbers
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.