1

what i want to do(python language):

I want to check whether it is possible to obtain a list by deleting one of its element such that the list is in increasing order .

e.g: for list = [1,2,4,3], it is POSSIBLE to obtain a list that is in increasing order by removing 4 .

. is there any way such that i can remove 1 number (temporary) and check whether:

sorted(list) == list

e.g: list = [1,2,4,3]

.1st i want to remove 1 and then check with [2,4,3]

.then i want to remove only 2 from list and check with list [1,4,3] and so on ..

How can i do that in python;

Hissaan Ali
  • 2,229
  • 4
  • 25
  • 51

4 Answers4

3

O(n) algorithm:

def almostSorted(L):
    """ function to check whether it is possible to obtain 
        a list by deleting one of its element such that 
        the list is in increasing order"""

    #uncomment the below line if you want to remain original list 
    #(in this case, func almostSorted(L) will work with copy of L) 
    #L = L[:]

    lenL = len(L)
    if lenL <= 2 :
        return True

    counter = 0
    while L[0] > L[1] and lenL != 1:
        del L[0]
        counter, lenL = counter+1, lenL-1

    i = 0
    while i+1 < lenL:
        if L[i+1] >= L[i]:
            i = i+1
            continue

        counter += 1

        if L[i+1] >= L[i-1]:
            del L[i]
        elif L[i+1] < L[i-1]:
            del L[i+1]
        lenL -= 1

    if counter > 1:
        return False
    else:
        return True

Test 1:

L = [1,2,3,4,5]
print L
print almostSorted(L)
print L

[1, 2, 3, 4, 5]
True
[1, 2, 3, 4, 5]

Test 2:

L = [10,2,3,4,5]
print L
print almostSorted(L)
print L

[10, 2, 3, 4, 5]
True
[2, 3, 4, 5]

Test 3:

L = [1,2,3,4,1]
print L
print almostSorted(L)
print L

[1, 2, 3, 4, 1]
True
[1, 2, 3, 4]
Denis Kuzin
  • 863
  • 2
  • 10
  • 18
2

Just do like this:

def check(lst):
    if len(lst) < 2:
        return False
    for i in range(len(lst)):
        new_lst = lst[:i] + lst[i+1:]
        if sorted(new_lst) == new_lst:
            return True
    return False

if __name__ == '__main__':
    print(check([1, 2, 4, 3])) # True
    print(check([1, 2, 4, 3, 2])) # False
williezh
  • 917
  • 5
  • 8
1

You will have to create a copy of the list before doing del list[x] on any index. Lists are mutable and hence you will lose the original list once you delete any element from it.

You would need the original list to check all permutations.

Afaq
  • 1,146
  • 1
  • 13
  • 25
1

Just loop through the list and try removing every element.

import copy

def is_increasing(sequence):
    sequence_n = copy.copy(sequence)
    for element in sequence:
        sequence_n.remove(element)
        if sorted(sequence_n) == sequence:
            return True
        sequence_n = copy.copy(sequence)
    return False
Zizouz212
  • 4,908
  • 5
  • 42
  • 66