Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a list is in descending order

Tags:

python

I am trying to write a function that will test whether or not a list is in decending order. This is what I have so far, but it doesn't seem to be working for all lists.

I used the list [9,8,5,1,4,3,2] and it returned 'true'.

I can't seem to figure out where my mistake is.

def ordertest(A):
    n = len(A)
    for i in range(n):
        if A[i] >= A[i+1]:
            return 'true'
        else:
            return 'false'
like image 947
user1653420 Avatar asked Oct 04 '12 19:10

user1653420


People also ask

How do you check if a list is in descending order in Python?

Method #1 : Naive method The simplest way to check this is run a loop for first element and check if we could find any larger element than it after that element, if yes, the list is not reverse sorted. if ( not flag) : print ( "Yes, List is reverse sorted." )

How do you check ascending or descending order in Python?

For ascending, check if the subtraction between the current item and the next time is greater than 0, if so, it is not sorted ascending. For descending, check if the subtraction between the current item and the next time is lesser than 0, if so, it is not sorted descending.

How do you check if an element is in a list in ascending order python?

sort() if (listB == listB_copy): print("Yes, List is sorted. ") else: print("No, List is not sorted.

How do you list numbers in descending order?

The descending order of numbers can be found by subtracting 1 from the number. For example, to write 10 to 6 in descending order, we will start with the largest number in the above sequence, which is 10 and keep subtracting 1 from it until we reach the lowest number.


1 Answers

You can do this easily with a generator expression and the all() builtin:

all(earlier >= later for earlier, later in zip(seq, seq[1:]))

For example:

>>> seq = [9, 8, 5, 1, 4, 3, 2] 
>>> all(earlier >= later for earlier, later in zip(seq, seq[1:]))
False
>>> seq = [9, 8, 5, 4, 3, 2] 
>>> all(earlier >= later for earlier, later in zip(seq, seq[1:]))
True

This should be nice and fast as it avoids python-side loops, short circuits nicely (if you use itertools.izip() in 2.x), and is nice and clear and readable (avoiding looping over indices, for example).

Note that a generic solution for all iterators (not just sequences) is possible too:

first, second = itertools.tee(iterable)
next(second)
all(earlier >= later for earlier, later in zip(first, second))
like image 72
Gareth Latty Avatar answered Oct 21 '22 15:10

Gareth Latty