livepython.net

204. Python Program to Find the Second Largest Number in a List

MediumPhase 2 · Practice

This one takes a few steps. It uses split(), max() and a for loop, and you know all three.

Overview

Finding the second largest number is one of the most common Python interview questions. The trap is a list where the largest number appears more than once.

Problem Statement

Omar runs a game club. The scores of a game are on one line, and Omar wants to give a prize to the second best score.

  • The second largest number must be a different value from the largest. In 4 9 2 9 7, the largest is 9 and the second largest is 7.
  • Print Second largest: <number>.
  • There is no second largest when the list has only one number, or when all the numbers are the same. Then print No second largest number.
  • Do not use sort() or sorted().

Examples

Example 1. Input 4 9 2 9 7 gives:

Second largest: 7

Why: 9 is the largest, and it appears twice. The biggest number that is smaller than 9 is 7.

Example 2. Input 5 5 5 gives:

No second largest number

Why: all the numbers are 5, so no number is smaller than the largest.

Input

One line of whole numbers, with one space between them (1 number or more). The numbers can be negative. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: Second largest: <number> or No second largest number. The tests try 8 different inputs, also negative numbers and a list with one number.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Second largest: 7

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.