How to check if given array is Monotonic or not in Python

In this tutorial, we will learn how to check if a given array is monotonic or not in Python. We can check either it is monotonic or not if it is monotonic check it is monotonic increasing or monotonic decreasing.

Python program to check if a given array is monotonic or not

In Python, it is easy to check whether the number is monotonic or not. Let’s start with an example in Python.

#creating a list
list_array = list()

#check if given array is monotonic or not
def is_Monotonic(A):
    if all(A[i] <= A[i+1] for i in range (len(A)-1)):
        return "Monotonic increasing"
    elif all(A[i] >= A[i+1] for i in range (len(A)-1)):
        return "Monotonic decreasing"
    return "not Monotonic array"

n = int(input("input size of the array :"))


#input and append that values
for i in range(n):
    s=int(input("input value for position {} : ".format(i)))
    list_array.append(s)

#output of reqired result
print("Input array is "+is_Monotonic(list_array))


def() :

The anonymous inline function consists of a single expression that is evaluated when the function is called and this function can be represented as def  variable_name(argument).

range()

Syntax 

range(start:stop:step)
  • range() is a built-in-function of python, which returns a range object.
  • The arguments to the range function must be an integer.
  • If the start value is erased, it defaults to 0 (zero).

.format syntax

str.format(args)

Perform a string operation.

.append Syntax :

list_array.append(s)

In this operation .append() method appends an element to the end of the list.

OUTPUT

Monotonic increasing for array size 2

input size of the array :2 

input value for position 0 : 1 

input value for position 1 : 4 

Input array is Monotonic increasing

Monotonic increasing for Array size 3

input size of the array :3 

input value for position 0 : 11 

input value for position 1 : 22 

input value for position 2 : 33

 Input array is Monotonic increasing

Monotonic decreasing For Array size 3

input size of the array :3 

input value for position 0 : 20 

input value for position 1 : 15

 input value for position 2 : 10 

Input array is Monotonic decreasing


In the above example, is_Monotonic(A):

is used to check whether the array is monotonic or not. If it is monotonic check it is monotonic increasing or monotonic decreasing.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *