我有一个“Node”类,它以x和y为参数。类方法计算不同的值。我有这个类的多个实例,称为“节点”。我想要的是找到具有最低“fcost”的节点,并获得该节点的x和y坐标。
我不知道如何解决这个问题,所以如果你能帮助我,我将不胜感激。
class Node():
# Node class
def __init__(self, y, x):
self.y = y
self.x = x
def gcost(self):
return self.x + self.y
def hcost(self):
return self.x * self.y
def fcost(self):
return self.gcost() + self.hcost() # method that indicates
# which node to choose
node1 = Node(5,5)
node2 = Node(2,2)
nodes = [node1, node2] # I actually don't know if I should create a
# list of nodes so please tell me if I should
# not
### CODE TO SOLVE THE PROBLEM ###
在这种情况下,node1和node2之间的最低fcost是node2的fcost所以我希望输出为:(2,2)
或[2,2]
无论是列表还是元组,无论哪种方式都可以。
你应该使用min()
函数。您可以以不同的方式使用它,但在这种情况下,我认为最简单的解决方案是使用lambda函数 - 这是在python中编写和定义函数的较短方法。您可以阅读有关min()
函数here的更多信息,以及有关lambda函数here的更多信息。
无论如何,这段代码应该可以正常工作:
class Node():
# Node class
def __init__(self, y, x):
self.y = y
self.x = x
def gcost(self):
return self.x + self.y
def hcost(self):
return self.x * self.y
def fcost(self):
return self.gcost() + self.hcost()
node1 = Node(5,5)
node2 = Node(2,2)
nodes = [node1, node2]
needed_node = min(nodes, key=lambda x:x.fcost())
needed_list = [needed_node.x, needed_node.y] # in case you want the result as a list
needed_tuple = (needed_node.x, needed_node.y) # in case you want the result as a tuple
使用min(list, key=...)
。
min_node = min(nodes, key=lambda n:n.fcost())
print(min_node, min_node.fcost(), min_node.x, min_node.y)
key
必须是功能名称。
min
将使用它来获得它将比较的价值以找到最小值。