I've seen some posts about this same question, and I think my logic is pretty much the same as their answers. But I cannot find where exactly I'm wrong here.
- My code first checks the length of the provided
sequence
, if it is 2 or less it automatically returnsTrue
. - Next, it removes(
pops
) the first element and check if the rest are in ascending order. - If the
sequence
isn't in order, it replaces it with theoriginal
sequence and repeats the second step, but this time it removes the next element (pop(i)
). - This continues until there are no more elements to remove, which ultimately returns as
False
- If in any of the iterations, the list is found to be in ascending order, the function returns
True
.
This is the code:
def almostIncreasingSequence(sequence):
original = sequence.copy()
if len(sequence) <= 2: return True
for i in range(len(sequence)):
sequence.pop(i)
# print(sequence)
for j in range(len(sequence)-1):
if sequence[j+1] <= sequence[j]:
sequence = original.copy()
elif j+1 == len(sequence)-1:
return True
if i == len(sequence)-1:
return False
And this is my result :'(
I think my logic may not be correctly implemented in the code. But I don't know how to test it. It'd be helpful if you can give me a sequence where this function will give a wrong answer.
Solve almostIncreasingSequence (Codefights)
This is one of the posts I was referring to at the very beginning. It also explains the almostIncreasingSequence(sequence)
question and the answer explains the logic behind the code.