Determine if a list is in descending order

前端 未结 7 2501
孤城傲影
孤城傲影 2020-12-03 17:35

I am trying to write a function that will test whether or not a list is in decending order. This is what I have so far, but it doesn\'t seem to be working for all lists. <

7条回答
  •  悲哀的现实
    2020-12-03 18:20

    Instead of using indices, you can iterate over the input:

    def ordertest(iterable):
        it = iter(iterable)
        prev = next(it)
        for e in it:
            if e > prev:
                return False
            prev = e
        return True
    

    Note that it's a bad idea to return the strings 'true' and 'false'. Instead, you can use Python's built-in booleans.

提交回复
热议问题