Can someone tell me why this won't work? It works in my own program

  • 1
    def rotate(self, nums, k):
        if len(nums)>1:
            for i in range(len(nums)):
                if i<k:

    This works in my own program. I know it's not the most efficient way to code, but it should work.

    However, what should be [2,1] from [1,2],1 returns [1,2] on OJ. WHY!?!?!?!?!?

  • 0

    Okay, after digging some of the discussion threads, I know what happened

    still not sure why 'nums' and 'nums[:]' makes a difference though

  • 0

    Well , I m running into a similar problem ( could be the same too ) . If I run it on my computer - it seems to work , but not on the OJ

    [1,2],1 ===> the same program returns [2,1] on my mac

    [1,2],1 ===> returns [1,2] on OJ

  • 0

    Do you mind sharing what went wrong ?

  • 0

    I had the same issue (returned [2,1] on my computer but [1,2] in the OJ), and fixed the problem by setting nums[:] = new_num instead of nums = new_num (my code was slightly different, but what's important is that you reset nums[:] at the end rather than nums). Can anyone explain what the '[:]' syntax means and why it might make a difference here?

  • 0

    If you only use nums=new_num, you just chance the reference of nums to new_num, but only inside your function. The original nums stays the same. So nums[:] might refer to the content of the list instead of it's reference.

    here's my code, that changes the original list:

        def rotate(self, nums, k):
        if len(nums) != 1 and k != 0:
            for i in range(k):

Log in to reply

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