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
Maybe something like this using numpy
:
def shift(x, direction='up'):
if direction == 'up':
temp = range(x.shape[0])
indicies = temp[1:] + [temp[0]]
return x[indicies]
elif direction == 'left':
temp = range(x.shape[1])
indicies = temp[1:] + [temp[0]]
return x[:, indicies]
else:
print 'Error direction not known'
Result:
>>> shift(l, direction='up')
array([[2, 5, 2],
[3, 3, 3],
[1, 1, 1]])
>>> shift(l, direction='left')
array([[1, 1, 1],
[5, 2, 2],
[3, 3, 3]])
>>> shift(l, direction='to the moon')
Error direction not known