generate valid sudoku board python

Solutions on MaxInterview for generate valid sudoku board python by the best coders in the world

showing results for - "generate valid sudoku board python"
Ivan
07 Jul 2017
1base  = 3
2side  = base*base
3
4# pattern for a baseline valid solution
5def pattern(r,c): return (base*(r%base)+r//base+c)%side
6
7# randomize rows, columns and numbers (of valid base pattern)
8from random import sample
9def shuffle(s): return sample(s,len(s)) 
10rBase = range(base) 
11rows  = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ] 
12cols  = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ]
13nums  = shuffle(range(1,base*base+1))
14
15# produce board using randomized baseline pattern
16board = [ [nums[pattern(r,c)] for c in cols] for r in rows ]
17
18for line in board: print(line)
19
20[6, 2, 5, 8, 4, 3, 7, 9, 1]
21[7, 9, 1, 2, 6, 5, 4, 8, 3]
22[4, 8, 3, 9, 7, 1, 6, 2, 5]
23[8, 1, 4, 5, 9, 7, 2, 3, 6]
24[2, 3, 6, 1, 8, 4, 9, 5, 7]
25[9, 5, 7, 3, 2, 6, 8, 1, 4]
26[5, 6, 9, 4, 3, 2, 1, 7, 8]
27[3, 4, 2, 7, 1, 8, 5, 6, 9]
28[1, 7, 8, 6, 5, 9, 3, 4, 2]
29