Lucas Chad
Lucas Chad

Reputation: 19

Check if list is Ascending OR Descending (using FOR)

So I have been set a task in my college where I'm suppose to check whether a list is in fact sorted (either ascending or descending). But I MUST use 'for'. (We just recently learned about for and lists and we must practice it)

This is what I have so far, I am able to confirm if a list is descending, but not descending OR ascending:

A=[10,9,8,3,1,0]

def order(A):
    for i in range(len(A) - 1): 
        if ((A[i]>A[i+1])) :
            return False
    return True

Upvotes: 1

Views: 19680

Answers (5)

glaand
glaand

Reputation: 1124

You need to create an algorithm in a such way so that the result before the other parameter, is unique!

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.

Try this:

def order(A) # Ascending order
    for i in range(len(A) - 1):
        if A[i] - A[i+1] > 0:
            return False
    return True

def order(A) # Descending order
    for i in range(len(A) - 1):
        if A[i] - A[i+1] < 0:
            return False
    return True

Upvotes: 1

Sirisha K
Sirisha K

Reputation: 1

def descending(l):
  x=0
  if len(l)<= 1 or (len(l) == 2 and l[0] >= l[1]):
    return True
  else:
    if l[0]<=l[1]:
      return descending(l[1:])
    else:
      return False

Upvotes: 0

moses51
moses51

Reputation: 124

Here is a simple way to return whether the list is ascending, descending, or neither.

def order(A):
if A == sorted(A,reverse=False):
    return 'Ascending'
elif A == sorted(A,reverse=True):
    return 'Descending'
else:
    return 'Neither'

Here is a sample output with simple input.

>> a = [2,5,4,7,1]
>> b = [1,3,5,7,9]
>> c = [9,6,3,1,0]
>> print(order(a), order(b), order(c))
out: Neither Ascending Descending

The benefit of this function is that we don't have to analyze the individual elements, we simply have to use built-in functions to analyze the list as a whole.

Upvotes: 3

tkhurana96
tkhurana96

Reputation: 939

This might help:

A=[10,9,8,3,1,0]
B=[1,9,18,33,41,50]
C=[1, 1, 1, 1, 1]
D= [1]
E=[1, 2, 3, 2, 1]
F =[]

def order(someList):
    asc = True
    desc = True

    for idx in range(1, len(someList)):
        if someList[idx] - someList[idx - 1] >= 0:
            asc = asc & True
            desc = desc & False
        else:
            desc = desc & True
            asc = asc & False

    if asc and not desc:
        return "list is in ascending order"
    elif desc and not asc:
        return "list is in descending order"
    else:
        return "list is in no order"

print(order(A))
print(order(B))
print(order(C))
print(order(D))
print(order(E))
print(order(F))

and when executed, this code's output was:

list is in descending order
list is in ascending order
list is in ascending order
list is in no order
list is in no order
list is in no order

Here what we are doing is that we are maintaining two boolean flags asc and desc, which will represent whether the list passed was in ascending order or descending order.

Then for each consecutive pair of numbers in the list, we calculate their difference if someList[idx] - someList[idx - 1] >= 0: then we and desc flag with False and vice versa in the else case.

Intuitively, what is being done in this code is as follows: if a sequence is in ascending order, then every consecutive pair of numbers will have their difference greater than zero, for ex: consider this sequence [a, b, c, d, e, f] where all characters represent numbers and assume for the case when this sequence is in ascending order i.e a <= b <= c <= d <= e <= f and if we consider all the consecutive pairs of numbers i.e (a, b), (b, c), (c, d), and so on.. and calculate difference for each of those pairs i.e b-a, c-b, d-c and so on.. then every difference will be >= 0 i.e b-a >= 0 and c-b >= 0 and d-c >= 0 and e-d >= 0 and f-e >= 0 and this is the condition that is being represented by the asc boolean flag in the code above. Similar explanation can be thought for desc boolean flag.

And if you want a smaller version of the code above while still using for loop then use this:

A=[10,9,8,3,1,0]
B=[1,9,18,33,41,50]
C=[1, 1, 1, 1, 1]
D= [1]
E=[1, 2, 3, 2, 1]
F = []

def order(someList):

    results = [True if second >= first else False for first, second in zip(someList, someList[1:])]

    if any(results) and all(results):
        return "ascending order"
    elif not any(results) and not all(results):
        return "descending order"
    else:
        return "no order"

print(order(A))
print(order(B))
print(order(C))
print(order(D))
print(order(E))
print(order(F))

and output for this

descending order
ascending order
ascending order
no order
no order
no order

Upvotes: 0

Joe Iddon
Joe Iddon

Reputation: 20434

You want to return True if the list is ascending or descending.

This makes the code really *readable**:

def order(lst):
    ascending = descending = True
    for i in range(len(lst) - 1): 
        if lst[i] > lst[i+1] :
            ascending = False
        elif lst[i] < lst[i+1] :
            descending = False
    return ascending or descending

We start by defining 2 boolean variables set to True - ascending and descending. We then loop through the lst (I gave the function a more sensible param name) and check if this index is less than the next. If it is, we can set the ascending variable to False (as the lst can now no longer be ascending). Else, if the next index is greater than the currentindex, we setdescendingtoFalse`.

Then finally, at the end we return if either the lst was ascending or descending.


Some examples:

>>> order([1,2,3,4])
True
>>> order([1,2,3,2])
False
>>> order([3,2,1,0])
True
>>> order([3,2,1,4])
False

Hope this helps! (by the way, if your interested, you could literally do the same function in one-line):

def order(lst):
    return lst == sorted(lst) or lst == sorted(lst)[::-1]

Upvotes: 0

Related Questions