我有两个函数,除了return语句之外,它们是完全相同的。如何使用一个函数中的变量来缩短第二个函数?
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)发布于 2019-09-30 11:55:16
让我们来看看所谓的“全局”变量:https://www.programiz.com/python-programming/global-local-nonlocal-variables
从本质上讲,定义在函数外部的变量将允许所有函数能够访问和操作该变量,而定义在函数内部的变量是“局部”的,只能在该特定函数内使用。
发布于 2019-09-30 12:13:36
不能,你不能直接访问函数中变量的状态。如果您想像这样访问变量
heuristic2(state).distanceToSquare然后,您必须让heuristic2返回一个具有distanceToSquare属性的类
class Heuristic():
def __init__(self, val, dis, dirt):
self.value = value
self.distanceToSquare = dis
self.numDirtySquares = dirt并调整return语句以将每个值作为类的一部分返回
v = 2 * (distanceToSquare * numDirtySquares + 1) + sum( \
(numDirtySquares - x) * 4 + 1 for x in range(0, numDirtySquares + 1))
return Heuristic(v, distanceToSquare, numDirtySquares)def heuristic3(self, state):
h2 = heuristic2(state)
return h2.value + 2 * (h2.distanceToSquare * h2.numDirtySquares + 1)https://stackoverflow.com/questions/58161292
复制相似问题