HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Is the list sorted?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortedlistthe

Problem

Is the trade-off between simplicity and performance worth it?

def is_sorted(list_):
    """
    Is the list sorted?

    The simpler `list_ == list(sorted(list_))` has
    time complexity O(N log N), this O(n).

    >>> is_sorted([1, 2, 3])
    True
    >>> is_sorted([1, 2, 7, 3])
    False
    """
    return all(curr <= list_[index + 1]
                  for index, curr in enumerate(list_[:-1]))

Solution

This can be written much more simply with izip from itertools. This removes having to fiddle with indices that enumerate gives back. Of course, it should probably also have a check for an list of length 0 or 1 as well.

return all(x <= y for x, y in izip(list, list[1:]))


Edit: The problem with built-in zip for Python 2 is that it will completely construct the list again in memory, which will kill performance for a large list. If you really want code that's portable between both Python 2 and 3, I'd suggest something like:

try:
    from itertools import izip
except ImportError:
    izip = zip

Code Snippets

return all(x <= y for x, y in izip(list, list[1:]))
try:
    from itertools import izip
except ImportError:
    izip = zip

Context

StackExchange Code Review Q#94354, answer score: 7

Revisions (0)

No revisions yet.