0

I tried solving this problem on hackerrank where you are given a list a and an integer d', you should rotate the list a to left d times and return the rotated list.

But, when I used this python code for a =[1,2,3,4,5] and d = 4 I got the output as [1,1,1,1,1] instead of [5,1,2,3,4].

temp = a
for j in range(len(a)):
    a[j-d] = temp[j]
return a

But when I explicitly copied each element of list 'a' into the list 'temp' it worked fine and I passed all the test cases.

temp = []
for i in range(len(a)):
    temp.append(a[i])
for j in range(len(a)):
    a[j-d]=temp[j]
return a

Can somebody explain what was wrong with the earlier code?? Thank you!

sanyassh
  • 8,100
  • 13
  • 36
  • 70

4 Answers4

1
temp = a

This is a reference assignment. You merely created another reference pointing to the same underlying list object.

temp = a[:]

This will create a new object and assign temp to the new object. (So does your loop of explicitly copying)

This is because list is a mutable type in python - so new objects are not created upon assignment.

rdas
  • 20,604
  • 6
  • 33
  • 46
0

itertools.cycle is your friend for this:

import itertools
def rotate(l, n):
    it = itertools.cycle(l)
    for _ in range(n):
      next(it)
    return [next(it) for _ in range(len(l))]

print(rotate([1,2,3,4,5], 4))

result:

[5, 1, 2, 3, 4]

Here you have the live example

Netwave
  • 40,134
  • 6
  • 50
  • 93
0

You set temp = a which indicate that they are referring to the same pointer a simple check you could do is to check their memory address

id(temp)
id(a)

You will notice both temp and a referring to the same address therefore changes done on a will also affect temp and vice versa.

In your second method, you created a new list instead of assigning it using an existing list, therefore the address are not similar and they are not referencing one another.

Tash
  • 59
  • 5
0
a =[1,2,3,4,5]
d = 4

for i in range(0,4):
    # repeat the below steps for d times
    temp=a[0] # store the a[0] in temp
    for j in range(0,len(a)-1):
        a[j]=a[j+1] # move all elements located in 1 to len(a)-1 to its previous location
    a[len(a)-1]=temp # store the temp in a[len(a)-1]
print(a)

output:

[5, 1, 2, 3, 4]
ncica
  • 7,015
  • 1
  • 15
  • 37