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

68 Views Asked by At

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)
2

There are 2 best solutions below

0
Dhia Hmila On BEST ANSWER

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)
1
F. Strothmann On

You have a off by one error as the indexing starts at 0 ends at len(list)-1. You call rev like this:

rev(0, len(nums), nums)

correct would be:

rev(0, len(nums)-1, nums)

Furthermore, due to the ability to add lists and index lists with negative indices in python you can also solve the problem this way:

nums = [1,2,3,4,5,6,7]

def rotate_list(list_to_rotate, k):
  return list_to_rotate[-k:] + list_to_rotate[:-k]

rotate_list(nums, 3)
# output: [5, 6, 7, 1, 2, 3, 4]