Check Ascending or Descending
In this step, you will learn how to check if a list is sorted in ascending or descending order. This is a common task in many programming scenarios, such as data validation and algorithm design.
To determine if a list is sorted, you can iterate through the list and compare adjacent elements. If each element is less than or equal to the next element, the list is sorted in ascending order. If each element is greater than or equal to the next element, the list is sorted in descending order.
Let's start by creating a Python script named check_order.py
in your ~/project
directory using the VS Code editor.
Here's the code to check if a list is sorted in ascending order:
def is_ascending(lst):
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True
numbers = [1, 2, 3, 4, 5]
print(is_ascending(numbers))
numbers = [1, 3, 2, 4, 5]
print(is_ascending(numbers))
Save the above code in check_order.py
. Now, run the script using the following command:
python ~/project/check_order.py
You should see the following output:
True
False
The first list [1, 2, 3, 4, 5]
is sorted in ascending order, so the function returns True
. The second list [1, 3, 2, 4, 5]
is not sorted in ascending order, so the function returns False
.
Now, let's add code to check if a list is sorted in descending order:
def is_descending(lst):
for i in range(len(lst) - 1):
if lst[i] < lst[i + 1]:
return False
return True
numbers = [5, 4, 3, 2, 1]
print(is_descending(numbers))
numbers = [5, 2, 3, 2, 1]
print(is_descending(numbers))
Add the above code to your check_order.py
file. The complete check_order.py
file should look like this:
def is_ascending(lst):
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True
def is_descending(lst):
for i in range(len(lst) - 1):
if lst[i] < lst[i + 1]:
return False
return True
numbers = [1, 2, 3, 4, 5]
print(is_ascending(numbers))
numbers = [1, 3, 2, 4, 5]
print(is_ascending(numbers))
numbers = [5, 4, 3, 2, 1]
print(is_descending(numbers))
numbers = [5, 2, 3, 2, 1]
print(is_descending(numbers))
Run the script again:
python ~/project/check_order.py
You should see the following output:
True
False
True
False
The list [5, 4, 3, 2, 1]
is sorted in descending order, so the function returns True
. The list [5, 2, 3, 2, 1]
is not sorted in descending order, so the function returns False
.
This exercise demonstrates how to check if a list is sorted in ascending or descending order using Python.