This tutorial will discuss about unique ways to check if a numpy array is sorted in descending order.
Table Of Contents
Method 1: Using numpy.diff()
We can use the numpy.diff()
method to check if a NumPy array is sorted in descending order. The numpy.diff()
method accepts an array as an argument, and returns an array containing the difference between every consequitive element. Basically it will return an array containing n-th discrete difference along the given axis. For example, if we pass an array arr
to the diff() methid, then it will return an array out
. Where,
out[i] = arr[i+1] - arr[i]
The ith element of returned array will be the difference between ith
and (i+1)th
element of passed numpy array.
Then we can check if all the values in the returned array are less than or equal to zero. If yes, then it means that the array is sorted in descending order.
Let’s see the complete example,
import numpy as np # Create a NumPy Array arr = np.array([55, 44, 43, 22, 20, 16]) # Check if array is sorted in descending order if np.all(np.diff(arr) <= 0): print("The NumPy Array is sorted in descending order") else: print("The NumPy Array is not sorted in descending order")
Output
Frequently Asked:
- Check if all elements in NumPy Array are False
- Check if all elements in a NumPy array are unique
- Check if all elements in a NumPy Array are equal to value
- Check if a value exists in a NumPy Array
The NumPy Array is sorted in descending order
Method 2: Using all() method
Iterate over all the elements of NumPy array by the index position. Check if any element is smaller than or equal to the element next to it. If yes, then it means array is not sorted, otherwise array is sorted in descending order.
Let’s see the complete example,
import numpy as np # Create a NumPy Array arr = np.array([55, 44, 43, 22, 20, 16]) # Check if array is sorted in descending order if all(arr[i] >= arr[i+1] for i in range(len(arr)-1)): print("The NumPy Array is sorted in descending order") else: print("The NumPy Array is not sorted in descending order")
Output
The NumPy Array is sorted in descending order
Summary
We learned about two ways to check if a NumPy array is sorted in descending order. Thanks.