0
import numpy as np
sudoku = np.array([   
    [2, 8, 7, 1, 6, 5, 9, 4, 3],
    [9, 5, 4, 7, 3, 2, 1, 6, 8],
    [6, 1, 3, 8, 4, 9, 7, 5, 2],
    [8, 7, 9, 6, 5, 1, 2, 3, 4],
    [4, 2, 1, 3, 9, 8, 6, 7, 5],
    [3, 6, 5, 4, 2, 7, 8, 9, 1],
    [1, 9, 8, 5, 7, 3, 4, 2, 6],
    [5, 4, 2, 9, 1, 6, 3, 8, 7],
    [7, 3, 6, 2, 8, 4, 5, 1, 9]
])
shape = (3, 3, 3, 3)
strides = sudoku.itemsize * np.array([27, 3, 9, 1])
squares = np.lib.stride_tricks.as_strided(sudoku, shape=shape, strides=strides) 
print(squares)

'''
[[[[2 8 7]    [9 5 4]    [6 1 3]]
  [[1 6 5]    [7 3 2]    [8 4 9]]
  [[9 4 3]    [1 6 8]    [7 5 2]]]

 [[[8 7 9]    [4 2 1]    [3 6 5]]
  [[6 5 1]    [3 9 8]    [4 2 7]]
  [[2 3 4]    [6 7 5]    [8 9 1]]]

 [[[1 9 8]    [5 4 2]    [7 3 6]]
  [[5 7 3]    [9 1 6]    [2 8 4]]
  [[4 2 6]    [3 8 7]    [5 1 9]]]]
'''

squares is a four dimensional array, i want to deal with it with some operations,but how can i recover squares to sudoku?

Lstack
  • 3
  • 2
  • What kind of operations? `squares` is a view of `sudoku`, so changes to one will be seen in the other. But be careful, some operations are likely to produce a copy, breaking the link between the two. For a start I'd suggest small experiments to get a clear idea of the relationship between the two. – hpaulj Nov 24 '18 at 07:05
  • Just change the value of some positions.What pullzes me is that how can i get a 2 dimensional array from the 4 dimensional array? – Lstack Nov 24 '18 at 07:21
  • Swap axes and reshape : `squares.swapaxes(1,2).reshape(9,9)`. Read more here : https://stackoverflow.com/questions/47977238/. – Divakar Nov 24 '18 at 07:25

1 Answers1

1

A simple solution is

from numpy import hstack
sudoku= hstack(hstack(squares))

Note that skimage.util.view_as_blocks does the direct operation:

rows=skimage.util.view_as_blocks(sudoku,(1,9))
cols=skimage.util.view_as_blocks(sudoku,(9,1))
blks=skimage.util.view_as_blocks(sudoku,(3,3))

sudoku= hstack(hstack()) reverse the three representations.

B. M.
  • 18,243
  • 2
  • 35
  • 54