0

New to Python, I've searched hard for this solution. This is for a school project.

The problem Write this function:

def is_ascending(items):

To 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 considered 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

Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
J Lee
  • 35
  • 6
  • 2
    You're not returning anything by default - if your list only has one item, then the inner `for` loop is skipped, and if your list is empty then the outer `for` loop is skipped as well. Just put a `return True` at the end of the method (outside both loops), and you should be fine. – Green Cloak Guy Oct 30 '21 at 18:46

2 Answers2

2

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:]))
2

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

Daniel Hao
  • 4,922
  • 3
  • 10
  • 23