Patrick Patrick - 1 month ago 7
Python Question

convert text into a series of lists

For fun - and to learn python (3.5), I'm programming a sudoku solver. At the moment, I have hard-coded a grid in the code so I can develop/test it.

# initialise list. It generates a 9x9 grid full of zeroes
matrix = [[0 for y in range(9)] for x in range(9)]

# generate hard-coded board. 0 means the cell is empty
matrix[0] = [0, 0, 3, 0, 2, 0, 6, 0, 0]
matrix[1] = [9, 0, 0, 3, 0, 5, 0, 0, 1]
matrix[2] = [0, 0, 1, 8, 0, 6, 4, 0, 0]
matrix[3] = [0, 0, 8, 1, 0, 2, 9, 0, 0]
matrix[4] = [7, 0, 0, 0, 0, 0, 0, 0, 8]
matrix[5] = [0, 0, 6, 7, 0, 8, 2, 0, 0]
matrix[6] = [0, 0, 2, 6, 0, 9, 5, 0, 0]
matrix[7] = [8, 0, 0, 2, 0, 3, 0, 0, 9]
matrix[8] = [0, 0, 5, 0, 1, 0, 3, 0, 0]


...which corresponds to this grid:

- - 3 | - 2 - | 6 - -
9 - - | 3 - 5 | - - 1
- - 1 | 8 - 6 | 4 - -
---------------------
- - 8 | 1 - 2 | 9 - -
7 - - | - - 4 | 1 - 8
- - 6 | 7 - 8 | 2 - -
---------------------
- - 2 | 6 - 9 | 5 - -
8 - - | 2 - 3 | - - 9
- - 5 | 4 1 - | 3 - -


Now that I've been able to solve this particular board (YAY! :), I'd like to change it to test the code works with a new puzzle. Instead of changing the numbers one by one, is there a way I can input something like:

new_puzzle = "
200080300
060070084
030500209
000105408
000000000
402706000
301007040
720040060
004010003"


and somehow converting it into a matrix like the one above (so, for example:

matrix[0] = [2,0,0,0,8,0,3,0,0]
matrix[1] = [0,6,0,0,7,0,0,8,4]
# etc...

Answer

First of all, if you want to use multiline strings, you have to use """:

new_puzzle = """
200080300
...
"""

Then you can use a list comprehension to convert the lines to a list of lists:

>>> [list(map(int, row)) for row in new_puzzle.strip().splitlines()]
[[2, 0, 0, 0, 8, 0, 3, 0, 0], [0, 6, 0, 0, 7, 0, 0, 8, 4], [0, 3, 0, 5, 0, 0, 2, 0, 9], [0, 0, 0, 1, 0, 5, 4, 0, 8], [0, 0, 0, 0, 0, 0, 0, 0, 0], [4, 0, 2, 7, 0, 6, 0, 0, 0], [3, 0, 1, 0, 0, 7, 0, 4, 0], [7, 2, 0, 0, 4, 0, 0, 6, 0], [0, 0, 4, 0, 1, 0, 0, 0, 3]]
Comments