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]))
O(n)
). You can't determine if it's worth it a priori. \$\endgroup\$O(2n)
is stillO(n)
, after all. But there are fixed costs to consider too. \$\endgroup\$