python 3.x - Why does my binary search use so many comparisons? -
here code:
def binary_search(sortedlist,target,comparisons): start = 0 end = len(sortedlist) - 1 while(end - start >= 0): mid = (start + end)//2 comparisons += 2 if(target < sortedlist[mid]): comparisons -= 1 end = mid - 1 elif(target > sortedlist[mid]): start = mid + 1 else: return target, comparisons return false, comparisons
it same every other post on here binary searching reason uses way many comparisons.
here code after fixed myself
from classes import genelist ## uncomment following line able make own testing genes # classes import gene, genome def binary_search(sortedlist, target, comparisons): reducedlist = sortedlist while len(reducedlist) > 1: mid = len(reducedlist) // 2 comparisons += 1 if target < reducedlist[mid]: reducedlist = reducedlist[:mid] else: reducedlist = reducedlist[mid:] comparisons += 1 if reducedlist[0] == target: return reducedlist[0], comparisons else: return false, comparisons def genetic_similarity_binary(first_genome, second_genome): """ function takes 2 genome objects, , returns genelist , integer. genelist of genes common between first_genome , second_genome, while integer how many comparisons took find similar genes. hint: might pay define helper function. """ comparisons = 0 similar_list = genelist() target in first_genome: result, comparisons = binary_search(second_genome, target, comparisons) if result: similar_list.append(result) return similar_list, comparisons
you dont have middle check
for optimisation purposes, should check termination condition first. try way,
def binary_search(sortedlist,target,comparisons): start = 0 end = len(sortedlist) - 1 while(end - start >= 0): mid = (start + end)//2 comparisons += 2 if(target == sortedlist[mid]): comparisons -= 1 return target, comparisons elif(target > sortedlist[mid]): start = mid + 1 else: end = mid - 1 return false, comparisons
as upon execution of binary_search([1,2,3,4,5,6,7,8,9,10],9,0)
for code gives outcome (9, 6)
, above mentioned changes give (9, 5)
Comments
Post a Comment