FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/half_search.py at master · chencunwei/algorithm · GitHub
chencunwei
algorithm
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
half_search.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
37 lines (31 loc) · 927 Bytes
Breadcrumbs
algorithm
/
half_search.py
Copy path
File metadata and controls
37 lines (31 loc) · 927 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#! /usr/bin/env python
#coding:utf-8
#折半查找某个元素在list中的位置
def
half_search
(
lst
,
value
,
left
,
right
):
length
=
len
(
lst
)
while
left
<
right
:
middle
=
(
right
-
left
)
/
2
if
lst
[
middle
]
>
value
:
right
=
middle
-
1
elif
lst
[
middle
]
<
value
:
left
=
middle
+
1
else
:
return
middle
#如果该元素在list中不止一个,可以用下面方法找出所有位置分布
def
find_value_location
(
lst
,
value
):
result
=
[
i
for
i
in
range
(
len
(
lst
))
if
value
==
lst
[
i
]]
return
result
if
__name__
==
"__main__"
:
lst
=
sorted
([
2
,
4
,
4
,
5
,
9
])
length
=
len
(
lst
)
left
=
0
right
=
length
-
1
value
=
4
result
=
half_search
(
lst
,
value
,
left
,
right
)
if
result
:
print
result
else
:
print
"There is no the value that you want to search."
lst2
=
[
2
,
4
,
5
,
4
,
2
]
result2
=
find_value_location
(
lst2
,
4
)
print
result2
Back
|
FazBrowse Home
|
New Git URL