Declan
Declan

Reputation: 45

How do I tell if a list is in ascending order? Just needs to return True or False

The way I have it it stops after checking if the first two digits are ascending.

How do I make it keep running until it has checked the whole list?

def isAscending(xs):
    for n in range(len(xs) + 1):
        if xs[n] > xs[n+1]:
            return False
        else:
            if xs[n] < xs[n+1]:
                return True

Upvotes: 1

Views: 2500

Answers (4)

timgeb
timgeb

Reputation: 78750

Only return True at the end, that is after every element has been checked. Fixing your code with minimal changes:

def isAscending(xs):
    for n in range(len(xs) - 1):
        if xs[n] > xs[n+1]:
            return False
    return True

print isAscending([1,2,3,4]) # True
print isAscending([1,2,4,3]) # False

Short solution:

>>> lst = [1,2,3,4]
>>> sorted(lst) == lst
True
>>> lst = [1,2,4,3]
>>> sorted(lst) == lst
False

Better short solution that runs in O(n) (sorting is O(n log n)):

>>> lst = [1,2,3,4]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
True
>>> lst = [1,2,4,3]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
False

To make the last one more memory efficient, use itertools.izip in place of zip if you are using Python 2.

Upvotes: 2

Prune
Prune

Reputation: 77850

Use the Python built-in all operator to do the optimization and iteration for you. The following code says "Let me know if everything in the list is True." It will quit early if it finds a False value.

def isAscending(xs):
    return all([xs[n] <= xs[n+1] for n in range(len(xs)-1)])

For future reference, the or version of this is the any operator.

Upvotes: 1

Nathan Villaescusa
Nathan Villaescusa

Reputation: 17649

Just keep track of the previous one:

def isAscending(xs):
    prev = None
    for n in xs:
        if prev is not None and n < prev:
            return False
        prev = n
    return True

Upvotes: 1

kairocks2002
kairocks2002

Reputation: 446

Just have it return True if it isn't False! Whenever return is called, it breaks out of the function. Only one return is ever called.

def isAscending(xs):

    for n in range(len(xs) + 1):
        if xs[n] > xs[n+1]:
            return False
    return True

This way, if it is not in ascending order, then the function returns False and exits the function. If the return False is never activated, though, then the list must be in ascending order so the return True is activated.

Upvotes: 0

Related Questions