Jan-08-2024, 01:28 PM
I am writing a linear search algorithm. I've got the main logic under my belt but it's the string representation that I haven't got right. Below is my script and output in my REPL. When I try to search (I call the method
What can you people tell me about what is wrong with my
Code:
seek
) for an integer within a list of intergers, the item I test is clearly present but my output shows: "False" as if it is not present. What can you people tell me about what is wrong with my
__str__
and what might you people recommend I use instead? Thanks.Code:
class LinearSearch: # This class accepts an array and an item def __init__(self, entered_list=None, item=None): self.entered_list = entered_list self.item = item def seek(self, item): # Loop through the array and check if the current array element is equal to the item for index in self.entered_list: if index == item: # If it is True, return the index at which the element is found return index # If the item is never found, return -1 return False def __str__(self): result = self.seek(self.item) if result: return str(result) else: return "Not Present"Here is the REPL inputs and outputs:
$ python Python 3.11.6 (main, Nov 14 2023, 09:36:21) [GCC 13.2.1 20230801] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from linear import LinearSearch >>> list_obj = [1,2,4,5,7,12,256] >>> item = 7 >>> item_exists = LinearSearch(list_obj,item) >>> item_exists <linear.LinearSearch object at 0x7ff5338add50> >>> item_exists.seek(7) False >>> item_exists.seek(256) False >>>