How to Check if Given Array is Monotonic in Python

In this tutorial, we’ll learn how to program "How to Check if a Given Array is Monotonic in Python." We’ll focus on verifying whether the given array is monotonic, meaning it is either entirely non-increasing or non-decreasing. The objective is to accurately determine the monotonic nature of a list. A sample program will be provided to demonstrate the coding process, making it simple and easy to understand. So, let’s get started!

This topic is straightforward to understand. Just follow the instructions I provide, and you'll be able to complete it with ease. The program I'll show you demonstrates the proper way to determine if an array is monotonic. I'll also provide a simple and efficient method to achieve this effectively. So, let’s start coding!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def isMonotonic(A):
  2.     x, y = [], []
  3.     x.extend(A)
  4.     y.extend(A)
  5.     x.sort()
  6.     y.sort(reverse=True)
  7.     if(x == A or y == A):
  8.         return True
  9.     return False
  10.  
  11. while True:
  12.     print("\n================= Check if Given Array is Monotonic =================\n\n")
  13.  
  14.     mylist = [1, 2, 3, 4, 3]
  15.  
  16.     print("My array: ", mylist)
  17.  
  18.     print("\nGiven array is Monotonic: ", isMonotonic(mylist))
  19.  
  20.     opt = input("\nDo you want to try again?(yes/no): ")
  21.  
  22.     if opt.lower() == 'yes':
  23.         ret=False
  24.     elif opt.lower() == 'no':
  25.         ret=True
  26.         print("Exiting program....")
  27.     else:
  28.         print("Please enter yes/no:")
  29.         break
  30.  
  31.     if ret == False:
  32.         continue

This program checks if a given array is monotonic (entirely non-increasing or non-decreasing) by comparing it to its sorted and reverse-sorted versions, and then allows the user to repeat the process or exit.

Output:

There you have it we successfully created How to Check if Given Array is Monotonic in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment