I dated all the answers in this question under different conditions and found that:
- Sorting was the fastest with a long shot if the list was already monotonously growing.
- Sorting was the slowest with a long shot if the list was shuffled / random, or if the number of elements is out of order greater than 1. Moreover, the list, of course, corresponds to a slower result.
- Michael J. Barber's method was the fastest if the list was mostly monotonically increasing or completely random.
Here is the code to try:
import timeit setup = ''' import random from itertools import izip, starmap, islice import operator def is_increasing_normal(lst): for i in range(0, len(lst) - 1): if lst[i] >= lst[i + 1]: return False return True def is_increasing_zip(lst): return all(x < y for x, y in izip(lst, islice(lst, 1, None))) def is_increasing_sorted(lst): return lst == sorted(lst) def is_increasing_starmap(lst): pairs = izip(lst, islice(lst, 1, None)) return all(starmap(operator.le, pairs)) if {list_method} in (1, 2): lst = list(range({n})) if {list_method} == 2: for _ in range(int({n} * 0.0001)): lst.insert(random.randrange(0, len(lst)), -random.randrange(1,100)) if {list_method} == 3: lst = [int(1000*random.random()) for i in xrange({n})] ''' n = 100000 iterations = 10000 list_method = 1 timeit.timeit('is_increasing_normal(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations) timeit.timeit('is_increasing_zip(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations) timeit.timeit('is_increasing_sorted(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations) timeit.timeit('is_increasing_starmap(lst)', setup=setup.format(n=n, list_method=list_method), number=iterations)
If the list was already monotonously increasing ( list_method == 1 ), the fastest and slowest was:
- sorted
- Starmap
- fine
- lightning
If the list was mostly monotonically increasing ( list_method == 2 ), the fastest for the slowest was:
- Starmap
- lightning
- fine
- sorted
(whether the bracket or zip was the fastest depends on the execution, and I could not identify the pattern. Starmap is usually faster)
If the list was completely random ( list_method == 3 ), the fastest and slowest was:
- Starmap
- lightning
- fine
- sorted (very bad)
Matthew Moisen Nov 14 '16 at 4:21 2016-11-14 04:21
source share