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
4fd6b3b9
authored
Nov 26, 2022
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
b860994f
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
20 additions
and
29 deletions
binary_search.py
binary_search.py
View file @
4fd6b3b9
# 使用二分查找法,找出
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
]
low
=
0
low
=
0
high
=
len
(
num_list
)
-
1
high
=
len
(
num_list
)
-
1
while
True
:
while
True
:
mid
=
(
low
+
high
)
//
2
print
(
'输入Q退出程序!'
)
guess
=
num_list
[
mid
]
number
=
input
(
'请输入要寻找的数:'
)
if
guess
==
20
:
if
number
==
Q
:
print
(
'找到这个数了!'
)
print
(
str
(
mid
))
break
break
elif
guess
<
20
:
elif
number
!=
int
:
low
=
mid
+
1
else
:
high
=
mid
-
1
if
high
<=
low
:
print
(
'没有这个数!'
)
break
low
=
0
high
=
len
(
num_list
)
-
1
while
True
:
mid
=
(
low
+
high
)
//
2
guess
=
num_list
[
mid
]
if
guess
==
9
:
print
(
'找到这个数了!'
)
print
(
str
(
mid
))
break
break
elif
guess
<
9
:
low
=
mid
+
1
else
:
else
:
high
=
mid
-
1
while
True
:
if
high
<=
low
:
mid
=
(
low
+
high
)
//
2
print
(
'没有这个数!'
)
guess
=
num_list
[
mid
]
break
if
guess
==
int
(
number
):
\ No newline at end of file
print
(
'找到这个数了!'
)
print
(
'这个数在列表中的索引为'
+
str
(
mid
))
break
elif
guess
<
int
(
number
):
low
=
mid
+
1
else
:
high
=
mid
-
1
if
high
<=
low
:
print
(
'列表中没有这个数!'
)
break
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