I am trying to wrap my head around mutable object passed in function. In the code below, solutionList
and outSoln
return two different lists. From my understanding, the append
function appends by reference. I tried to use solutionList.append(sudoku[:])
and solutionList.append(list(sudoku))
as done in other SO answers but it does not seem to work.
Is there a better way to do that assigning two global variables?
code:
def solve(options, onlyOneSoln=False):
global sudoku
global solutionList
global outSoln
if len(solutionList) > 5:
return True
for y in range(9):
for x in range(9):
# print("x: %s" %x)
if sudoku[y][x]==0:
for val in range(1,10):
if len(solutionList)>0 and onlyOneSoln:
break
if possible(val,y, x, sudoku, options):
sudoku[y][x]=val
solve(options, prnt, onlyOneSoln)
sudoku[y][x]=0
# print_sudoku(sudoku)
# print("could not assign value -- backtracking")
return
solutionList.append(sudoku[:])
outSoln =copy.deepcopy(solutionList)
sudoku = [[0, 0, 0, 0, 0, 8, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 4, 0],
[0, 0, 0, 0, 0, 0, 2, 0, 6],
[0, 4, 7, 0, 5, 0, 0, 9, 0],
[8, 0, 0, 6, 0, 3, 0, 0, 5],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 6, 5, 0, 0],
[0, 0, 8, 0, 0, 2, 9, 0, 0],
[9, 7, 0, 0, 0, 0, 0, 0, 1]]
solutionList = []
outSoln= []
solve([''])
print("outsoln:")
print(outSoln)
print("\nsolutionList:")
print(solutionList)
output:
outsoln:
[[[2, 3, 4, 1, 6, 8, 7, 5, 9], [1, 5, 6, 2, 7, 9, 8, 4, 3], [7, 8, 9, 3, 4, 5, 2, 1, 6], [6, 4, 7, 8, 5, 1, 3, 9, 2], [8, 2, 1, 6, 9, 3, 4, 7, 5], [3, 9, 5, 4, 2, 7, 1, 6, 8], [4, 1, 2, 9, 3, 6, 5, 8, 7], [5, 6, 8, 7, 1, 2, 9, 3, 4], [9, 7, 3, 5, 8, 4, 6, 2, 1]], [[2, 3, 4, 1, 6, 8, 7, 5, 9], [1, 5, 6, 2, 7, 9, 8, 4, 3], [7, 8, 9,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