I don't like numbers like programmers level1

Asked 2 years ago, Updated 2 years ago, 16 views

Array arr is given. Each element in the array arr consists of the numbers 0 through 9. At this point, you want to leave only one consecutive number in the array arr and remove them all. However, when returning the remaining numbers after removal, the order of the elements in the array arr must be maintained. For example,

If arr = [1, 1, 3, 0, 1, 1], return [1, 3, 0, 1]. If arr = [4, 4, 4, 3, 3], return [4, 3]. Complete the solution function that removes consecutive numbers from the array arr and returns the remaining numbers.

Restrictions Array arr size: natural number not more than 1,000,000 The size of the element in array arr: an integer greater than or equal to 0 and less than or equal to 9 Input/Output Example

arr answer
[1,1,3,3,0,1,1] [1,3,0,1]
[4,4,4,3,3] [4,3]
def solution(arr):

    for i in range(len(arr)-1):
        if arr[i] == arr[i+1]:
            arr.remove(arr[i])
            print(arr)
        else:
            pass

    return arr


arr = [1, 1, 3, 3, 0, 1, 1]
arr = [4, 4, 4, 3, 3]

print(solution(arr))
I

to write code that erase the number comes out, in front of the same direction in the arr. But while ' loops for iteration and it catches somewhere in the part I think I'm not sure.

Execution result here.
[1, 3, 3, 0, 1, 1]
[1, 3, 0, 1, 1]
[3, 0, 1, 1]

It comes out like this.

I wonder why the range doesn't go all the way around and the result doesn't come out as [1, 3, 0, 1]. Why is there an out-of-range error? I'm asking you a question because I couldn't even try hand-coding. I think it's an easy question, but I'm so frustrated.

python

2022-09-20 16:31

3 Answers

The reason for the range error is... Just under the for line, try print(i) before if. Then you'll see what's going on as a whole.

I'd do this, by the way.

It's not that this is a better approach, but think about it.


2022-09-20 16:31

As soon as the element is removed from the remove arr, the contents and size of the arr change. So the problem arises.


2022-09-20 16:31

I did this.

def solution(arr):
    b = []
    for i in range(len(arr)):
        if i == 0:
            b.append(arr[i])
        elif arr[i] != arr[i-1]:
            b.append(arr[i])
    return b


2022-09-20 16:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.