Pythonic way to check if a list is sorted or not
Here is a one liner:
all(l[i] <= l[i+1] for i in range(len(l) - 1))
If using Python 2, use xrange
instead of range
.
For reverse=True
, use >=
instead of <=
.
How to check if a list is ordered?
If you are using MSTest, you may want to take a look at CollectionAssert.AreEqual.
Enumerable.SequenceEqual may be another useful API to use in an assertion.
In both cases you should prepare a list that holds the expected list in the expected order, and then compare that list to the result.
Here's an example:
var studyFeeds = Feeds.GetStudyFeeds(2120, DateTime.Today.AddDays(-200), 20);
var expectedList = studyFeeds.OrderByDescending(x => x.Date);
Assert.IsTrue(expectedList.SequenceEqual(studyFeeds));
How to check if a list is sorted consecutively?
The only way to check if the list is sorted is to go through every item in the list and compare it to the next item, in which case you might as well just call sort in the first place as that will perform the exact same check and sort anything out of order
Edit:
i'm suspicious of the fact that you keep using the word "consecutively"
if you are looking for Missing or Duplicated Values then that is not mentioned in your question at all, but if that is the case a simple left join will do that for you with no need of sorting
var min = collectionGroups.Min(x => x.Sequence);
var deviation = collectionGroups.Max(x => x.Sequence) - min;
var result = from i in Enumerable.Range(min, deviation )
join c in collectionGroups on i equals c.Sequence into grp;
from g in grp.DefaultIfEmpty()
where g.Count() != 1
select new{ ID=g.Key, Count=g.Count()};
this will then return a list of duplicate or missing values no sorting needed
Edit in reply to comment by juunas
var data = Enumerable.Range(0, 20000000).ToList();
bool sort = false;
for (int i = 0; i < data.Count - 1; i++)
{
if (data[i] > data[i + 1])
{
sort = true;
break;
}
}
if (sort) data.Sort();
884 ms
Compared to
var data = Enumerable.Range(0, 20000000).ToList();
data.Sort();
651ms
Check if list is sorted in either ascending or descending order in one pass
You could check pairs of consecutive elements, keep track of whether the first pair that is not ==
is <
or >
, and check that all the other pairs have the same relation (if not equal):
def is_sorted(lst):
asc = None
for i in range(len(lst)-1):
a, b = lst[i], lst[i+1]
if a == b:
continue
if asc is None:
asc = (a < b)
if (a < b) != asc:
return False
return True
That's a bit verbose, but you could also make it shorter with next
and all
, using a shared zip
iterator for both so the entire list is iterated only once.
def is_sorted(lst):
pairs = zip(lst, lst[1:])
asc = next((a < b for a, b in pairs if a != b), None)
return asc is None or all((a < b) == asc for a, b in pairs if a != b)
However, this version (like your original) will create a copy of the input list with lst[1:]
, so that's not really just a single loop, either. To fix that, you could e.g. use itertools.tee
or islice
.
How to determine if a List is sorted in Java?
Guava provides this functionality through its Comparators class.
boolean sorted = Comparators.isInOrder(list, comparator);
There's also the Ordering class, though this is mostly obsolete. An Ordering
is a Comparator
++. In this case, if you have a list of some type that implements Comparable
, you could write:
boolean sorted = Ordering.natural().isOrdered(list);
This works for any Iterable
, not just List
, and you can handle null
s easily by specifying whether they should come before or after any other non-null
elements:
Ordering.natural().nullsLast().isOrdered(list);
Also, since you mentioned that you'd like to be able to check for reverse order as well as normal, that would be done as:
Ordering.natural().reverse().isOrdered(list);
Check if a list is in a custom order
from itertools import zip_longest, groupby
okay = list(x == y for y, (x, _) in zip_longest(
(y for y in Y if y in X), groupby(x for x in X if x in Y)))
print(len(okay) >= 2 and all(okay))
First we discard unnecessary elements from both lists. Then we can use groupby
to collapse sequences of the same elements of X
. For example, your first example ['a', 'c', 'c', 'b', 'd', 'd', 'd']
first becomes ['a', 'c', 'c', 'b'] (by discarding the unnecessary
'd'), then
[('a', _), ('c', _), ('b', _)]. If we compare its keys element by element to the Y
without the unnecessary bits, and there are at least 2 of them, we have a match. If the order was violated (e.g. ['b', 'c', 'c', 'a', 'd', 'd', 'd']
, there would have been a False
in okay
, and it would fail. If an extra element appeared somewhere, there would be a comparison with None
(thanks to zip_longest
), and again a False
would have been in okay
.
This can be improved by use of sets to speed up the membership lookup.
Check if list is sorted in python
I think the function need to be two lines of code with <=
operators, to detect low to high
and high to low
list and equal sequences.
def in_order(nums):
a = [nums[i-1] <= nums[i] for i in range(1, len(nums))]
return all(x == a[0] for x in a)
[8, 6, 5, 4]
In order
[5, 5, 6, 6, 6, 8, 8, 10, 10, 10, 10]
In order
Check if list is ordered
Doesn't seem like it should be any more complex than
ordered( [] ) .
ordered( [_] ) .
ordered( [X,Y|Z] ) :- X =< Y , ordered( [Y|Z] ) .
Arithmetic comparison predicates are covered here: http://www.amzi.com/manuals/amzi/pro/ref_math.htm#MathematicalComparisons
Use @=</2
or compare/3
to check the ordering of things in the standard order of terms: http://www.amzi.com/manuals/amzi/pro/ref_manipulating_terms.htm#StandardOrder
Check array in JS - is list sorted?
var str = ["1,2,3,4,5", "1,2,8,9,9", "1,2,2,3,2"];
for (var i in str){ var list = str[i].split(',').map(Number); console.log(list); var isSorted = true; for(var j = 0 ; j < list.length - 1 ; j++){ if(list[j] > list[j+1]) { isSorted = false; break; } } console.log(isSorted);}
Related Topics
Choose One of Many Internet Connections for an Application
How to Name Variables Dynamically in C#
Parse Datetime in Multiple Formats
How to Handle Null or Optional Dll Struct Parameters
What Is the Maximum Resolution of C# .Net Bitmap
Equivalent of SQL Isnull in Linq
SQL Where Clause Matching Values with Trailing Spaces
Open Default Mail Client Along with a Attachment
What Is the "Right" Way to Bring a Windows Forms Application to the Foreground
Use Reflection to Invoke an Overridden Base Method
What's the Best Strategy for Equals and Gethashcode
How to Save Image in Database Using C#