Who can tell me why is this wrong? By python


  • 0
    J
    class Solution:
        # @param {integer[]} nums
        # @return {void} Do not return anything, modify nums in-place instead.
        def sortColors(self, nums):
            l = nums
            a = b = c = 0
            for i in range(len(l)):
                if l[i]==0:
                    a+=1
                elif l[i]==1:
                    b+=1
                else:
                    c+=1
            l1=a*[0]+b*[1]+c*[2]
            print l1

  • 0

    Could you please at least indent your code properly so others can read your code?


  • 0
    J

    Thanks,it changed


  • 2

    You're supposed to modify the original list object. You don't do that. You instead create a new list that the caller never even sees.


  • 0
    J

    Thanks,but I have try this (l=a*[0]+b*[1]+c*[2]).It's also wrong.And the OJ's judge shows maybe the format is wrong.Could you please help me with the problem that why [0,1] don't equal to [0, 1]?


  • 0

    Yes, that's wrong for the exact same reason. You're not changing the original list. You just change your variable to point to another list. To change the original list, you can for example do l[:] = a*[0]+b*[1]+c*[2].


  • 0
    J

    Thank you for your detailed explanations!


Log in to reply
 

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