Vanshita Rohela
Vanshita Rohela

Reputation: 11

Rotate array in Python

There is this question, 189 Rotate array on Leetcode. enter link description here Its statement is "Given an array, rotate the array to the right by k steps, where k is non-negative." To understand it better, here's an example. enter image description here

So, My code for this is

for _ in range(k):
   j = nums[-1]
   nums.remove(nums[-1])
   nums.insert(0, j)

It cannot pass some of the test cases in it. In the discussion panel, I found a code claiming it got submitted successfully that went like

for _ in  range(k):
   nums.insert(0, nums.pop(-1))

I would like to know, what is the difference between these two and why my code isn't able to pass some of the test cases.

Upvotes: 1

Views: 298

Answers (5)

Rajarshi Ghosh
Rajarshi Ghosh

Reputation: 462

The remove() method takes a single element as an argument and removes it's first occurence from the list.

The pop() method takes a single argument (index). The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item).

If the test case has the same item before the last index then test case will fail.

Hence to correct your code replace remove with pop

for _ in range(k):
   poppedElement = nums.pop()
   nums.insert(0, poppedElement)

or to make it even concise -

for _ in range(k):
   nums.insert(0, nums.pop())

Upvotes: 0

rikyeah
rikyeah

Reputation: 2013

Answer given by cesarv is good and simple, but on large arrays numpy will definitely perform better. Consider:

np.roll(lst, n)

Upvotes: 0

qazwsxedc
qazwsxedc

Reputation: 17

In your code j = nums[-1] and you are trying to insert(0, nums[-1]).

In

for _ in  range(k):
   nums.insert(0, nums.pop(-1))

inserting other number - (0, nums.pop(-1))

Upvotes: 0

user17903384
user17903384

Reputation:

Just use slicing:

>>> def rotate(l, n):
...     return l[-n:] + l[:-n]
...
>>> lst = [1, 2, 3, 4, 5, 6, 7]
>>> rotate(lst, 1)
[7, 1, 2, 3, 4, 5, 6]
>>> rotate(lst, 2)
[6, 7, 1, 2, 3, 4, 5]
>>> rotate(lst, 3)
[5, 6, 7, 1, 2, 3, 4]

Upvotes: 1

Alexander Suraphel
Alexander Suraphel

Reputation: 10603

If you do this on python shell [].remove.__doc__, you'll see the purpose of list.remove is to:

Remove first occurrence of value. Raises ValueError if the value is not present.

In your code nums.remove(nums[-1]) does not remove the last item, but first occurrence of the value of your last item.

E.g.

If you have a list with values nums = [2, 4, 8, 3, 4] and if you do nums.remove(nums[-1]) the content of nums becomes [2, 8, 3, 4] not [2, 4, 8, 3] that you're expecting.

Upvotes: 1

Related Questions