I want to implement a method that accepts a value as a parameter. The method will return True if the value passed as a parameter is found in the list and False if not. I have tried the following but I get an error of type AttributeError: int object is not iterable
What I have tried is the following:
def check(self, valor):
for nodo in self:
if nodo.value == valor:
return True
else:
return False
I also attach the class I created so you can see the existing attributes:
class LinkedList:
class Node:
def __init__(self, value, next_node = None):
self.value = value
self.next_node = next_node
def __init__(self):
self.__first = None
self.__len = 0
def __len__(self):
return self.__len
def __iter__(self):
self.__current = self.__first
return self
def __next__(self):
if self.__current != None:
result = self.__current.value
self.__current = self.__current.next_node
return result
else:
raise StopIteration
You have two problems with your code:
First, you implement the iterator protocol by:
That is, the iterator generated by your class iterates over the values of the nodes of the list, not over its nodes directly. Therefore the comparison should not be:
otherwise:
On the other hand,
else
he can't be there. If the first value is not the one sought, False is automatically returned, when it should only be returnedFalse
if after going through the entire list the value is not found.Therefore it should be:
After all the fuss, it really is all much simpler, just use the membership operator:
The same thing that caused your failure, the way you implement the iterator protocol, allows to use
in
directly.P.S.
if self.__current != None:
is not technically correct, the identity operator must be used withNone
,if self.__current is not None:
.