The immutable and mutable is causing problem.
I was trying to rotate the matrix by 90 degree clockwise without changing the argument passed in function.
def rotate(m):
rm=[[0]*len(m)]*(len(m))
print("m:",m)
print("rm:",rm)
for j in range(len(rm)):
for i in range(len(rm)):
k=m[j][i]
y=(len(rm)-j-1)
rm[i][y] = k
print(i," ",len(rm)-j-1," ",rm[i][(len(rm)-j-1)])
print("m:",m)
print("rm:",rm)
return rm
print(rotate([[1,2,3],[4,5,6],[7,8,9]]))
I expect the rm should be "[[7, 4, 1], [8, 5, 2], [9, 6, 3]]" but it is "[[9, 6, 3], [9, 6, 3], [9, 6, 3]]" at the end of function.
Harshal Parekh
6,0374 gold badges25 silver badges46 bronze badges
asked Aug 17, 2019 at 23:13
1 Answer 1
You are seeing the error, because the line rm=[[0]*len(m)]*(len(m))
. Try to change it for:
rm = [[0 for _ in range(len(m))] for _ in range(len(m))]
Note: The above function can be rewritten as:
l = [[1,2,3],[4,5,6],[7,8,9]]
def rotate(lst):
return [list(val[::-1]) for val in zip(*lst)]
print(rotate(l))
This prints:
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
answered Aug 18, 2019 at 4:37
-
Wow. I think this is something that is important and non-obvious (maybe it is obvious to everyone but me, I dunno).
rm1=[[0]*3]*3
(OPs approach) andrm2=[[0 for _ in range(3)] for _ in range(3)]
(Andrej's approach) will produce listsrm1
andrm2
that look alike and compare equal, but behave differently. Assigningrm1[0][0]=33
will result in list[[33, 0, 0], [33, 0, 0], [33, 0, 0]]
whereas assigningrm2[0][0]=44
will result in list[[44, 0, 0], [0, 0, 0], [0, 0, 0]]
.Wilf Rosenbaum– Wilf Rosenbaum2019年08月18日 05:21:18 +00:00Commented Aug 18, 2019 at 5:21
lang-py