Home > other >  How to determine if a list of integers is strictly ascending
How to determine if a list of integers is strictly ascending

Time:10-31

I am very new to Python and I've searched high and low for this solution. This is for a school project.

The problem

def is_ascending(items):

Determine whether the sequence of items is strictly ascending so that each element is strictly larger (not just merely equal to) than the element that precedes it. Return True if the list of items is strictly ascending, and return False otherwise. Note that the empty sequence is ascending, as is also every one-element sequence, so be careful that your function returns the correct answers in these seemingly insigni5icant edge cases of this problem. (If these sequences were not ascending, pray tell, what would be the two elements that violate the requirement and make that particular sequence not be ascending?)

enter image description here

I can't seem to make it work, here's my code:

enter image description here

CodePudding user response:

The failure has been explained in earlier post clearly. Alternatively, you could also try this simple comparison:

[Note] it's also very adaptable for new requirement - eg. changing for descending is trivial in this approach.

def is_ascending(lst: List[int]) -> bool:
    ''' determine if the given list of ints is in strict ascending order'''

    return all(a<b for a,b in zip(lst, lst[1:]))

Sample runs:

>>> is_ascending([1, 1, 2, 3, 4])
False
>>> is_ascending([1])
True
>>> is_ascending([])
True
>>> is_ascending([-1, 8, 12, 22, 33])
True

CodePudding user response:

In regards to your code, we only need to compare the current item to its right-side neighbor. If that test passes, don't return until we have compared all items in the list, instead just continue after that iteration until we reach the end of all items:

def is_ascending(items):
    for index, item in enumerate(items):
        try:
            if items[index 1] > item:
                continue
            else:
                return False
        except IndexError:
            break
    return True

And use ritem > item since it is testing for 'ascending'.


Otherwise, (this is a duplicate of) a better and more succinct solution answered in Python - How to check list monotonicity:

def is_ascending(items):
    return all(x<y for x, y in zip(items, items[1:]))
  • Related