I have tried searching online for this, but unfortunately have not been able to come up with a solution so far, so I was hoping someone might be able to help me. My basic question is how can I check whether an object is already in a list?
I am currently working on a Rubik's Cube solver, and have created a class called MyCube, where each object has 4 properties:
def __init__(self, cp=None, co=None, ep=None, eo=None):
There are a number of methods for changing the properties, and I have also created methods for __eq__ and __ne__ as follows:
def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
def __ne__(self, other):
return not self.__eq__(other)
I have a list of cubes MyMoveCube = [MyCube() for i in range(18)] and each cube goes through various different transformations. I then have another cube MyNewCube and I want to check whether it is already in MyMoveCube and if not to add it to the list.
I have tried the following, but I find that this gets very slow very quickly as the size of MyMoveCube increases:
for current_move in MyMoveCube:
if current_move == MyNewCube:
break
MyMoveCube.append(MyNewCube)
My question is, is there a better way to do this without looping through it each time?
if MyNewCube in MyMoveCube:...? This will first check the identity and then will call__eq__if required.