Hi, I am having trouble with this assignment. I would definitely like a lesson on how each statement works and why it works there. Here is the OrderedList Class.
class OrderedList:
def __init__(self, l):
self.n = l
self._step = 0
self._index = 0
self.items = list(range(1, l))
def binary_search(self, key, flag):
self.start = 0
# print(self.items)
self.n -= 1
while self.start <= self.n:
self._index = (self.start + self.n) // 2
# print("start = ",self.start,"end = ",self.n,"index =",self._index)
if self.items[self._index] == key:
print("Step #", (self._step + 1), " index ", self._index)
self._step += 1
return flag
if self.items[self._index] < key:
# print("greater than ")
self.start = self._index + 1
print("Step #", (self._step + 1), " index ", self._index)
self._step += 1
else:
# print("less than")
self.n = self._index - 1
print("Step #", (self._step + 1), " index ", self._index)
self._step += 1
def get_index(self):
return self._index
def get_step(self):
return self._step
n = 100
mylist = OrderedList(n)
key = 50
if mylist.binary_search(key, True):
print("Value " + str(key) + " at " + str(mylist.get_index()))
print("Obtained in " + str(mylist.get_step()) + " Steps")
4-(5pts)Complete the 5 statements in the following binary_search method (in the class OrderedList) that returns True if a given item is found in the list items, and False otherwise. It also keeps track of the number of binary search steps and records the value of the index if the item is found. Note: the argument com permits some printed comments if True.
def binary_search(self, x, com):
lower = 0
upper = self.n - l # l statement here.
while lower <= upper:
mid = lower + (upper - lower) // 2 # 2 statement here.
if com:
print("step #" + str(self._step) + " index " + str(mid))
if self.items[mid] == x: # 3 statement here.
print("Step #" + str(self._step + 1) + " index " + str(mid))
self._step += 1
return True
elif self.items[mid] < x:
lower = mid + 1 # 4 statement here.
else:
upper = mid - 1 # 5 statement here.