I asked this question on Stackoverflow as well, but I think it's best suited here because my code needs optimization instead of error checking (that I previously thought).
I've made changes to my code as well. But the logic is pretty much the same:
- My code first checks the length of the provided sequence, if it is 2 or less it automatically returns
True
. - Next, it creates a
newlist
with the first element removed and checks if the rest of the list is in ascending order. - If the sequence is not in order, the iteration
breaks
and anewlist
is generated again and this time with the next element removed. - This continues until there are no more elements to remove (i.e.
i == len(sequence) - 1
), which ultimately returns asFalse
- If in any of the iterations, the list is found to be in ascending order(i.e.
in_order
remainsTrue
), the function returnsTrue
.
def almostIncreasingSequence(sequence):
# return True for lists with 2 or less elements.
if len(sequence) <= 2:
return True
# Outerloop, removes i-th element from sequence at each iteration
for i in range(len(sequence)):
newlist = sequence[:i] + sequence[i+1:]
# Innerloop, checks if the sequence is in ascending order
j = 0
in_order = True
while j < len(newlist) - 1:
if newlist[j+1] <= newlist[j]:
in_order = False
break
j += 1
if in_order == True:
return True
elif i == len(sequence)-1:
return False
I received a suggestion that I should only use one loop, but I cannot think of a way to implement that. Nested loops seems necessary because of the following assumptions:
- I have to remove every next element from the original sequence. (outer loop)
- I need to check if all the elements are in order. (inner loop)
This is a brief on almostIncreasingSequence()
my code follows the logic provided in the answer here, it solves almost all of the Tests as well, but it is too slow for larger lists (that are approx 10000+ elements).