How to shift a list one more time than before each time?

625 views python
2

For example - a left shift:

Here is a grid of letters for example

tiwxz          
shshq          
avidy          
bsvsc          

This is the effect I want to have. The X symbol fills in the space created by the movement.

XXXtiwxz         # no shift
XXshshqX         # one shift left
XavidyXX         # two shift left
bsvscXXX         # three shift left
  • The grid of letters would be a list where each row is an item
  • I do not know how long the list is going to be
  • Solution should be pure python

How would I do a left shift and a right shift for grid?

This is all I have got:

def diags(grid, rev=False):
    n = len(grid)
    _grid = [list(row) + [None]*(n-1) for row in grid]  

answered question

By writing a python function.

Can you share your initial attempt? As written, this sounds like you’re asking a community of volunteers to write your python function.

stealththeninja I've added it

Seems these X's are appearing out of nowhere.

Jaba i said it in the question?

Yes, but just 3 of them or what amount are you trying to move them?

''shift a list one more time than before each time''

1 Answer

0

You can pad the left and right sides with Xs (or Nones) based on the row's index which you can get with enumerate:

grid = [list(s) for s in 'tiwxz shshq avidy bsvsc'.split()]
new_grid = [(['X'] * (len(grid) - 1) + lst)[i:] + ['X'] * i for i, lst in enumerate(grid)]

Output

for l in new_grid:
    print(l)

# ['X', 'X', 'X', 't', 'i', 'w', 'x', 'z']                                                                                                                      
# ['X', 'X', 's', 'h', 's', 'h', 'q', 'X']                                                                                                                      
# ['X', 'a', 'v', 'i', 'd', 'y', 'X', 'X']                                                                                                                      
# ['b', 's', 'v', 's', 'c', 'X', 'X', 'X']

posted this

Have an answer?

JD

Please login first before posting an answer.