Reputation: 2567
Im trying to work on a popular python question - rotating a 2D list. Given a list = [[1,2,3,4],[5,6,7,8],[12,13,14,15]]
.
I know a very simple solution exists which is : zip(*list[::-1]
. But I wanted to create my own function. So i go this:
def flip(list):
output = []
temp = len(list)
for row in range(temp):
newlist = []
for col in range(temp):
newlist.append(list[col][temp - row - 1])
print list[col][temp - row -1]
output.append(newlist)
But this only works when we have an n*n
matrix. What should I change if I have am*n
matrix . What am i doing wrong here
Upvotes: 1
Views: 97
Reputation: 3503
Define your row and col length from the original list and then create. With some changes to your code here is something that can work for mxn. However this doesn't work if your inner lists are of not same length. zip(*list[::-1]) will give you the output using the list with minimum length. You need to make more changes for that.
def flip(list):
output = []
rowLength = len(list)
colLength = len(list[0])
for row in range(colLength):
newlist = []
for col in range(rowLength):
newlist.append(list[col][row])
print list[col][row]
output.append(newlist)
return output
Upvotes: 0
Reputation: 387677
You are using temp = len(list)
as the upper boundary for both iterations. A m×n matrix of course requires different boundaries each.
If you assume that each inner list in the outer list has the same length, you could just save both lengths first and iterate to those sizes then:
m = len(list)
n = len(list[0])
Upvotes: 3