Python - Как проверить монотонность списка
Какой эффективный и питонный способ проверить монотонность списка?
то есть что оно имеет монотонно увеличивающиеся или уменьшающиеся значения?
Примеры:
[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
Ответы
Ответ 1
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)
Ответ 2
Если у вас есть большие списки номеров, лучше всего использовать numpy, а если вы:
import numpy as np
def monotonic(x):
dx = np.diff(x)
return np.all(dx <= 0) or np.all(dx >= 0)
должен сделать трюк.
Ответ 3
import itertools
import operator
def monotone_increasing(lst):
pairs = zip(lst, lst[1:])
return all(itertools.starmap(operator.le, pairs))
def monotone_decreasing(lst):
pairs = zip(lst, lst[1:])
return all(itertools.starmap(operator.ge, pairs))
def monotone(lst):
return monotone_increasing(lst) or monotone_decreasing(lst)
Этот подход O(N)
в длине списка.
Ответ 4
@6502 имеет идеальный код для списков, я просто хочу добавить общую версию, которая работает для всех последовательностей:
def pairwise(seq):
items = iter(seq)
last = next(items)
for item in items:
yield last, item
last = item
def strictly_increasing(L):
return all(x<y for x, y in pairwise(L))
def strictly_decreasing(L):
return all(x>y for x, y in pairwise(L))
def non_increasing(L):
return all(x>=y for x, y in pairwise(L))
def non_decreasing(L):
return all(x<=y for x, y in pairwise(L))
Ответ 5
import operator, itertools
def is_monotone(lst):
op = operator.le # pick 'op' based upon trend between
if not op(lst[0], lst[-1]): # first and last element in the 'lst'
op = operator.ge
return all(op(x,y) for x, y in itertools.izip(lst, lst[1:]))
Ответ 6
Вот функциональное решение с использованием reduce
сложности O(n)
:
is_increasing = lambda L: reduce(lambda a,b: b if a < b else 9999 , L)!=9999
is_decreasing = lambda L: reduce(lambda a,b: b if a > b else -9999 , L)!=-9999
Замените 9999
верхним пределом ваших значений и -9999
с нижним пределом. Например, если вы тестируете список цифр, вы можете использовать 10
и -1
.
Я тестировал свою производительность против @6502 answer и быстрее.
Дело True: [1,2,3,4,5,6,7,8,9]
# my solution ..
$ python -m timeit "inc = lambda L: reduce(lambda a,b: b if a < b else 9999 , L)!=9999; inc([1,2,3,4,5,6,7,8,9])"
1000000 loops, best of 3: 1.9 usec per loop
# while the other solution:
$ python -m timeit "inc = lambda L: all(x<y for x, y in zip(L, L[1:]));inc([1,2,3,4,5,6,7,8,9])"
100000 loops, best of 3: 2.77 usec per loop
Случай False от второго элемента: [4,2,3,4,5,6,7,8,7]
:
# my solution ..
$ python -m timeit "inc = lambda L: reduce(lambda a,b: b if a < b else 9999 , L)!=9999; inc([4,2,3,4,5,6,7,8,7])"
1000000 loops, best of 3: 1.87 usec per loop
# while the other solution:
$ python -m timeit "inc = lambda L: all(x<y for x, y in zip(L, L[1:]));inc([4,2,3,4,5,6,7,8,7])"
100000 loops, best of 3: 2.15 usec per loop
Ответ 7
Я приурочил все ответы в этом вопросе в разных условиях и обнаружил, что:
- Сортировка была самой быстрой с длинным выстрелом, если список уже был монотонно возрастающим.
- Сортировка была самой медленной с длинным выстрелом, если список был перетасован/случайным, или если количество элементов не в порядке больше 1. Более того, список, конечно, соответствует более медленному результату.
- Метод Майкла Дж. Барберса был самым быстрым, если список был в основном монотонно возрастающим или полностью случайным.
Вот код, чтобы попробовать:
import timeit
setup = '''
import random
from itertools import izip, starmap, islice
import operator
def is_increasing_normal(lst):
for i in range(0, len(lst) - 1):
if lst[i] >= lst[i + 1]:
return False
return True
def is_increasing_zip(lst):
return all(x < y for x, y in izip(lst, islice(lst, 1, None)))
def is_increasing_sorted(lst):
return lst == sorted(lst)
def is_increasing_starmap(lst):
pairs = izip(lst, islice(lst, 1, None))
return all(starmap(operator.le, pairs))
if {list_method} in (1, 2):
lst = list(range({n}))
if {list_method} == 2:
for _ in range(int({n} * 0.0001)):
lst.insert(random.randrange(0, len(lst)), -random.randrange(1,100))
if {list_method} == 3:
lst = [int(1000*random.random()) for i in xrange({n})]
'''
n = 100000
iterations = 10000
list_method = 1
timeit.timeit('is_increasing_normal(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations)
timeit.timeit('is_increasing_zip(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations)
timeit.timeit('is_increasing_sorted(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations)
timeit.timeit('is_increasing_starmap(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations)
Если список уже монотонно увеличивался (list_method == 1
), самым быстрым и медленным был:
- отсортирован
- Starmap
- нормально
- молния
Если список был в основном монотонно возрастающим (list_method == 2
), самым быстрым для самого медленного был:
- Starmap
- молния
- нормально
- отсортирован
(независимо от того, была ли скобка или zip самой быстрой, зависит от выполнения, и я не мог идентифицировать шаблон. Starmap, как правило, быстрее)
Если список был полностью случайным (list_method == 3
), самым быстрым и медленным был:
- Starmap
- молния
- нормально
- отсортировано (очень плохо)
Ответ 8
L = [1,2,3]
L == sorted(L)
L == sorted(L, reverse=True)
Ответ 9
Это возможно с помощью Pandas, которые вы можете установить через pip install pandas
.
import pandas as pd
Следующие команды работают со списком целых или с плавающей точкой.
pd.Series(mylist).is_monotonic_increasing
Строго монотонно возрастающий (>):
myseries = pd.Series(mylist)
myseries.is_unique and myseries.is_monotonic_increasing
Альтернатива с использованием недокументированного частного метода:
pd.Index(mylist)._is_strictly_monotonic_increasing
pd.Series(mylist).is_monotonic_decreasing
Строго монотонно убывающий (<):
myseries = pd.Series(mylist)
myseries.is_unique and myseries.is_monotonic_decreasing
Альтернатива с использованием недокументированного частного метода:
pd.Index(mylist)._is_strictly_monotonic_decreasing
Ответ 10
>>> l = [0,1,2,3,3,4]
>>> l == sorted(l) or l == sorted(l, reverse=True)