我还需要3个数据字段和一个信息组。G=当前距离,F=总值(启发式值+G),P=父级。如何构建一个包含所有这些内容的结构?
您应该使用一个类来表示一个构造:
class Formation(object):
"""A formation of camels."""
def __init__(self, camels, parent):
self.camels = camels
self.current_distance = 0
self.parent = parent
@property
def total_distance(self):
"""The total distance."""
return self.current_distance + self.heuristic
这个
@property
事物(称为
装饰工
)修改以下函数,使其看起来像类的属性。这就是为什么Python不使用显式访问器方法(例如
GetDistance()
和
SetDistance
);不要使所有属性看起来像方法,而是根据需要使方法看起来像属性。所以,要得到一个队形的总距离,你只要说
theFormation.total_distance
没有
()
之后。
我不熟悉您试图解决的问题,但我对您的代码有一些意见:
def solution(formation):
return len([i for i in formation[formation.index(fCamel) + 1:] if i == bCamel]) == 0
这实际上是作为标准循环更好地实现的。将其作为
Formation
班级:
@property
def solution(self):
for camel in self.camels[self.camels.index(fCamel) + 1:]:
if camel == bCamel:
return False
return True
创建列表毫无意义(
len()
不会在发电机上操作)如果你只是在清点物品。这也可以成为一种财产。
关于
heuristic
你不需要
else: pass
,您不需要分号,请每行执行一个分配:
@property
def heuristic(self):
fCamels = 0
score = 0
for camel in self.camels:
if camel == fCamel:
fCamels += 1
elif camel == bCamel:
score += fCamels
return score
对
getneighbors
. 在
genn
,
list(...)
不会复制列表,它只会获取给定的内容并从中列出一个列表。如果它的参数已经是一个列表,那么它什么也不做并返回输入。如果你想复印一份,你就得做
from copy import copy
然后使用
copy
功能。(还有一个
deep_copy
功能在
复制
模块。):
def copy_swapping_camels(self, i, j):
newCamels = copy(self.camels)
newCamels[i], newCamels[j] = newCamels[j], newCamels[i]
return Formation(newCamels, self)
def get_neighbors(self):
igap = self.camels.index(gap)
result = [[]]
if igap > 0:
result.append(self.copy_swapping_camels(igap, igap - 1))
if igap > 1:
result.append(self.copy_swapping_camels(igap, igap - 2))
if igap < len(self.camels) - 1:
result.append(self.copy_swapping_camels(igap, igap + 1))
if igap < len(self.camels) - 2:
result.append(self.copy_swapping_camels(igap, igap + 2))
return result
在这里,在一行上做两个分配是可以的,因为这是一个交换(分配是相互关联的)。