4. janúar 2007

Rotating a matrix CW/CCW in Python

Just for those of you who are wondering, like I was :)

import sys, os

def rotate( indata, height, width, rotate_ccw ):
outdata = []
for col in range( width ):
newrow = []
for row in range( height ):
if( rotate_ccw ):
newrow.append( indata[row][(width-1)-col])
else:
newrow.append( indata[(height-1)-row][col])
outdata.append( newrow )
return outdata

#Test the rotation
test = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

print test
print "Rotate CW"
rotated = rotate(test, 3, 3, False )
print rotated
print "Rotate CCW"
print rotate(rotated, 3, 3, True )

In under 15 minutes, hurray for Python!

Engin ummæli: