Book Image

Learning NumPy Array

By : Ivan Idris
Book Image

Learning NumPy Array

By: Ivan Idris

Overview of this book

Table of Contents (14 chapters)
Learning NumPy Array
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Stride tricks for Sudoku


We can do even more fancy things with NumPy. The ndarray class has a field, strides, which is a tuple indicating the number of bytes to step in each dimension when going through an array. Sudoku is a popular puzzle originally from Japan; although it was known in a similar form before in other countries. If you don't know about Sudoku, it's maybe better that way because it is highly addictive. Let's apply some stride tricks to the problem of splitting a Sudoku puzzle to the 3 x 3 squares it is composed of:

  1. First define the Sudoku puzzle array, as shown in the following code snippet. This one is filled with the contents of the actual solved Sudoku puzzle (part of the array is omitted for brevity).

    sudoku = np.array([[2, 8, 7, 1, 6, 5, 9, 4, 3],[9, 5, 4, 7, 3, 2, 1, 6, 8],…[7, 3, 6, 2, 8, 4, 5, 1, 9]])
  2. Now calculate the strides. The itemsize field of ndarray gives us the number of bytes in an array. itemsize calculates the strides as follows:

    strides = sudoku.itemsize ...