【发布时间】:2019-09-30 03:48:52
【问题描述】:
除了返回语句之外,我有两个完全相同的函数。 如何在一个函数中使用变量来缩短第二个函数?
heuristic 和 heuristic2 是原始函数,理想情况下,我会将两者之一转换为 heuristic3 之类的函数。
这些不是完整的功能,但足以了解我正在尝试做什么。
def heuristic(self, state):
for currentState in argsWith0:
endX = (currentState - 1) // 3
endY = (currentState - 1) % 3
newSquare = state[currentState]
currentDistanceToDirtyNode = abs(endX - startX) + abs(endY - startY)
if currentDistanceToDirtyNode < distanceToSquare:
distanceToSquare = currentDistanceToDirtyNode
return 2 * (distanceToSquare * numDirtySquares + 1) + sum( \
(numDirtySquares - x) * 4 + 1 for x in range(0, numDirtySquares + 1))
def heuristic2(self, state):
for currentState in argsWith0:
endX = (currentState - 1) // 3
endY = (currentState - 1) % 3
newSquare = state[currentState]
currentDistanceToDirtyNode = abs(endX - startX) + abs(endY - startY)
if currentDistanceToDirtyNode < distanceToSquare:
distanceToSquare = currentDistanceToDirtyNode
return 2 * (distanceToSquare * numDirtySquares + 1) + sum( \
(numDirtySquares - x) * 4 + 1 for x in range(0, numDirtySquares + 1))
def heuristic3(self, state):
return heuristic2(state) + 2 * \
(heuristic2(state).distanceToSquare * heuristic2(state).numDirtySquares + 1)
【问题讨论】:
-
似乎两个函数都是相同的,如果只是返回不同,然后编写一个具有不同条件的函数。
-
这段代码能运行吗?
distanceToSquare在使用之前从未分配过