Im trying to do binary search in python for different objects with the same attributes. I started with the code, but dont know why its not working. I want to be able to put any name (attribute) and if its in the list be able to see that the value is there, and if not just return False.
class Person:
def __init__(self, name,age):
self.name = name
self.age = age
def __lt__(self,other):
return self.name < other.name
def readfile(file):
person = []
with open(file, 'r') as f:
for i in f:
name, age = i.split('*')
person.append(Person(name,age))
return person
def binary_search(item_list, item):
names = []
first_position = 0
last_position = len(item_list) - 1
for i in item_list:
names.append(i.name) # attribute of object
names.sort() # sorting list
while first_position <= last_position:
mid_point = (first_position + last_position) // 2
if names[mid_point] == item:
return mid_point
else:
if names[mid_point] > item:
last_position = mid_point - 1
else:
first_position = mid_point + 1
return False
the_list = readfile('p.txt')
last_element = the_list[n-1]
binary_search(the_list,last_element)
source https://stackoverflow.com/questions/71198398/trying-to-use-binary-search-on-object-attribute
Comments
Post a Comment