Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to check list monotonicity

What would be an efficient and pythonic way to check list monotonicity?
i.e. that it has monotonically increasing or decreasing values?

Examples:

[0, 1, 2, 3, 3, 4]   # This is a monotonically increasing list [4.3, 4.2, 4.2, -2]  # This is a monotonically decreasing list [2, 3, 1]            # This is neither 
like image 881
Jonathan Livni Avatar asked Feb 13 '11 08:02

Jonathan Livni


People also ask

How do you know if an array is monotonic?

Traverse the array arr[] from i = 0 to N-2 and check if the array is increasing in order. Traverse the array arr[] from i = 0 to N-2 and check if the array is decreasing in order. If neither of the above two is true, then the array is not monotonic.

How do you check if a list is increasing in Python?

In this approach we first slice each element compare its value to the next element that is sliced. If all such comparisons hold true then we conclude the list is strictly in increasing order.

How do you find monotonicity?

To tell if a function is monotonically increasing, simply find its derivative and see if it is always positive on its domain. If the derivative of a function is always positive (or greater than or equal to zero), then the function is monotonically increasing.


2 Answers

It's better to avoid ambiguous terms like "increasing" or "decreasing" as it's not clear if equality is acceptable or not. You should always use either for example "non-increasing" (clearly equality is accepted) or "strictly decreasing" (clearly equality is NOT accepted).

def strictly_increasing(L):     return all(x<y for x, y in zip(L, L[1:]))  def strictly_decreasing(L):     return all(x>y for x, y in zip(L, L[1:]))  def non_increasing(L):     return all(x>=y for x, y in zip(L, L[1:]))  def non_decreasing(L):     return all(x<=y for x, y in zip(L, L[1:]))  def monotonic(L):     return non_increasing(L) or non_decreasing(L) 
like image 65
6502 Avatar answered Sep 22 '22 04:09

6502


If you have large lists of numbers it might be best to use numpy, and if you are:

import numpy as np  def monotonic(x):     dx = np.diff(x)     return np.all(dx <= 0) or np.all(dx >= 0) 

should do the trick.

like image 26
Autoplectic Avatar answered Sep 23 '22 04:09

Autoplectic