标签:arc 频繁 有序列表 sea 二分查找 == highlight binary 速度
二分查找
二分查找又称折半查找 优点是比较次数少,查找速度快,平均性能好 缺点是要求待查表为有序表,且插入删除困难 折半查找方法适用于不经常变动而查找频繁的有序列表。
猜数字游戏
1、生成一个有序列表 2、用户猜测某个数字是否在列表中
代码:
#!/usr/bin/env python # -*- conding-utf8 -*- def binary_search(data_source, find_n): mid = int(len(data_source)/2) if mid >= 1: if data_source[mid] > find_n: # data in left print("data in left of [%s]" % data_source[mid]) print(data_source[:mid]) binary_search(data_source[:mid], find_n) elif data_source[mid] < find_n: # data in right print("data in right of [%s]" % data_source[mid]) print(data_source[mid:]) binary_search(data_source[mid:], find_n) elif data_source[mid] == find_n: print("found %s" % data_source[mid]) elif data_source[mid] == find_n: print("found %s" % data_source[mid]) else: print("not found") if __name__ == ‘__main__‘: data = list(range(1,100,3)) ret = input("请输入猜测的数字:") binary_search(data, int(ret))
运行结果:
请输入猜测的数字:50 data in right of [49] [49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97] data in left of [73] [49, 52, 55, 58, 61, 64, 67, 70] data in left of [61] [49, 52, 55, 58] data in left of [55] [49, 52] data in left of [52] [49] not found 请输入猜测的数字:1 data in left of [49] [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46] data in left of [25] [1, 4, 7, 10, 13, 16, 19, 22] data in left of [13] [1, 4, 7, 10] data in left of [7] [1, 4] data in left of [4] [1] found 1
标签:arc 频繁 有序列表 sea 二分查找 == highlight binary 速度
原文地址:http://www.cnblogs.com/python-gm/p/7685870.html