2

I was solving a question of matrix rotation by 90 degrees. In the problem, I am taking up a list k filled with 0s of the exact degree as passed by the user.

I have tried this following code:

def rotate(m):
    k=[]
    f=[]
    print(m)
    for i in range(0,len(m)):
        f.append(0)
    for i in range(0,len(m)):
        k.append(f)
    print(k)
    for i in range(0,len(m)):
        for j in range(0,len(m)):
            print("REPLACING POSITION:",i,j )
            t=m[i][j]
            k[j][len(m)-i-1]=t
    return (k)
print(rotate([[1,2],[3,4]]))

I expect the output:

[[1, 2], [3, 4]]
[[0, 0], [0, 0]]
REPLACING POSITION: 0 0
REPLACING POSITION: 0 1
REPLACING POSITION: 1 0
REPLACING POSITION: 1 1
[[3, 1], [4, 2]]

I am getting the output:

[[1, 2], [3, 4]]
[[0, 0], [0, 0]]
REPLACING POSITION: 0 0
REPLACING POSITION: 0 1
REPLACING POSITION: 1 0
REPLACING POSITION: 1 1
[[4, 2], [4, 2]]

Why does the last row keep on repeating? Please help.

MichaelD
  • 1,274
  • 1
  • 10
  • 16

2 Answers2

3

Your first loop generates the list f. Your next for loop generates the list k, which is meant to contain len(m) copies of list f. The problem is f (and most lists) are just pointers. So list k is actually a list of pointers to the same list f.

Thus all the modifications you make to elements of f in k are made to the same list.

One solution is to use a copy of list f when generating list k by using the slice operator:

    for i in range(0,len(m)):
        k.append(f[:])
drootang
  • 2,351
  • 1
  • 20
  • 30
0

Use f.copy() to get deep copy of the list.

    def rotate(m):
    k=[]
    f=[]
    print(m)
    for _ in range(0,len(m)):
        f.append(0)
    for _ in range(0,len(m)):
        k.append(f.copy())
    for i in range(0,len(m)):
        for j in range(0,len(m)):
            print("REPLACING POSITION:",i,j )
            t=m[i][j]
            k[j][len(m)-i-1]=t

            print(j,len(m)-i-1)           
    return k


print(rotate([[1,2],[3,4]]))
Ahmad Farhan
  • 575
  • 4
  • 12