1

Task:

An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

I was wondering why this solution is not working?

def solution(A , K):
     old = A
     new = [0]*len(A)

     for i in range(K):
         new[0]=old[-1]
         new[1:] = old[:-1]
         old = new
     return new

Note: I have already solved the task, but I just don't understand why this is not working.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Axel
  • 27
  • 1
  • 2
  • So what input did you give and what should it produce? What happens instead? – Martijn Pieters Feb 23 '19 at 16:43
  • Put differently: *not working* doesn't tell us what happens instead, or what 'working' *looks* like. – Martijn Pieters Feb 23 '19 at 16:43
  • The issue here is that `old = new` doesn't create a copy, so now `new is old` is true and `new[0] = old[-1]` means that the old value at `new[0]` (which is also the old value at `old[0]`) is now lost. See the duplicate on how to copy a list properly. – Martijn Pieters Feb 23 '19 at 16:46
  • Exact the question I was looking for which is from `codility.com`. – Timo Sep 21 '20 at 17:59

1 Answers1

6

The problem is that you are simply assigning a new variable name to your new list when you do old = new. So whatever changes you now do to new will also be reflected in old because you simply created a new pointer to the same memory location of the new list. You should create a copy of the list so that you do not modify the original list. One way to do so is old = new.copy()

def solution(A , K):
     old = A
     new = [0]*len(A)
     for i in range(K):
         new[0]=old[-1]
         new[1:] = old[:-1]
         old = new.copy() # This was the problematic line
     return new

solution([1,2,3,4,5], 2)
# [4, 5, 1, 2, 3]

solution([1,2,3,4,5], 3)
# [3, 4, 5, 1, 2]
Sheldore
  • 37,862
  • 7
  • 57
  • 71