Python 3 while loop not fully looping?

时间:2015-10-30 23:08:36

标签: python

So I've been at this for a while. I'm trying to create a function that checks if the numbers in a list are increasing. For example [1, 2, 3] is True but [1, 3, 2] is False. I have gotten to the point where it will say [1, 2, 3] is True, [3, 2, 1] is False, but [1, 3, 2] is still True. I assume it is only because only the first two positions are being read?

Here is the function for reference:

 def increasing(lst):
    index = 0
    index2 = index + 1
    while index < len(lst):
        if lst[index] >= lst[index2]:
            index += 1
            index2 += 1
            return False
        else:
            while index < len(lst):
                if lst[index] < lst[index2]:
                    index += 1
                    index2 += 1
                    return True

2 个答案:

答案 0 :(得分:2)

Try this:

def increasing(lst):
    return lst == sorted(lst)

This checks whether the list is sorted.

答案 1 :(得分:1)

Your code seems overly complicated. Just check with a loop that i-th element is larger than (i-1)-th element and you're done.

EDIT: here's the simple code

def isSorted(l):
    i = 1
    while i < len(l):
        if l[i] < l[i-1]:
            return False
        i += 1
    return True
isSorted([1, 2, 3]) #True
isSorted([1, 3, 2]) #False