Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Element in array. I don't understand how work output in my case [python]

Tags:

python

I don't understand how work output in my case. Could you explain to me what I'm doing wrong?

task:(27. Remove Element)

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.

  • Return k.

My solution:

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        if len(nums) > 1:
            
            nums = [u for u in nums if u != val]
            print("nums = ", nums)

            if val not in nums:
                return len(nums)

Testcase:

nums =[0,1,2,2,3,0,4,2]

val = 2

Results:

Stdout (print in loop): nums = [0, 1, 3, 0, 4]

Output: [0,1,2,2,3]

Expected: [0,1,4,0,3]

like image 909
Polina Avatar asked Aug 19 '26 07:08

Polina


1 Answers

The problem is that you are not removing the elements in-place, so nums outside the function is not affected.

One option is to iterate over the list and remove items with pop. To avoid index out of range exception iterate over the list from end to start

for i in range(len(nums) - 1, 0, -1):
    if nums[i] == val:
        nums.pop(i)
like image 121
Guy Avatar answered Aug 21 '26 21:08

Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!