Python: If statement skipped even though True

Python: If statement skipped even though True
0.0 0

#1

Could someone tell me why my if statement is skipped (doesn’t enter the nest) once I return back to it on the 3rd time of the loop? (I know there are other problems with this code but I want to solve this one first.)

def almostIncreasingSequence(sequence):
    failure = 0
    list_index = 0
    post_index = 1
    while failure < 2:
        max_length = len(sequence)
        if sequence[list_index] < sequence[post_index] and post_index <= max_length and failure < 2:
            list_index += 1
            post_index += 1
            if post_index >= len(sequence):
                return True

        elif sequence[list_index] > sequence[post_index] and post_index <= max_length and failure < 2:
            failure += 1
            sequence.pop(list_index)
            post_index = 0
            list_index = 1

        else:
            return False


sequence = [1, 3, 2]
almostIncreasingSequence(sequence)

#2

You incorrectly set post_index and list_index the wrong way around

If post_index is always meant to be 1 ahead of list_index, why not save yourself some trouble and use list_index + 1?

Also if failure ever reaches 2, your function never reaches the else clause and so your function doesn’t return at all (it actually returns None when that happens)


#3

Thanks, I hate when I overlook the obvious. Reason I have two separate variables is due to readability, as it’s the pythonic way. Descriptive meaningful values.