def paintPointsBlack(originalBoard, point0, point1, point2):
board = originalBoard[:]
# do something
return board
def fillTheBoard(board, point):
movePointToWhitePoint(board, point)
if point['row'] == height - 1:
print('last line. terminate')
return
elif point['row'] != height - 1:
LCanFit = canPutLShape(board, point)
if LCanFit['total'] != 0:
point0 = dict(point)
if LCanFit['RdD'] == 1:
...
newBoard = paintPointsBlack(board[:], point, point1, point2)
fillTheBoard(newBoard, point0)
if LCanFit['DL'] == 1:
...
newBoard = paintPointsBlack(board[:], point, point1, point2)
fillTheBoard(newBoard, point0)
if LCanFit['RD'] == 1:
...
newBoard = paintPointsBlack(board[:], point, point1, point2)
fillTheBoard(newBoard, point0)
if LCanFit['DR'] == 1:
...
newBoard = paintPointsBlack(board[:], point, point1, point2)
fillTheBoard(newBoard, point0)
print("inspected everything around : ", point['row'], point['col'])
else:
return
fillTheBoard
是在某些条件(LCanFit
)匹配时调用的函数。 if
有很多,为了使其正常工作,初始传递的参数board
不应在if
的相同深度处改变。可能会更改board
的唯一函数是paintPointsBlack
,但为避免这种情况,我传递了副本(board[:]
),并进行了一次谨慎但无意义的尝试,使它复制了参数在paintPointsBlack
中。
我遇到的问题是,在递归的一个分支完成之后,board
仍然会更改,并移至下一个分支(下一个if
)。因此,board
内的if LCanFit['RdD'] == 1
和board
内的if LCanFit['DL'] == 1
(相同的深度)是不同的,因为board
更改为{{1}最后调用的函数(与前一个newBoard
一起使用的最深函数)。
我知道按值传递无法更改原始内容,但我仍然看到它会更改if
,而且如此令人困惑。如果我最好重写代码,应该如何构造它?