Python Program to Check if an Array is Monotonic

1. Introduction

An array is monotonic if it is entirely non-increasing or non-decreasing. Monotonic arrays are a simple yet important concept in computer science, particularly in algorithm design and analysis, as they often simplify searching and sorting. Determining whether an array is monotonic can be crucial in optimizing algorithms and ensuring data integrity. This blog post will explore a Python program designed to check if a given array is monotonic.

2. Program Steps

1. Define the array to be checked.

2. Determine if the array is non-decreasing (every element is equal to or greater than the previous element).

3. Determine if the array is non-increasing (every element is equal to or less than the previous element).

4. If either condition is true, the array is monotonic.

5. Display the result.

3. Code Program

# Step 1: Define the array
array = [6, 5, 4, 4]

# Function to check if the array is monotonic
def is_monotonic(array):
    # Step 2 & 3: Check for non-decreasing or non-increasing
    return (all(array[i] <= array[i + 1] for i in range(len(array) - 1)) or
            all(array[i] >= array[i + 1] for i in range(len(array) - 1)))

# Step 4: Determine if the array is monotonic
monotonic = is_monotonic(array)

# Step 5: Display the result
print(f"The array {array} is monotonic: {monotonic}")

Output:

The array [6, 5, 4, 4] is monotonic: True

Explanation:

1. The program starts by defining an array that needs to be checked for monotonicity.

2. It defines a function is_monotonic that checks if the array is either non-decreasing or non-increasing. This is achieved by using Python's all() function in conjunction with a generator expression that iterates through the array, comparing each element with the next one.

3. The function is_monotonic returns True if either condition (non-decreasing or non-increasing) is met for the entire array, indicating the array is monotonic. Otherwise, it returns False.

4. The result of the is_monotonic function is stored in the variable monotonic and printed out, showing whether the input array is monotonic.

5. This approach demonstrates a concise and efficient way to determine the monotonicity of an array in Python, using comprehension and the all() function to evaluate the array's elements in a single line of code.

Comments