0
votes

I'm trying to solve this problem:Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. I came up with this code:

def almostIncreasingSequence(seq):
    count_2 = 0
    for element in seq:
        count = 0
        seq.remove(element)
        for i in range(len(seq)-1):
            if seq[i] < seq[i+1]:
                count += 1
            else:
                break
        if count == len(seq):
            return True
        else:
            seq = [element]+ seq
            count_2 += 1
    if count_2 == len(seq):
        return False

The problem is that when I give an input, the function doesn't do anything.for example in the interactive shell:

>>>print(almostIncreasingSequence([10,1,2,3,4,5]))
>>None

and if I don't use print:

>>>almostIncreasingSequence([10,1,2,3,4,5])
>>>

it returns nothing,it should return True for this special sequence.

2
can you share an example of the sequence? - Jeril
Did you try the debugger to see what happens? You have at least 2 cases in your if/else statements that don't return anything, maybe it's going down one of those paths. - Bernhard
It would be helpful if you posted the calling code, and the output that you see. - Jack Aidley
@JackAidley It doesn't have an out put,that is the problem. - FrastoFresto
@Jeril for instance:almostIncreasingSequence([10,1,2,3,4,5]) it has return True but it doesn't - FrastoFresto

2 Answers

0
votes

Your problem is related with "if - else". If you add print like below, you can see your error:

def almostIncreasingSequence(seq):
count_2 = 0
for element in seq:
    count = 0
    seq.remove(element)
    for i in range(len(seq)-1):
        if seq[i] < seq[i+1]:
            count += 1
            print("count1",count, len(seq))
        else:
            break
    if count == len(seq):
        return True
    else:
        seq = [element]+ seq
        count_2 += 1
        print("count2",count_2, len(seq))
if count_2 == len(seq):
    return False

For example call your function with [1, 2, 3], you will reach below output:

count1 1 2
count2 1 3
count1 1 2
count2 2 3

Your function returns True or False, when counts are equal len(seq). You can see from output counts are not equal len(seq), therefore doesn't return anything. You need to add "else" with return.

0
votes

Your code has two problems:

1) In line 11:

if count == len(seq):

should be replaced by

if count == len(seq) -1:

2) In your for loop you iterate over seq, but change seq in the loop. That confuses python.

I tested your code after correcting and it seemed to work fine. You might think about a more efficient algorithm though.