python 数据结构--查找
Posted hqc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 数据结构--查找相关的知识,希望对你有一定的参考价值。
1 顺序查找O(n)
def sequential_search(a_list, item): pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos+1 return found test_list = [1, 2, 32, 8] print sequential_search(test_list, 3) print sequential_search(test_list, 32)
2 二分查找O(lgn)
def binary_search(a_list, item): first = 0 last = len(a_list)-1 found = False while first <= last and not found: midpoint = (first+last)//2 if a_list[midpoint] == item: found = True elif a_list[midpoint] < item: first = midpoint+1 else: last = midpoint-1 return found test_list = [1, 2, 3, 4, 5, 6] print binary_search(test_list, 3) print binary_search(test_list, 0)
3 哈希查找O(1)
概念:来自wikipedia
以上是关于python 数据结构--查找的主要内容,如果未能解决你的问题,请参考以下文章