Home > Enterprise >  How to save solved grid as a global variable?
How to save solved grid as a global variable?

Time:08-01

When I print the grid again outside the function I want it to show the solved grid as well. Rather, currently it only displays the initial variable set at the beginning of the code.

The reason my solve function shuffles the number list is because this function doubles to generate a new unique board given a grid of 9x9 0's :)

def possible(row,column,number):
    global grid
    for i in range(0,9):
        if grid[row][i] == number:
            return False
    for i in range(0,9):
        if grid[i][column] == number:
            return False
    x0 = (column // 3) * 3
    y0 = (row // 3) * 3
    for i in range (0,3):
        for j in range (0,3):
            if grid[y0 i][x0 j] == number:
                return False
    return True

def solve():
    global grid
    number_list = [1,2,3,4,5,6,7,8,9]
    random.shuffle(number_list) #Shuffles the first row of the solution
    for row in range(0,9):
        for column in range(0,9):
            if grid[row][column] == 0:
                for number in number_list:
                    if possible(row, column, number):
                        grid[row][column] = number
                        solve()
                        grid[row][column] = 0
                return
    print(np.matrix(grid))                
                
solve()
print(np.matrix(grid))  

CodePudding user response:

solve() is resetting values to zero as it is returning up through the call stack with grid[row][column] = 0, after the recursion call to solve().

CodePudding user response:

instead of calling solve() without parameters, pass to it a global object capable of storing the result, so the result is stored on that object.

def solve(globalObject: globalClass):
    ...
    globalObject.matrixGrid=np.matrix(grid)

problem=globalClass()
solve(problem)

print(problem.matrixGrid)
  • Related