0

I am trying to make a function that for a sequence of integers as an array can determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. If an element can be remove than the output is True otherwise return False. I tried,

def almostIncreasingSequence(sequence):

   if sequence[:-1] == sequence[1::]:
        return True
   else:
        return False

It works for list,

  sequence =  [1, 3, 2, 1]
  >>> False

Since you cannot remove any number that would lead to an increasing sequence. However, if the list was

sequence: [1, 3, 2]
>>> True

It is true since you can remove 2 or 3 to have an increasing sequence. My function incorrectly outputs False though.

user1821176
  • 1,141
  • 2
  • 18
  • 29
  • 4
    It's unclear how the code you tried would ever be used to solve the problem described in the question. All it checks is that the last `len-1` and first `len-1` items are the same; it doesn't check that anything is strictly increasing or consider the consequence of removing any intermediate item. I'm not sure if this counts as a good-faith attempt to solve the problem... it might help to include, in the OP, a description of how your algorithm is intended to work. – Ollin Boer Bohan Nov 11 '18 at 16:24

2 Answers2

3

I really don't see what was your first idea... How about a more simple solution ?

def fn(seq):
    last_i = None
    lives = 1
    for i in seq :
        if last_i is None :
            last_i = i
        else :
            if (i <= last_i):
                lives = lives - 1
                if (lives < 0) :
                    return False
            last_i = i
    return True

>>> fn([1, 3, 2, 1])
False
>>> fn([1, 3, 2])
True
>>> fn([1, 3, 2, 3])
True
>>> fn([1, 3, 2, 4, 6, 8])
True
>>> fn([1, 3, 2, 4, 6, 8, 2])
False
theplatypus
  • 81
  • 1
  • 1
  • 5
0

The code below uses the monotonicity check as wrote in this answer and iterates over the elements of the list to check if poping a single element results in increasing monotonicity.

def strictly_increasing(L):
    return all(x<y for x, y in zip(L, L[1:]))
def non_decreasing(L):
    return all(x<=y for x, y in zip(L, L[1:]))

L = [1, 3, 2]
L_mod = L.copy()
my_bool = False
if not strictly_increasing(L):
    for i, x in enumerate(L):
        L_mod.pop(i)
        if strictly_increasing(L_mod):
            my_bool = True
            exit
        else: L_mod = L.copy()
else:
    my_bool = True

Use strictly_increasing or non_decreasing as you wish.

b-fg
  • 3,959
  • 2
  • 28
  • 44