Given a two dimensional matrix, e.g.
l = [[1,1,1],
[2,5,2],
[3,3,3]])
What is the most efficient way of implementing a shift operatio
This is a generic version you can rotate it in all four directions, any number of times
l = [[1,1,1],
[2,5,2],
[3,3,3]]
def shift(direction, count, myList):
myLen = len(myList)
if direction == "up":
return [myList[i % myLen] for i in range(count, count + myLen)]
elif direction == "down":
return [myList[-i] for i in range(count, count - myLen, -1)]
elif direction == "left":
tlist = zip(*myList)
return map(list, zip(*[tlist[i % myLen] for i in range(count, count + myLen)]))
elif direction == "right":
tlist = zip(*myList)
return map(list, zip(*[tlist[-i] for i in range(count, count - myLen, -1)]))
print shift("up", 1, l)
print shift("up", 2, l)
print shift("down", 2, l)
print shift("down", 1, l)
print shift("left", 1, l)
print shift("right", 1, l)
Output
[[2, 5, 2], [3, 3, 3], [1, 1, 1]]
[[3, 3, 3], [1, 1, 1], [2, 5, 2]]
[[2, 5, 2], [3, 3, 3], [1, 1, 1]]
[[3, 3, 3], [1, 1, 1], [2, 5, 2]]
[[1, 1, 1], [5, 2, 2], [3, 3, 3]]
[[1, 1, 1], [2, 2, 5], [3, 3, 3]]