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
Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78

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,960
  • 1
  • 22
  • 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,845
  • 2
  • 16
  • 26