6

I have a large matrix that represents.. say a Rubik's cube.

>>cube

>>[[-1, -1, -1,  1,  2,  3, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  4,  5,  6, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  7,  8,  9, -1, -1, -1, -1, -1, -1],
   [ 1,  2,  3,  4,  5,  6,  7,  8,  9,  8,  1,  8],
   [ 4,  5,  6,  0,  7,  7,  6,  9,  6,  8,  1,  0],
   [ 7,  8,  9,  6,  9,  7,  6,  6,  9,  0,  1,  7],
   [-1, -1, -1,  1,  1,  0, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  8,  8,  1, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  8,  0,  1, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  7,  1,  0, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  0,  1,  8, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  8,  1,  8, -1, -1, -1, -1, -1, -1]])

I have sliced it into parts that represent the faces.

top_f   = cube[0:3,3:6]
botm_f  = cube[6:9,3:6]

back_f  = cube[3:6,9:12]
front_f = cube[3:6,3:6]
left_f  = cube[3:6,0:3]
right_f = cube[3:6,6:9]

I want to now assign a modified matrix to the left face.

left_f = numpyp.rot90(left_f, k=3)

But this does not change the values in the parent matrix cube. I understand this is because the newly generated matrix is being assigned to the variable left_f and so the reference to the sub-slice cube[3:6,0:3] is lost.

I could just resort to replacing it directly.

cube[3:6,0:3] = numpyp.rot90(left_f, k=3)

But that wouldn't be very readable. How do I assign a new matrix to a named slice of another matrix in a pythonic way?

Harsh
  • 166
  • 8
  • 1
    What about `cube[3:6,0:3] = left_f` after `left_f = numpyp.rot90(left_f, k=3)` ? I'd say that your code is pythonic enough. When working with matrices, you're bound to work with many indices. – Eric Duminil Mar 11 '17 at 12:27
  • 1
    BTW, isn't `cube` too big? The last 3 rows aren't used. – Eric Duminil Mar 11 '17 at 12:29
  • @eric-duminil Yes that would do the trick but its not ideal. Suppose later I change left_f slice to some other part of the matrix say `cube[3:6,1:4]` then I would have to hunt throughout the code to replace those parts. I wish to keep the explicit use of the indexes to minimum. – Harsh Mar 11 '17 at 12:34
  • 1
    You might need another data structure. [This](http://stackoverflow.com/questions/500221/how-would-you-represent-a-rubiks-cube-in-code) might help you. – Eric Duminil Mar 11 '17 at 12:39
  • The cube is purposefully three rows bigger, I am actually using it to keep another representation of the back_f so that I can easily roll the columns for representing moves. I have changed the matrix in the question to show this. – Harsh Mar 11 '17 at 12:40
  • Thanks. I'll look into those other data structures. – Harsh Mar 11 '17 at 12:45

1 Answers1

3

You can assign your slices to a variable:

left_face = slice(3, 6), slice(0, 3)
cube[left_face] = np.rot90(cube[left_face], k=3)
Tristan
  • 1,576
  • 9
  • 12