Skip to content

Commit 90bfbca

Browse files
committed
查找元素位置及分半查询
1 parent adce1c1 commit 90bfbca

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

half_search.md

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#问题
2+
3+
查找某个值在list中的位置
4+
5+
#解决思路
6+
7+
可以用折半查询的方法解决此问题。
8+
9+
#解决(Python)
10+
11+
#! /usr/bin/env python
12+
#coding:utf-8
13+
14+
#折半查找某个元素在list中的位置
15+
16+
def half_search(lst,value,left,right):
17+
length = len(lst)
18+
while left<right:
19+
middle = (right-left)/2
20+
if lst[middle]>value:
21+
right = middle-1
22+
elif lst[middle]<value:
23+
left = middle+1
24+
else:
25+
return middle
26+
27+
if __name__=="__main__":
28+
lst=sorted([2,4,5,9])    #折半算法中list要进行排序
29+
length = len(lst)
30+
left = 0
31+
right = length-1
32+
value =4
33+
result = half_search(lst,value,left,right)
34+
if result:
35+
print result
36+
else:
37+
print "There is no the value that you want to search."
38+
39+
#再思考
40+
41+
对于上面的折半方法,在python中,可以通过一个函数实现
42+
43+
lst = sorted([2,4,5,9])    #这里进行排序,主要是为了得到与上面方法一样的结果。事实上,list.index()可以针对任何list操作,不一定非要排序
44+
result = lst.index(4)
45+
46+
此外,如果遇到list中有多个相同的元素,应该如何将这些元素的位置都查询出来呢?下面的方法是用python实现。
47+
48+
def find_value_location(lst,value):
49+
result = [i for i in range(len(lst)) if value==lst[i]]
50+
return result
51+
52+
##qiwsir#gmail.com

half_search.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#! /usr/bin/env python
2+
#coding:utf-8
3+
4+
#折半查找某个元素在list中的位置
5+
6+
def half_search(lst,value,left,right):
7+
length = len(lst)
8+
while left<right:
9+
middle = (right-left)/2
10+
if lst[middle]>value:
11+
right = middle-1
12+
elif lst[middle]<value:
13+
left = middle+1
14+
else:
15+
return middle
16+
17+
#如果该元素在list中不止一个,可以用下面方法找出所有位置分布
18+
19+
def find_value_location(lst,value):
20+
result = [i for i in range(len(lst)) if value==lst[i]]
21+
return result
22+
23+
24+
if __name__=="__main__":
25+
lst=sorted([2,4,4,5,9])
26+
length = len(lst)
27+
left = 0
28+
right = length-1
29+
value =4
30+
result = half_search(lst,value,left,right)
31+
if result:
32+
print result
33+
else:
34+
print "There is no the value that you want to search."
35+
lst2=[2,4,5,4,2]
36+
result2 = find_value_location(lst2,4)
37+
print result2

0 commit comments

Comments
 (0)