Sudoku in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • v2rocketboy
    New Member
    • Apr 2010
    • 5

    Sudoku in python

    I am looking to make an autofill function for a sudoku game in python. I want to make a function that fills empty squares in with values. If there is only one possible answer by analysis of the row and column and 3x3 box that it is in. Any suggestions and how to do this?
    Last edited by Niheel; May 10 '10, 11:24 AM. Reason: grammar and punctuation
  • leegao
    New Member
    • Mar 2010
    • 3

    #2
    I'm not quite sure if you still need this still, but the basic gist would be something like

    Code:
    if __name__ == "__main__":
        grid = []
        from random import randint
        
        SIZE = 9
        MINI = 3
        
        HARD = int(float(SIZE)*1.5)
        MEDIUM = SIZE*2+2
        EASY = SIZE*3
        
        for i in range(SIZE):
            _grid = []
            for r in range(SIZE): _grid += [0]
            grid += [_grid]
        for r in range(EASY):
            n = randint(1,SIZE)
            a = randint(0,SIZE-1)
            b = randint(0,SIZE-1)
            aa = a/MINI
            bb = b/MINI
            mini = [g[bb*MINI:bb*MINI+MINI] for g in grid[aa*MINI:aa*MINI+MINI]]
            coverage = set()
            for x in mini:
                for y in x:
                    coverage.add(y) if y else None
            if n in coverage: continue
            if n in grid[a]: continue
            if n in [x[b] for x in grid]: continue
            grid[a][b]=n
        print(("\n").join([" ".join([str(g) if g else "_" for g in s]) for s in grid]))
    This still doesn't anticipate a few types of traps so to clear this up, write a function to see if you can actually solve the puzzle

    Note: Python2.x friendly rendition of http://www.cs.mcgill.ca/~aassaf9/pyt...gorithm_x.html
    Code:
    # Author: Ali Assaf <ali.assaf.mail@gmail.com>
    # Copyright: (C) 2010 Ali Assaf
    # License: GNU General Public License <http://www.gnu.org/licenses/>
    
    from itertools import product
    
    def solve_sudoku(size, grid):
        R, C = size
        N = R * C
        X = ([("rc", rc) for rc in product(range(N), range(N))] +
             [("rn", rn) for rn in product(range(N), range(1, N + 1))] +
             [("cn", cn) for cn in product(range(N), range(1, N + 1))] +
             [("bn", bn) for bn in product(range(N), range(1, N + 1))])
        Y = dict()
        for r, c, n in product(range(N), range(N), range(1, N + 1)):
            b = (r // R) * R + (c // C) # Box number
            Y[(r, c, n)] = [
                ("rc", (r, c)),
                ("rn", (r, n)),
                ("cn", (c, n)),
                ("bn", (b, n))]
        X, Y = exact_cover(X, Y)
        for i, row in enumerate(grid):
            for j, n in enumerate(row):
                if n:
                    select(X, Y, (i, j, n))
        for solution in solve(X, Y, []):
            for (r, c, n) in solution:
                grid[r][c] = n
            yield grid
    
    def exact_cover(X, Y):
        _x = {}
        for j in X: _x[j] = set()
        X = _x
        for i, row in Y.items():
            for j in row:
                X[j].add(i)
        return X, Y
    
    def solve(X, Y, solution):
        if not X:
            yield list(solution)
        else:
            c = min(X, key=lambda c: len(X[c]))
            for r in list(X[c]):
                solution.append(r)
                cols = select(X, Y, r)
                for solution in solve(X, Y, solution):
                    yield solution
                deselect(X, Y, r, cols)
                solution.pop()
    
    def select(X, Y, r):
        cols = []
        for j in Y[r]:
            for i in X[j]:
                for k in Y[i]:
                    if k != j:
                        X[k].remove(i)
            cols.append(X.pop(j))
        return cols
    
    def deselect(X, Y, r, cols):
        for j in reversed(Y[r]):
            X[j] = cols.pop()
            for i in X[j]:
                for k in Y[i]:
                    if k != j:
                        X[k].add(i)
    
    for solution in solve_sudoku((MINI, MINI), grid):
            print("\n".join([" ".join([str(g) for g in s]) for s in solution]))
            break

    Comment

    • v2rocketboy
      New Member
      • Apr 2010
      • 5

      #3
      wow thankyou for your response i managed to get around it and got full marks on my own, but thank you for replying and putting in the effort to.

      Comment

      Working...