Program to check whether the given array is monotonic in Python

Introduction

In this article, we will understand the python code to check whether the given array is monotonic or not. A monotonic array is of two types: increasing monotonic and decreasing monotonic.

A increasing monotonic array is the one which follows the condition; for all Array[i] <= Array[i+1]. Whereas a decreasing monotonic array follows the nature Array[i] >= Array[i+1].

Program

def check_monotone(arr):
#Return True if it follows monotonic condition
    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)))
arr = [3, 5, 7, 19]
print("The given array is monotonic ? True/False:",check_monotone(arr))

 

Output:

Program to check whether the given array is monotonic

Explanation

In the above python code, we have created an array which is increasing monotonic in nature. The function check_monotone() will check the condition of increasing and decreasing monotone and returns the Boolean value depending upon the condition.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.