Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
Administrator
/
level3-lesson16-diy1
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
f4a504e9
authored
May 16, 2021
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
b250abfe
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
23 additions
and
2 deletions
binary_search.py
binary_search.py
View file @
f4a504e9
import
random
# 使用二分查找法,找出9和20在列表里面的索引
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
]
\ No newline at end of file
num_list
=
[]
for
i
in
range
(
1
,
100
,
5
):
num_list
.
append
(
i
)
num
=
random
.
choice
(
num_list
)
def
binary_search
(
num_list
,
num
):
low
=
0
# 设置最低索引
high
=
len
(
num_list
)
-
1
# 设置最高索引
while
low
<=
high
:
# 无限循环条件 最低索引小于等于最高索引
mid
=
(
low
+
high
)
//
2
# 找到中间索引
guess
=
num_list
[
mid
]
# 找到你要猜测的数字
if
guess
==
num
:
# 判断猜测的数字等于你要查找的数字
return
mid
elif
guess
<
num
:
# 否则如果猜测的数字小于查找的数字
low
=
mid
+
1
# 最低索引移到中间索引的右边
else
:
# 否则
high
=
mid
-
1
# 最高索引移到中间索引的左边
return
None
result
=
binary_search
(
num_list
,
num
)
print
(
'我们要查找的数字是:'
,
num
)
print
(
'它在列表里面的索引是:'
,
result
)
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment