def is_sorted(lst, key=lambda x: x):
for i, el in enumerate(lst[1:]):
if key(el) < key(lst[i]): # i is the index of the previous element
return False
return True
如果列表已经排序了,那么它将是 O (n)(而且在 for循环中是 O (n) !)因此,除非您希望它在大多数时候不被排序(并且相当随机) ,否则我将再次对列表进行排序。
我测试了基准 ABC0是长列表中最快的,而 all(l[i] >= l[i+1] for i in xrange(len(l)-1))是短列表中最快的。这些基准测试是在 MacBook Pro 201013”(Core2 Duo 2.66 GHz,4 GB 1067 MHz DDR3 RAM,Mac OS X 10.6.5)上运行的。
def is_sorted(lst):
it = iter(lst)
try:
prev = next(it)
except StopIteration:
return True
for x in it:
if prev > x: # For reverse, use <
return False
prev = x
return True
from itertools import tee, izip
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def is_sorted(iterable, key=lambda a, b: a <= b):
return all(key(a, b) for a, b in pairwise(iterable))
def issorted(x):
"""Check if x is sorted"""
return (numpy.diff(x) >= 0).all() # is diff between all consecutive entries >= 0?
我还没有真正将它与其他方法进行计时,但是我假设它比任何纯 Python 方法都要快,特别是对于大 n,因为 numpy.diff 中的循环(可能)直接在 C 中运行(n-1减法后跟 n-1比较)。
但是,如果 x 是一个无符号整型数,则需要小心,这可能会导致 numpy.diff ()中出现静默整型下溢,从而导致错误的正值。下面是修改后的版本:
def issorted(x):
"""Check if x is sorted"""
try:
if x.dtype.kind == 'u':
# x is unsigned int array, risk of int underflow in np.diff
x = numpy.int64(x)
except AttributeError:
pass # no dtype, not an array
return (numpy.diff(x) >= 0).all()
from itertools import imap, tee
import operator
def is_sorted(iterable, compare=operator.le):
a, b = tee(iterable)
next(b, None)
return all(imap(compare, a, b))
import numba
@numba.jit
def issorted(vec, ascending=True):
if len(vec) < 2:
return True
if ascending:
for i in range(1, len(vec)):
if vec[i-1] > vec[i]:
return False
return True
else:
for i in range(1, len(vec)):
if vec[i-1] < vec[i]:
return False
return True
def is_list_sorted(al):
llength =len(al)
for i in range (llength):
if (al[i-1] > al[i]):
print(al[i])
print(al[i+1])
print('Not sorted')
return -1
else :
print('sorted')
return true
from more_itertools import pairwise
class AssertionHelper:
@classmethod
def is_ascending(cls, data: iter) -> bool:
for a, b in pairwise(data):
if a > b:
return False
return True
@classmethod
def is_descending(cls, data: iter) -> bool:
for a, b in pairwise(data):
if a < b:
return False
return True
@classmethod
def is_sorted(cls, data: iter) -> bool:
return cls.is_ascending(data) or cls.is_descending(data)
from functools import reduce
# myiterable can be of any iterable type (including list)
isSorted = reduce(lambda r, e: (r[0] and (r[1] or r[2] <= e), False, e), myiterable, (True, True, None))[0]
[0] (sortedSoFarFlag) evaluates true if: prev_0 is true and (prev_1 is true or prev_2 <= elementValue)
[1] (firstTimeFlag): False
[2] (lastElementValue): elementValue
减少的最终结果是一个元组:
[0]: True/False depending on whether the entire list was in sorted order
[1]: True/False depending on whether the list was empty
[2]: the last element value
import numpy as np
# Trasform the list to a numpy array
x = np.array(l)
# check if ascendent sorted:
all(x[:-1] <= x[1:])
# check if descendent sorted:
all(x[:-1] >= x[1:])