Cyclic Rotation In Python
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
Solution 1:
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]
Post a Comment for "Cyclic Rotation In Python"