In: Computer Science
How can I do this in python ???
In order to create the Exam Result objects correctly, one must find
the student object and the subject object that the exam result
should refer to. The distributed code contains O (n) methods that
perform sequential searches to find them in the lists. Create new
implementations of oving7. find _student and oving7.find_ topic
that is more effective.
oving7. find _student:
def find _student (student no, student list):
for student in student list:
if
student.get_studentnumber () == studentnr:
return
student
return None
oving7.find_ topic:
def find _ topic (topic code, topic list):
for subject in subject list:
if topic.get_
topic code () == topic code:
return
topic
return None
Above Python codes take O(n) time as they are performing linear search operation, So in order to make them efficient, we can apply Binary Search-
Python Code for the above two functions using Binary Search is as follows-
#This function
will return the index of the found element i.e; student_list[idx]
will be the answer
def find _student(studentnr, student_list):
first = 0
last = len(student_list)-1
idx = -1
while (first <= last) and (idx == -1):
mid = (first+last)//2
if student_list[mid] == studentnr:
idx = mid
else:
if studentnr<student_list[mid]:
last = mid -1
else:
first = mid +1
return idx
#This function
will return the index of the found element i.e; topic_list[idx]
will be the answer
def find _ topic(topic_code, topic_list):
first = 0
last = len(topic_list)-1
idx = -1
while (first <= last) and (idx == -1):
mid = (first+last)//2
if topic_list[mid] == topic_code:
idx = mid
else:
if topic_code<topic_list[mid]:
last = mid -1
else:
first = mid +1
return idx