Optimize Binary Search

天大地大妈咪最大 提交于 2019-12-12 04:22:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!