Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Python 2
- # simple sudoku scratchpad
- #
- # Sample grid load:
- # =916354872 873629154 524718936 768935241 149287365 235461798 697842513 381576429 452193
- # Solution to sample (687 in locations 7,9, 8,9, and 9,9):
- # 796 898 997
- grid = ['.'] * 81
- def row_set (y):
- return set(grid[y*9: y*9+9]) - set('.')
- def col_set (x):
- return set(grid[x: x+81: 9]) - set('.')
- # Box #s 0..8 left-to-right and top-to-bottom
- def box_set (n):
- return set([grid[y*9+x]
- for x in range((n % 3) * 3, (n % 3) * 3 + 3)
- for y in range(n // 3 * 3, n // 3 * 3 + 3)]) - set('.')
- def format_row (y):
- return '|' + ''.join(grid[y*9: y*9+3]) + \
- '|' + ''.join(grid[y*9+3: y*9+6]) + \
- '|' + ''.join(grid[y*9+6: y*9+9]) + '|'
- def print_grid ():
- print ' x123 456 789'
- print 'y+---+---+---+'
- for y in range(0, 9):
- print str(y+1) + format_row(y)
- if y % 3 == 2: print ' +---+---+---+'
- def load_grid (digits):
- grid = ['.'] * 81
- for i in range(0, min(81, len(digits))):
- set_grid(i % 9, i // 9, digits[i])
- def set_grid (x, y, digit):
- if '1' <= digit <= '9':
- box = y // 3 * 3 + x // 3
- if digit in col_set(x):
- print 'There is already a', digit, 'in column', x + 1
- elif digit in row_set(y):
- print 'There is already a', digit, 'in row', y + 1
- elif digit in box_set(box):
- print 'There is already a', digit, 'in box', box + 1
- else:
- grid[y * 9 + x] = digit
- else:
- grid[y * 9 + x] = '.'
- print "Enter '= digit digit ...' to load the grid (0 or . for empty)."
- print "Enter 'x y digit ...' to set specific grid squares."
- while True:
- changes = list(raw_input('Load/change: ').replace(' ', ''))
- if len(changes) and changes[0] == '=':
- load_grid(changes[1:])
- else:
- while len(changes) > 2:
- set_grid(int(changes[0]) - 1, int(changes[1]) - 1, changes[2])
- changes = changes[3:]
- print_grid()
- if '.' not in grid:
- print 'Solved!'
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement