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'
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." )
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.
sort() if (listB == listB_copy): print("Yes, List is sorted. ") else: print("No, List is not sorted.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With