Python bootcamp · Lab 19

Second largest

mediumLists12 minLesson: Sort Lists

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a line of integers and print the second largest distinct value.

The catch is "distinct": if the biggest number appears twice, the second largest is still the next different number down.

Input. One line: integers separated by spaces (at least two distinct values).

Output. One integer: the second largest distinct value.

Examples

Example 1 — Two 7s collapse to one, so second largest is 4.
Input
4 1 7 7 3
Output
4
Example 2
Input
10 20 30
Output
20
Hint
  1. set(nums) drops duplicates.
  2. sorted(...) puts them ascending, so index -2 is the second largest.
Show correct code

Peek only after you have tried. You can still Check your own version.

nums = list(map(int, input().split()))
print(sorted(set(nums))[-2])
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.