Wednesday, 15 June 2016

Rotation of the numbers-python



To find the rotations of a number I wrote a code like



def rotation(N):
A=[]
for i in range(len(N)):

y=N.pop(0)
N.append(y)
A.append(N)
return A
K=[1,9,7]
r=rotation(K)
print(r)


but it gives me an output like:




A=[[1, 9, 7], [1, 9, 7], [1, 9, 7]]


but it should be



A=[[1,9,7],[9,7,1],[7,1,9]]


and I didnt understand why this happens

thanks


Answer



Use collections.deque



You should use collections.deque for this task and use the in-place method deque.rotate designed specifically for this purpose.



Using a list for this task would require expensive copying operations, while deque is optimised for fast addition and removal of elements from the beginning and end of a queue. See TimeComplexity for more details.



from collections import deque


A = deque([1, 9, 7])

for i in range(len(A)):
print(A)
A.rotate()

deque([1, 9, 7])
deque([7, 1, 9])
deque([9, 7, 1])



Why your code does not work



The reason your code does not work is because you are modifying the same object rather than a copy. The following will work:



def rotation(N):
A = []
for i in range(len(N)):
N = N[:]
N.append(N.pop(0))

A.append(N)
return A

K = [1,9,7]
r = rotation(K)

print(r)

[[9, 7, 1], [7, 1, 9], [1, 9, 7]]



Further explanation



If you modify the same object, A will consist of 3 lists with each list pointing to the same object and will therefore be guaranteed to be identical. Remember each list is just a bunch of pointers. If each pointer points to one object, changing it 3 times means the final assignment will be used for all the sublists.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...