I need to have 3 more data fields along with a formation. g = current distance, f = total value (heuristic value + g), p = parent. How to make a structure including all these?
You should use a class to represent a formation:
"""A formation of camels."""
def __init__(self, camels, parent):
self.camels = camels
self.current_distance = 0
self.parent = parent
"""The total distance."""
return self.current_distance + self.heuristic
@property thing (called a decorator) modifies the following function so it looks like a property of the class. This is why Python doesn't bother with explicit accessor methods (i.e. things like
SetDistance); instead of making all properties look like methods, you make methods look like properties as needed. So, to get a formation's total distance, you just say
() after it.
I'm not familiar with the problem you're trying to solve, but I have a few comments on your code:
return len([i for i in formation[formation.index(fCamel) + 1:] if i == bCamel]) == 0
This is actually better implemented as a standard loop. Writing it as a another property of the
for camel in self.camels[self.camels.index(fCamel) + 1:]:
if camel == bCamel:
No point creating a list (
len() won't operate on a generator) if you're just counting items. This can also be made a property.
heuristic, you don't need
else: pass, you don't ned semicolons, and please do one assignment per line:
fCamels = 0
score = 0
for camel in self.camels:
if camel == fCamel:
fCamels += 1
elif camel == bCamel:
score += fCamels
list(...) doesn't copy the list, it just takes whatever it's given and makes a list out of it. If its parameter is already a list, then it does nothing and returns the input. If you want to make a copy, you'll need to do
from copy import copy and then use the
copy function. (There's also a
deep_copy function in the
def copy_swapping_camels(self, i, j):
newCamels = copy(self.camels)
newCamels[i], newCamels[j] = newCamels[j], newCamels[i]
return Formation(newCamels, 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))
Here, doing two assignments on one line is okay because it's a swap (the assignments are related to each other).