问题
I am new to python, and very much enthusiastic to learn algorithm. I have written sample code for Binary search, can any one suggest how can i achieve same result in more pythonic way (Optimize the code, or using Bisect if any way possible)?
def bee_search(alist, target):
sort_list = sorted(alist)
while len(sort_list) >= 1:
end = len(sort_list)
middle = int((0 + end)/2)
if target == sort_list[middle]:
print "Found it", str(sort_list[middle])
break
elif target > sort_list[middle]:
sort_list = sort_list[middle:]
elif target < sort_list[middle]:
sort_list = sort_list[:middle]
else:
return "Fount it", str(sort_list[middle])
else:
print "List is Empty"
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
bee_search(arr,15)
回答1:
Probably this answers part of your question. You don't really need to get the middle index, you can compare the maximum value in alist
with target
:
def bee_search(alist, target):
largest = max(alist)
if target == largest:
print "Found", target
elif target < largest:
print"Found", target
else: # target > largest
print("Not found")
This is okay when target == largest
and when target > largest
but not when target < largest
, yes this is a broken algorithm!
arr = [1,0,2,3, 10, 200, 5, 29, 10, 39, 109]
bee_search(arr, 30)
When run this is the output:Found 30
.
This problem applies to your algorithm too, a simple comparison cannot tell us definitely whether alist
has a reference for integer 30
. You may need to consider workarounds, don't give up.
来源:https://stackoverflow.com/questions/44858843/optimize-binary-search