2

So I wrote a code that yields a grid with the help of some helpful stackoverflow users, and here it is..

import random
import string

for x in range(4):
    for y in range(4):
        print( '['+random.choice(string.ascii_letters)+']',end='' )
    print()

and now I want to create a function moveleft(grid) that will move every column to the left

For instance, if my grid looks like this at first..

[k][b][s][v]
[u][w][p][O]
[t][i][i][K]
[n][J][r][f]

then after executing moveleft(grid), this will be my grid,

[v][k][b][s]
[O][u][w][p]
[K][t][i][i]
[f][n][J][r]

what should I write up for moveleft(grid) to work as the example provided above?

OTheDev
  • 2,916
  • 2
  • 4
  • 20
Droid
  • 520
  • 1
  • 7
  • Your code does not _store_ the grid, it just _prints_ it. So the first step is to store the grid, perhaps in a `list` of `list`s, or a `numpy.ndarray` or whatever – gimix May 04 '22 at 06:15

1 Answers1

2

numpy.roll does this. For example,

>>> import numpy as np
>>> grid = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> grid
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.roll(grid, shift=1, axis=1)
array([[3, 1, 2],
       [6, 4, 5],
       [9, 7, 8]])
Dilara Gokay
  • 418
  • 3
  • 10