What is wrong with my Python code?


  • 0
    J

    I got error: input is ([4,5],4), and the output should be [5], while it is said my output is [4]. However, I tried on my machine, and it works fine. Can anyone tell me what is wrong with my code?


    class Solution(object):

    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        num = [nums[i] for i in range(len(nums)) if not (nums[i] == val)]
        return len(num)
    

    And I tried this one, does not work either.

    class Solution(object):

        def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        num = []
        for i in nums:
            if i != val:
                num.append(i)
        return len(num)

  • 0
    Y

    You returned the right answer of the new list length, but if you checked the details of the run code status, you may find that not only the right answer of the list length is asked for, but also the right output list. So you have to do 'real' delete on the list and return the length of the new list.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.