![]() The code only works for 9×9 Sudoku grids made up of 3×3 blocks. It turns out to be just as fast, but a lot simpler, to test all the entries in previous rows of the block, like this: i0, j0 = i - i % 3, j - j % 3 # origin of 3x3 block You avoid an unnecessary test, but at the cost of a lot of extra code. The reason you go to this trouble is to avoid testing against board and board, which you know would be useless, because you already tested these cells when you checked the column. The code for checking against other cells in the 3×3 block is very repetitive: if i % 3 = 1: ![]() # No number is valid in this cell, start over.Ĭan be simplified using the built-in function any: if any(row = checkMe for row in board): continue # If we've reached here, the number is valid. Write a for loop with an else: for x in checking: Instead of this complex while loop: x = -1 format(*(cell or ' ' for cell in line)))Ĭan be combined into one using itertools.product: for i, j in itertools.product(range(9), repeat=2): #If we've reached here, the number is valid. If j % 3 = 0 and checkMe in (board,board,board,board): continueĮlif j % 3 = 1 and checkMe in (board,board,board,board): continueĮlif j % 3 = 2 and checkMe in (board,board,board,board): continue If j % 3 = 0 and checkMe in (board,board): continueĮlif j % 3 = 1 and checkMe in (board,board): continueĮlif j % 3 = 2 and checkMe in (board,board): continue #Check if the number is elsewhere in this 3x3 grid based on where this is in the 3x3 grid #No number is valid in this cell, start over I'm maybe just being impractical to want a more intelligent solution so I thought I'd ask how it looks to people on here and if anyone has suggestions on improving it. In practical terms that's almost negligible but still seems wasteful to ditch the processing up to that point (as it takes, on average, hundreds of attempts to find a valid puzzle). I tested it by making 1000 puzzles and it took just under 100 seconds, so a single puzzle takes 0.1. It loops over all the numbers from 1-9 and then if it finds itself trapped in a corner with no valid answers it throws out the whole board and restarts. It currently runs through each line of the 9x9 grid and places numbers randomly if they're valid.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |