python 基本演算法

來源:互聯網
上載者:User

標籤:python演算法

一.無序表尋找def sequential_search(lis, key):    for i in lis:        if i == key:            return lis.index(i)        else:            continue    else:        return Falseif __name__ == '__main__':    LIST = [1, 5, 8, 123, 22, 54, 7, 99, 300, 222]    result = sequential_search(LIST,1231)    print(result)    二.有序表尋找1.二分尋找(Binary Search)def binary_search(lis,key):    low = 0    high = len(lis) - 1    time = 0    while low < high:        time += 1        mid = int((low + high)/2)        if key < lis[mid]:            high = mid - 1        elif key > lis[mid]:            low = mid + 1        else:            print("times: %s" % time)            return mid    print("times: %s" % time)    return Falseif __name__ == '__main__':    LIST = [1, 5, 7, 8, 22, 54, 99, 123, 200, 222, 444]    result = binary_search(LIST,99)    print(result)    2. 插值尋找二分尋找法雖然已經很不錯了,但還有可以最佳化的地方。有的時候,對半過濾還不夠狠,要是每次都排除十分之九的資料豈不是更好?選擇這個值就是關鍵問題,插值的意義就是:以更快的速度進行縮減。插值的核心就是使用公式:value = (key – list[low])/(list[high] – list[low])用這個value來代替二分尋找中的1/2def binary_search(lis, key):    low = 0    high = len(lis) - 1    time = 0    while low < high:        time += 1        # 計算mid值是插值演算法的核心代碼        mid = low + int((high - low) * (key - lis[low]) / (lis[high] - lis[low]))        print("mid=%s, low=%s, high=%s" % (mid, low, high))        if key < lis[mid]:            high = mid - 1        elif key > lis[mid]:            low = mid + 1        else:            # 列印尋找的次數            print("times: %s" % time)            return mid    print("times: %s" % time)    return False


python 基本演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.