Python Program to check if given array is Monotonic
In this article, we will learn to check whether the array is monotonic or not using the python program.
What is the monotonic array?
An array that is continuous increases or continuous decreases is said to be a monotonic array.
Explanation
Let's take any array,
arr = [1, 2, 3, 4, 5, 6 ]
when i <= j
arr[i] <= arr[j]
Then this array is said to be monotnic increasing.
And,
arr = [11, 8, 5, 2, 1]
when i >=j
arr[i] >= arr[j]
Then this array is said to be monotonic decreasing.
Program
1 2 3 4 5 6 7 8 9 10 11 | # make a function that check the condition for monotonics def monotonic(arr): # if all the elements in the increase order or decrease order then return true. return (all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) or all(arr[i] >= arr[i + 1] for i in range(len(arr) - 1))) # array initisilze arr = [1,5,7,11,21,32] # print the result print(monotonic(arr)) |
Output
True