What's wrong with my python code?


  • 0
    0
    class Solution:
        def removeDuplicates(self, A):
            if not A:
                return 0
            else:
                A = [A[i] for i in range(0, len(A)) if (A[i] != A[i-1] or i == 0)]
    
            return len(A)
    

    it passes my local tests

    could anyone help me figure it out?


  • 2
    K

    Hi, you can't re-assign the A variable because in this situation it behaves like an immutable object. It creates a new copy of itself instead of sharing the common memory address.

    class Solution:
        def removeDuplicates(self, A):
            A = [A[i] for i in range(0, len(A)) if (A[i] != A[i-1] or i == 0)]
            print A # [1, 2, 3, 44, 5, 7, 99]
            return len(A)
    
    sol = Solution()
    B = [1, 1, 2, 3, 44, 5, 5, 5, 5, 5, 7, 99]
    print sol.removeDuplicates(B)
    print B # [1, 1, 2, 3, 44, 5, 5, 5, 5, 5, 7, 99]
    

    @see: http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference


  • 0
    0

    thank you so much!


Log in to reply
 

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