[Tutor] lists

Martin A. Brown martin at linux-ip.net
Sat Nov 28 21:07:24 EST 2020


Hello there,

> Hi I would like to know how to check if an element in a list is greater
> than the next element on the same list like this
> 
> [5,4,3,2,1]
> 
> if 5 > 4 > 3 > 2 > 1
> return True
> 
> in an example like this one [5,4,5,2], it would give False.

Is this another way of asking:  Is the list (reverse) sorted?

If so,

For many general computation problems, not only will the entire list 
fits easily in the memory of modern machines, but the sorting is 
reasonably quick, so you can perform the sort operation on the input 
and then compare the original list with the sorted list and you know 
that it's not sorted if you don't have equality.  This should work 
fine for integers (and numbers in general), as in your example.  It 
will not work reliably for more complex elements of a list.

Here's a function that returns True or False:

  def is_reverse_sorted(l):
      return l == sorted(l, reverse=True)
  
  def test_is_reverse_sorted():
      examples = [
                   ([5,4,3,2,1], True),
                   ([5,4,5,2], False),
                   ([5,4,5,3,1], False),
                   ([5,5,5,5,1], True),
                 ]
      for l, expected in examples:
          assert is_reverse_sorted(l) == expected

In the thread I saw two of the above sample lists and I made up one 
myself that includes repeated integers, just to demonstrate.

If no, or if a future problem needs different rules, you can take 
this sort of technique (a function and a testing function to run 
through some test cases) and apply it to increasingly more 
complicated rules for the input data.  Say, for example, you wanted 
to test that all list elements are integers (or float()-able).  You 
could add logic to ensure that there were no duplicates.  You could 
add testing to see that there were no duplicates.

-Martin

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list