First comment: in your loops, you always loop over range(0, len(a))
. This assumes that the height and width are both equal to len(a)
, in other words this assume that a
is a square. However, your task makes sense for all rectangles, not just for squares. So, it is better not to make this assumption. Vertical indices for a
should loop over range(0,len(a))
, but horizontal indices for a
should loop over range(0, len(a[0]))
.
Second comment: rather than for j in range(len(a),0,-1): print(a[j-1][i],end=",")
, I recommend for j in range(len(a)-1,-1,-1): print(a[j][i],end=",")
Now on to actually performing the task.
Since your printing-loop works, you can turn it into a function that returns a new list of lists, by "printing into a list", using list.append
instead of print
. Just replace:
print(x, end='')
with row.append(x)
;
print()
with result.append(row); row=[]
:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # square
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] # non-square rectangle
def rotate_clockwise_append(a):
height, width = len(a), len(a[0])
result = []
row = []
for i in range(0,width):
for j in range(height-1,-1,-1):
row.append(a[j][i])
result.append(row)
row = []
return result
print(rotate_clockwise_append(a)) # [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
print(rotate_clockwise_append(b)) # [[9, 5, 1], [10, 6, 2], [11, 7, 3], [12, 8, 4]]
In python, it's always possible to build a list using a list comprehension, rather than using .append
in a loop:
def rotate_clockwise_listcomp(a):
height, width = len(a), len(a[0])
return [
[a[j][i] for j in range(height-1,-1,-1)]
for i in range(0,width)
]
print(rotate_clockwise_listcomp(a)) # [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
print(rotate_clockwise_listcomp(b)) # [[9, 5, 1], [10, 6, 2], [11, 7, 3], [12, 8, 4]]
You can also use builtin functions to do the reversal operations for you:
def rotate_clockwise_builtin(a):
return list(zip(*reversed(a))) # or list(map(list,zip(*reversed(a)))) if you're afraid of a list of tuples
print(rotate_clockwise_builtin(a)) # [(7, 4, 1), (8, 5, 2), (9, 6, 3)]
print(rotate_clockwise_builtin(b)) # [(9, 5, 1), (10, 6, 2), (11, 7, 3), (12, 8, 4)]
If you deal with rectangle arrays a lot, it is often recommended to use numpy rather than builtin python lists:
import numpy as np
def rotate_clockwise_numpy1(a):
return np.flip(a, axis = 0).T # flip vertically, then transpose
def rotate_clockwise_numpy2(a):
return np.flip(np.transpose(a), axis=1) # transpose, then flip horizontally
print(rotate_clockwise_numpy1(a))
# [[7 4 1]
# [8 5 2]
# [9 6 3]]
print(rotate_clockwise_numpy1(b))
# [[ 9 5 1]
# [10 6 2]
# [11 7 3]
# [12 8 4]]
print(rotate_clockwise_numpy2(a))
# [[7 4 1]
# [8 5 2]
# [9 6 3]]
print(rotate_clockwise_numpy2(b))
# [[ 9 5 1]
# [10 6 2]
# [11 7 3]
# [12 8 4]]