Help..Don't know whats wrong here in Python

  • 0

    Hi all,
    I am a beginner.
    I don't know why my code has wrong answer on:

    Input: [1,2], 1

    Output: [1,2]

    Expected: [2,1]

    Can someone tell me why? please

    Thank you.

    class Solution:
    # @param nums, a list of integer
    # @param k, num of steps
    # @return nothing, please modify the nums list in-place.
    def rotate(self, nums, k):
        k %=len(nums)
        if nums is None:
            return None
            nums = nums[-k:]+nums[:-k]
            return (nums)

  • 0

    I have the same problem at first. Then i changed the 'nums' into 'nums[:]'. It was accpeted. I guess it is because it requires '# @return nothing, please modify the nums list in-place.'
    def rotate(self, nums, k):
    nums[:] = nums[len(nums)-k:]+nums[:len(nums)-k]

  • 0

    you can revise nums=nums[-k:]+nums[:-k] into nums[:]=nums[-k:]+nums[:-k] ,then it'll work

  • 0

    Hi @Krystal - I see this works ; but what is the difference between the two usages .

  • 0

    +1 this question -- Can anyone explain what the '[:]' syntax means and why it might make a difference here?

  • 1

    assume you call the function like below:

    a = [1,2,3,4,5,6]
    Solution().rotate(a, 3)
    print a

    In the rotate function, variable nums is not a list ,
    it's a reference of list a
    nums[:] = [1,2,3] operating will edit the list as a references (they share same memory area)
    nums= [1,2,3], you just give the reference of [1,2,3] to nums, after this nums doesn't reference the old list (a) any more

  • 0

    thanx for the explanation !!!!!

  • 0

    Oh, of course. Thanks for explaining!

Log in to reply

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