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
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With