203. Python Program to Check If a List Is Sorted
EasyPhase 1 · Warm-up
You know split(), range() and list positions. That is all you need here.
Overview
Checking if a list is sorted is a common interview warm-up. Some fast search methods, like binary search, only work when the data is in order.
Problem Statement
Zara works in a library. The numbers of the books on a shelf should go from small to big.
A list is sorted when each number is the same as or bigger than the number before it. A list with one number is sorted too.
Read the numbers. Print The list is sorted or The list is not sorted.
Steps
- Read the line and split it into a list.
- Start by saying the list is sorted.
- From the second number on, compare each number with the number before it.
- If a number is smaller than the number before it, the list is not sorted.
- Print the right line.
Examples
Example 1. Input 1 3 3 7 9 gives:
The list is sorted
Why: each number is the same as or bigger than the one before it. 3 and 3 are equal, and that is fine.
Example 2. Input 2 5 4 8 gives:
The list is not sorted
Why: 4 comes after 5, and 4 is smaller than 5.
Input
One line of whole numbers, with one space between them (1 number or more). 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: The list is sorted or The list is not sorted. The tests try 6 different inputs, also one number and equal numbers.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.
This is the last question of Phase 1 · Warm-up. The next question starts Phase 2.