我是新来的Python和面向对象编程中一般,所以请原谅,或许,非常设计不良的代码(任何提示将不胜感激)。
在此,做作,MWE这纯粹是为了说明我的较大项目有类似的问题。我通过一个3x3格要迭代和填充它,这样它包含所有的数字1-9,我可以改变的值只有其当前设置的。A 0,即如果电网目前有数字1-7和两个位置是0,则这些0中的一个变成一个8和一个成为如图9所示,在这种情况下有由于图8和9的顺序两种溶液也可以交换。
我设计了一个回溯求解器(runSolver()),并且它确实解决这个问题,我很努力,虽然做的是存储解决方案时,我接触他们。我已经加入达成解决方案时的打印语句,并能打印出预期的解决方案,我再尝试这种解决方案追加到一个列表,而不是附加刚刚发现它,而不是追加初始,尚未解决的解决方案,网格。
class Grid:
def __init__(self):
self.grid = np.zeros((3, 3))
def writeGrid(self, grid):
self.grid = grid
def printGrid(self):
print(self.grid)
def getValue(self, col, row):
return self.grid[row][col]
def setValue(self, col, row, num):
self.grid[row][col] = num
class Solver:
def __init__(self, grid):
self.grid = grid
self.solutions = []
self.n_solutions = 0
def isValid(self, num):
for i in range(3):
for j in range(3):
if self.grid.getValue(i, j) == num:
return False
return True
def runSolver(self):
for row in range(3):
for col in range(3):
if (self.grid.getValue(col, row)) == 0:
for num in range(1,10):
if self.isValid(num):
self.grid.setValue(col, row, num)
self.runSolver()
self.grid.setValue(col, row, 0)
return
self.grid.printGrid() # this line prints the actual solutions when reached (it works)
self.solutions.append(self.grid) # this should append the solution to 'solutions'
self.n_solutions += 1 # keeps track of how many solutions there are
其主要功能实际上说明问题的话,
# Set up game
gameGrid = Grid()
gameGrid.writeGrid([[1, 4, 5],
[0, 6, 0],
[7, 8, 9]])
solverGrid = Solver(gameGrid)
# Run the solver
solverGrid.runSolver()
# This should print out the found solutions,
# It actually prints out the initial, unsolved, grid twice
for i in range(solverGrid.n_solutions):
solverGrid.solutions[i].printGrid()
从一些网上搜索我想我可能会越来越实例属性和类属性,以及与他们接近,但是我真的不知道该范围之间的混淆。
当你运行self.solutions.append(self.grid)
你基本上只是追加一个参考的self.grid
来self.solutions
。因此,在你结束runSolver
你的引用列表中的self.solutions
所有指向同一个对象。
这是与事实,无论你做Grid
对象和numpy的数组都是可变的对象。相较于Python字符串,例如,当你修改它们(带self.grid.setValue(col, row, num)
为例),相同的对象代替,而不是创建新对象修改。
这里是一个列表的列表说明了同样的问题:
>>> l = []
>>> x = [1]
>>> l.append(x)
>>> l
[[1]]
>>> x.append(2)
>>> l.append(x)
>>> l
[[1, 2], [1, 2]]
你必须每次你把它添加到时间创建网格的副本self.solutions
,这样你可以有一个网格的“快照”,因为它是在这一点上。
你可以这样做:
class Grid:
def __init__(self, grid=None):
if grid == None:
self.grid = np.zeros((3, 3))
else:
# Copy the array, otherwise we'll have the same mutability issue as above.
self.grid = np.copy(grid)
在runSolver
:
grid_copy = Grid(self.grid.grid)
self.solutions.append(grid_copy) # this should append the solution to 'solutions'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句