0

I'm trying to solve the almost increasing sequence problem. The goal is to see if an array is a strictly increasing sequence if no more than one item is removed. I'm trying to accomplish this with the pop() method. Here is what I have so far:

def almostIncreasingSequence(sequence):
    new_seq = sequence

    output = False

    for i in range(len(sequence)):
        new_seq.pop(i)
        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            output = True
        else:
            output = False

    return output

I'm basically popping the element at index i and then assigning a boolean value to output depending on whether it is strictly increasing or not but this is the error I'm getting:

Traceback (most recent call last):
  main.py3 in the pre-written template, in getUserOutputs
    userOutput = _runmaxat(testInputs[i])
  main.py3 in the pre-written template, in _runmaxat
    return almostIncreasingSequence(*_fArgs_mksftvlwcpxn)
  main.py3 on line 6, in almostIncreasingSequence
    sequence.pop(i)
IndexError: pop index out of range
Sample tests: 0/19
oo92
  • 2,594
  • 2
  • 19
  • 49

2 Answers2

1
foo = [1, 2, 3]
while foo:
    print(foo)
    foo.pop()

output:

[1, 2, 3]
3
[1, 2]
2
[1]
1
m79lkm
  • 2,780
  • 1
  • 21
  • 22
0

This is because when you pop, it alters the list and your index no longer points where you'd expect.

Example:

a = [1,2,3]
count = 0

for i in a:
    print('Count ', str(count))
    print(i)
    a.pop()
    print(i)
    count += 1

'''
('Count ', '0')
1
3
1
('Count ', '1')
2
2
2
'''

If you want to traverse a list without losing order, simply create a copy of "a" when performing the for loop:

a = [1,2,3]
count = 0

for i in list(a):
    print('Count ', str(count))
    print(i)
    a.pop()
    print(i)
    count += 1

'''
('Count ', '0')
1
3
1
('Count ', '1')
2
2
2
('Count ', '2')
3
1
3
'''
Greg
  • 1,685
  • 2
  • 13
  • 20
  • Your example doesn't really show the issue with this. The code and output you posted seem to demonstrate a valid behaviour. Also, what is the purpose of `count`? – Tomerikoo Feb 03 '20 at 17:32
  • Thanks, forgot to update count. I've edited my answer to hopefully make more sense. – Greg Feb 03 '20 at 17:34
  • Again, this doesn't seem to pose any issue. The problem in the OP code is that the loop is iterating on the indexes of the original list and then trying to access elements that no longer exist. Your example loops on elements which gives a different effect – Tomerikoo Feb 03 '20 at 17:36
  • Just implemented your suggestion and still doesn't work. – oo92 Feb 03 '20 at 17:36
  • @OnurOzbek What error is it throwing now? – Greg Feb 03 '20 at 17:38
  • The same error. Check my edit above. – oo92 Feb 03 '20 at 17:59