Is there a pythonic way to check if a list is already sorted in ASC
or DESC
listtimestamps = [1, 2, 3, 5, 6, 7]
something like isttimestamps.isSorted()
that returns True
or False
.
I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.
If you want the fastest way for numpy arrays, use numba, which if you use conda should be already installed
The code will be fast because it will be compiled by numba
and then:
I would just use
unless it's a very big list in which case you might want to create a custom function.
if you are just going to sort it if it's not sorted, then forget the check and sort it.
and don't think about it too much.
if you want a custom function, you can do something like
This will be O(n) if the list is already sorted though (and O(n) in a
for
loop at that!) so, unless you expect it to be not sorted (and fairly random) most of the time, I would, again, just sort the list.Actually we are not giving the answer anijhaw is looking for. Here is the one liner:
For Python 3:
This is in fact the shortest way to do it using recursion:
if it's Sorted will print True else will print out False
Not very Pythonic at all, but we need at least one
reduce()
answer, right?The accumulator variable simply stores that last-checked value, and if any value is smaller than the previous value, the accumulator is set to infinity (and thus will still be infinity at the end, since the 'previous value' will always be bigger than the current one).
A beautiful way to implement this is to use the
imap
function fromitertools
:This implementation is fast and works on any iterables.