Saturday, June 17, 2017

Schooled in Efficient Code - by Udacity

Take a sudoku grid and implement the only-choice - that is, when you have multiple choices for numbers to put in a square - when one of those choices occurs only in this square, you know what to do..

My answer :

    for box in unit :
        for choice in grid[box] :
            others = ''.join( [ grid[x] for x in unit if not x == box ] )
            if not re.search( choice , others ) :
                grid[box] = choice

And U :

    for digit in '123456789':
         dplaces = [box for box in unit if digit in values[box]]
         if len(dplaces) == 1:
             values[dplaces[0]] = digit

For each number in 1..9, they get the boxes that contain that number and then, when there's only one box for a particular number, they assign that number to that box - yes, you'll be doing some redundant work, but ain't the code short and sweet?

Look at me - I first get a string made up of the contents of all the other boxes and then I check if this box's contents (one number at a time) occur in that string..

No comments: