How to check if an array is monotonic in Python

2 Answers

0 votes
# check adjacent list elements to determine if the array is monotone increasing (or decreasing)

def isMonotonic(lst) :
    increase = 0
    decrease = 0
    size = len(lst)
    i = 0
    
    while (i < size - 1) :
        if (lst[i] > lst[i + 1]) :
            increase = 1
        if (lst[i] < lst[i + 1]) :
            decrease = 1
        if (increase == 1 and decrease == 1) :
            return False
        i += 1
        
    return True

lst = [1, 3, 4, 6, 8, 9, 11, 17, 18]

print(isMonotonic(lst))




'''
run:

True

'''

 



answered Feb 22, 2024 by avibootz
0 votes
# check adjacent list elements to determine if the array is monotone increasing (or decreasing)

def strictly_increasing(lst):
    return all(x < y for x, y in zip(lst, lst[1:]))

def strictly_decreasing(lst):
    return all(x > y for x, y in zip(lst, lst[1:]))

def isMonotonic(lst):
    return strictly_increasing(lst) or strictly_decreasing(lst)

lst = [1, 3, 4, 6, 8, 9, 11, 17, 18]

print(isMonotonic(lst))




'''
run:

True

'''

 



answered Feb 22, 2024 by avibootz

Related questions

1 answer 111 views
111 views asked Feb 23, 2024 by avibootz
1 answer 113 views
1 answer 185 views
1 answer 143 views
1 answer 141 views
1 answer 100 views
100 views asked Feb 22, 2024 by avibootz
1 answer 103 views
...