Write is_sorted(nums) that returns True when every number is less than or equal to the next. Print YES or NO. Think about edge cases such as one number and equal neighbours.
What to build
A function that has to handle edge cases correctly.
Requirements
- Write
is_sorted(nums), returningTruewhen each number is less than or equal to the next. - Print
YESorNO.
Input
The first line has n (1 to 1000). The second line has n whole numbers.
Output
YES or NO.
Constraints
n is from 1 to 1000.
Example
Input:
4
1 2 2 5
Output:
YES
Why it works
With one number there are no neighbours to compare, so the loop does not run and the answer is correctly True.
Examples
Example 1 · Input
4 1 2 2 5
Expected output
YES
Example 2 · Input
3 3 1 2
Expected output
NO
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Compare each number with the next one.
Hint 2
A list of one number is sorted.
Solution
Show one correct solution (try it yourself first)
def is_sorted(nums):
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return False
return True
n = int(input())
nums = [int(x) for x in input().split()]
print("YES" if is_sorted(nums) else "NO")