Read a list of different whole numbers and print the second largest.
What to build
A program that finds the runner-up.
Requirements
- Read the list of different numbers.
- Print the second largest.
Input
The first line has n (2 to 1000). The second line has n different whole numbers.
Output
The second largest number.
Constraints
n is from 2 to 1000, and all the numbers are different.
Example
Input:
4
4 9 2 7
Output:
7
Why it works
Sorting puts the numbers in order, so the second from the end is the answer. Tracking the two best values in one loop would work as well.
Examples
Example 1 · Input
4 4 9 2 7
Expected output
7
Example 2 · Input
2 1 2
Expected output
1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
After nums.sort(), the largest is nums[-1] and the second largest nums[-2].
Solution
Show one correct solution (try it yourself first)
n = int(input()) nums = [int(x) for x in input().split()] nums.sort() print(nums[-2])