How to create lists of 3x3 sudoku block in python

后端 未结 5 1678
长发绾君心
长发绾君心 2021-01-23 11:27

I need help creating a list for each of the 9 3x3 blocks in sudoku. so I have a list of lists representing the original sudoku board (zero means empty):

board=[[         


        
5条回答
  •  广开言路
    2021-01-23 12:18

    You can do this with a combination of reshape and transpose when you use numpy.

    edit - sorry - hit enter too soon:

    import numpy as np
    board=[[2,0,0,0,0,0,0,6,0],
           [0,0,0,0,7,5,0,3,0],
           [0,4,8,0,9,0,1,0,0],
           [0,0,0,3,0,0,0,0,0],
           [3,0,0,0,1,0,0,0,9],
           [0,0,0,0,0,8,0,0,0],
           [0,0,1,0,2,0,5,7,0],
           [0,8,0,7,3,0,0,0,0],
           [0,9,0,0,0,0,0,0,4]]
    
    t = np.array(board).reshape((3,3,3,3)).transpose((0,2,1,3)).reshape((9,9));
    print t
    

    Output:

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

提交回复
热议问题