Why this doens't work for Python.


  • 0
    X

    can someone tell why this solution is returning [3,2,1] for input [3,2,1]? Is the highlighted line(with !!!!!!s) not doing anything?

    Thanks!

    class Solution(object):
        def nextPermutation(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            if len(nums) < 2:
                return
            # check if descending order already
            k = -1
            for i in range(len(nums) - 2, -1, -1):
                if nums[i] < nums[i + 1]:
                    k = i
                    break
            if k == -1:
                nums = nums[::-1] # !!!!!!!this line not working?!!!!!!!!!
                return
            # rearrangement
            l = -1
            for j in range(len(nums) - 1, k, -1):
                if nums[j] > nums[k]:
                    l = j
                    break
            nums[l], nums[k] = nums[k], nums[l]
            nums[k + 1:] = sorted(nums[k + 1:])
    

  • 2
    Y

    This is quite common pitfall when people write python. To understanding see following easy code:

    x = [1,2,3]
    y = x
    y = [3,4,5]
    print (x) # you still will get [1,2,3]
    

    The reason is quite simple if you think in reference name and object level. In first line you create a list object and also assign a reference x to point at that object. In second line, you assign another reference y to point at the same list object. The third line is tricky. Actually, you create the new list object and change the reference y pointing from old list object to this new object. Noticing the original object didn't change at all and reference x is also the same.

    Now come to your question,

    nums = nums[::-1]
    

    Python do two things here. First, it create a new object which is the reverse list of nums. Second change the reference name nums to point at this new object. But from the outside perspective, the original object is never changed!

    You need to use the in-place reverse instead:

    nums.reverse()
    

  • 0
    X

    I see, thanks for answering!


Log in to reply
 

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