I can't figure out why the program is behaving in a peculiar way. The program is meant to rotate an array cyclically for 'K' times. When the list A is assigned to B in function rotate_array(), the program behaves in an incorrect way as shown in the output. Whereas when it is changed with the line B=[0]*len(A), the problem disappears. Could someone please help ?
def rotate_array(A):
#B = [0]*len(A) # This solves the problem
B = A # This seems to cause a problem
print "In rotate_array", A
for index, item in enumerate(A):
print "index:item ={}:{}, length of A={}".format(index, item, len(A))
if index == (len(A) - 1):
B[0] = A[index]
else:
B[index + 1] = item
print B
return B
def solution(A, K):
for index, item in enumerate(A):
print "in fn soln: index:item ={}:{}, length of A={}".format(index, item, len(A))
ctr = 0
while ctr < K:
A = rotate_array(A)
ctr += 1
return A
if __name__ == '__main__':
A = [1,2,3,4]
K = 1
ret_A = solution(A, K)
print ret_A
Output:
in fn soln: index:item =0:1, length of A=4
in fn soln: index:item =1:2, length of A=4
in fn soln: index:item =2:3, length of A=4
in fn soln: index:item =3:4, length of A=4
In rotate_array [1, 2, 3, 4]
index:item =0:1, length of A=4
index:item =1:1, length of A=4
index:item =2:1, length of A=4
index:item =3:1, length of A=4
[1, 1, 1, 1]
[1, 1, 1, 1]
When function rotate_array(A) is changed to have this line
B = [0]*len(A) # This solves the problem
instead of
B = A
The output is now correct -
in fn soln: index:item =0:1, length of A=4
in fn soln: index:item =1:2, length of A=4
in fn soln: index:item =2:3, length of A=4
in fn soln: index:item =3:4, length of A=4
In rotate_array [1, 2, 3, 4]
index:item =0:1, length of A=4
index:item =1:2, length of A=4
index:item =2:3, length of A=4
index:item =3:4, length of A=4
[4, 1, 2, 3]
[4, 1, 2, 3]
B=Acreates an alias (two references to the same list). If you want a (shallow) copy useB = A[:].