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.- def isMonotonic(A):
- x, y = [], []
- x.extend(A)
- y.extend(A)
- x.sort()
- y.sort(reverse=True)
- if(x == A or y == A):
- return True
- return False
- while True:
- print("\n================= Check if Given Array is Monotonic =================\n\n")
- mylist = [1, 2, 3, 4, 3]
- print("My array: ", mylist)
- print("\nGiven array is Monotonic: ", isMonotonic(mylist))
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- 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
Add new comment
- 62 views