Home > front end >  Decreasing or ascending list
Decreasing or ascending list

Time:10-20

How do I go through a list like this:
list = [0, 1, 8 , 10, 14, 16]

Observing if the first term is less than or equal to the next and so on.

And if that is true, return True, and if not, return False.

Thank you very much.

CodePudding user response:

You seem to want to test whether the list is sorted.

def is_sorted(seq):
    return seq == sorted(seq)

CodePudding user response:

You could do this (for a list x - best not to name a list list):

all(x[i] <= x[i 1] for i in range(len(x)-1))

which has the benefit that it stops comparing once a result makes the answer False.

Examples:

>>> x = [0, 1, 8, 10, 14, 16]
>>> all(x[i] <= x[i 1] for i in range(len(x)-1))
True

>>> x = [0, 1, 8, 10, 17, 16]
>>> all(x[i] <= x[i 1] for i in range(len(x)-1))
False

CodePudding user response:

You can use functions like this:

listA = [0, 1, 8 , 10, 14, 16]
listB = [16, 14, 10 , 8, 1, 0]


def isAscending(input):
    j = float('-inf')
    for i in input:
        if i<j : 
            return False
        j = i
    return True
        
def isDescending(input):
    j = float('inf')
    for i in input:
        if i>j : 
            return False
        j = i
    return True
        
print(isAscending(listA))  # -> True
print(isDescending(listA)) # -> False

print(isAscending(listB))  # -> False
print(isDescending(listB)) # -> True

Checking if the list is sorted will also work (as in @PasserBy 's answer).
You can also use a function like this (this one also handles lists in descending order):

def isValid(input):
    return input == sorted(input) or input == sorted(input , reverse = True)
    
print(isValid(listA)) # -> True
print(isValid(listB)) # -> True

CodePudding user response:

If you want to know if two consecutive terms are in increasing order you can pair them with zip and then compare.

new_list = [0, 1, 8 , 3, 10, 14, 16, 12]

is_pairwise_ascending_order = [i <= j for i, j in zip(new_list[:-1], new_list[1:])]

print(is_pairwise_ascending_order)

Output

[True, True, False, True, True, True, False]

Finally, to check if the list is in ascending sequence you could use, for example, all built-in function (as done in another solution) or False not in is_pairwise_ascending_order

  • Related