Advertisement
briank

sudoku_grid.py

Feb 13th, 2013
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. # Python 2
  2. # simple sudoku scratchpad
  3. #
  4. # Sample grid load:
  5. # =916354872 873629154 524718936 768935241 149287365 235461798 697842513 381576429 452193
  6. # Solution to sample (687 in locations 7,9, 8,9, and 9,9):
  7. # 796 898 997
  8.  
  9. grid = ['.'] * 81
  10.  
  11. def row_set (y):
  12.     return set(grid[y*9: y*9+9]) - set('.')
  13.  
  14. def col_set (x):
  15.     return set(grid[x: x+81: 9]) - set('.')
  16.  
  17. # Box #s 0..8 left-to-right and top-to-bottom
  18. def box_set (n):
  19.     return set([grid[y*9+x]
  20.       for x in range((n % 3) * 3, (n % 3) * 3 + 3)
  21.       for y in range(n // 3 * 3, n // 3 * 3 + 3)]) - set('.')
  22.  
  23. def format_row (y):
  24.     return '|' + ''.join(grid[y*9: y*9+3]) + \
  25.       '|' + ''.join(grid[y*9+3: y*9+6]) + \
  26.       '|' + ''.join(grid[y*9+6: y*9+9]) + '|'
  27.  
  28. def print_grid ():
  29.     print ' x123 456 789'
  30.     print 'y+---+---+---+'
  31.     for y in range(0, 9):
  32.         print str(y+1) + format_row(y)
  33.         if y % 3 == 2: print ' +---+---+---+'
  34.  
  35. def load_grid (digits):
  36.     grid = ['.'] * 81
  37.     for i in range(0, min(81, len(digits))):
  38.     set_grid(i % 9, i // 9, digits[i])
  39.  
  40. def set_grid (x, y, digit):
  41.     if '1' <= digit <= '9':
  42.     box = y // 3 * 3 + x // 3
  43.     if digit in col_set(x):
  44.         print 'There is already a', digit, 'in column', x + 1
  45.     elif digit in row_set(y):
  46.         print 'There is already a', digit, 'in row', y + 1
  47.     elif digit in box_set(box):
  48.         print 'There is already a', digit, 'in box', box + 1
  49.     else:
  50.         grid[y * 9 + x] = digit
  51.     else:
  52.     grid[y * 9 + x] = '.'
  53.  
  54. print "Enter '= digit digit ...' to load the grid (0 or . for empty)."
  55. print "Enter 'x y digit ...' to set specific grid squares."
  56. while True:
  57.     changes = list(raw_input('Load/change: ').replace(' ', ''))
  58.     if len(changes) and changes[0] == '=':
  59.     load_grid(changes[1:])
  60.     else:
  61.     while len(changes) > 2:
  62.         set_grid(int(changes[0]) - 1, int(changes[1]) - 1, changes[2])
  63.         changes = changes[3:]
  64.     print_grid()
  65.     if '.' not in grid:
  66.     print 'Solved!'
  67.     break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement