Reputation: 300
I am trying to implement a simple left rotation in a list. Please review the following code:`
def left_rotation(n,d,arr):
temp = arr
for i in range(n):
print(temp[i]) # here is the problem
if (i-d < 0):
arr[i+n-d] = temp[i]
else:
arr[i-d] = temp[i]
return arr
print(left_rotation(5, 4,[1,2,3,4,5]))
When I put the if-else
structure it fails to access the variable temp
but when I remove the if-else
, it works.
How do you explain that ?
Upvotes: 1
Views: 702
Reputation: 731
temp = arr
does not copy the list. It only creates a new reference which points to the same list. To copy you can use temp = arr[:]
def left_rotation(n,d,arr):
temp = arr[:]
for i in range(n):
print(temp[i]) # here is the problem
if (i-d < 0):
arr[i+n-d] = temp[i]
else:
arr[i-d] = temp[i]
return arr
print(left_rotation(5, 4,[1,2,3,4,5]))
This should work. Sample Output1:
>>> print(left_rotation(5,2,[1,2,3,4,5]))
1
2
3
4
5
[3, 4, 5, 1, 2]
Sample Output2:
>>> print(left_rotation(5,1,[1,2,3,4,5]))
1
2
3
4
5
[2, 3, 4, 5, 1]
Upvotes: 4