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
acec3ccc
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
2 changed files
with
44 additions
and
2 deletions
binary_search.py
demo1.py
binary_search.py
View file @
acec3ccc
import
random
# 使用二分查找法,找出9和20在列表里面的索引
# 使用二分查找法,找出9和20在列表里面的索引
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
]
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
,
34
,
56
,
65
,
67
,
78
,
90
]
\ No newline at end of file
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
)
demo1.py
0 → 100644
View file @
acec3ccc
import
random
# 使用二分查找法,找出9和20在列表里面的索引
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
]
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
if
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