Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
Administrator
/
level3-lesson16-diy2
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
8dd4f546
authored
Apr 16, 2021
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
adaf6f8a
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
57 additions
and
8 deletions
diy.py
diy2.py
my_search.py
diy.py
0 → 100644
View file @
8dd4f546
# 什么都没有输出,说明不在列表里
bingo_num
=
20
# 要查找的数:20
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
]
low
=
0
high
=
len
(
num_list
)
-
1
while
low
<=
high
:
mid
=
(
low
+
high
)
//
2
guess_num
=
num_list
[
mid
]
if
guess_num
==
bingo_num
:
print
(
'找到了,他在列表里的索引是:'
,
mid
)
break
elif
guess_num
<
bingo_num
:
low
=
mid
+
1
else
:
high
=
mid
-
1
diy2.py
0 → 100644
View file @
8dd4f546
import
random
alist
=
[]
for
i
in
range
(
1
,
101
):
alist
.
append
(
i
)
num
=
random
.
choice
(
alist
)
def
search
(
alist
,
num
):
low
=
0
high
=
len
(
alist
)
-
1
while
low
<=
high
:
mid
=
(
low
+
high
)
//
2
guess_num
=
alist
[
mid
]
if
guess_num
==
num
:
return
mid
elif
guess_num
<
num
:
low
=
mid
+
1
else
:
high
=
mid
-
1
return
None
result
=
search
(
alist
,
num
)
print
(
'需要猜测的数字是:'
,
num
)
print
(
'猜测数字所在的索引是:'
,
result
)
\ No newline at end of file
my_search.py
View file @
8dd4f546
import
random
一、问题抽象化:这道题的要求是要找到哪个
target
?还是要找到第一个比
target
小(或小于等于)的元素?
还是第一个比
target
大(或大于等于)的元素?
alist
=
[]
for
i
in
range
(
1
,
101
):
alist
.
append
(
i
)
num
=
random
.
choice
(
alist
)
# 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置
def
binary_search
(
alist
,
num
):
\ No newline at end of file
二、如果当前
mid
指向的值等于
target
了之后,我应该怎么处理?是直接
return
?还是移动
left
或者
right
?
三、最后一次循环的时候(循环是以
left
<=
right
作为判断条件),
left
===
right
,那么这个时候,我
是移动
left
还是移动
right
,移动之后,是
left
指向的我想返回的结果,还是
right
?
四、没找到怎么办?
给定一个
n
个元素有序的(升序)整型数组
nums
和一个目标值
target
,
写一个函数搜索
nums
中的
target
,如果目标值存在返回下标,否则返回
-
1
。
\ 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