python-3.xautorotate

Why I am out of range by using x,y = y,x in python


The request is to rotate a list. When K=3, you turn [1,2,3,4,5,6,7] into [5,6,7,1,2,3,4]; when K=1, you turn [1,2,3,4,5,6,7] into [7,1,2,3,4,5,6]

Why am I out of range? PyCharm informed me like this: IndexError: list index out of range

class Solution:
 def rotate(self, nums, k) -> None:
  k = k%len(nums)
  def rev(x, y, num):
      while y > x:
         num[x], num[y] = num[y], num[x]
         x += 1
         y -= 1
      rev(0, len(nums), nums)
      rev(0, k-1,nums)
      rev(k, len(nums), nums)
    
nums = [1,2,3,4,5,6,7]
s = Solution()
s.rotate(nums,3)

Solution

  • you're getting an index out of range error because you're trying to access an index in the list that doesn't exist.

    Typically, your list nums has 7 elements which means you can do nums[i] if 0<=i<=6.

    To fix your code you just need to replace rev(0, len(nums), nums) by rev(0, len(nums)-1, nums)

    class Solution:
        def rotate(self, nums, k) -> None:
            k = k % len(nums)
    
            def rev(x, y, num):
                while y > x:
                    num[x], num[y] = num[y], num[x]
                    x += 1
                    y -= 1
            rev(0, len(nums)-1, nums)
            rev(0, k - 1, nums)
            rev(k, len(nums)-1, nums)
    
    
    nums = [1, 2, 3, 4, 5, 6, 7]
    s = Solution()
    s.rotate(nums, 3)
    

    Alternatively, you can use this simpler implementation which returns another list:

    class Solution:
        def rotate(self, nums, k) -> list:
            k = k % len(nums)
    
            return nums[-k:] + nums[:-k]
    
    
    nums = [1, 2, 3, 4, 5, 6, 7]
    s = Solution()
    nums = s.rotate(nums, 3)