FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
programmingWithPythonCode/loops/while_loop_search.py at main · mlecjm/programmingWithPythonCode · GitHub
mlecjm
programmingWithPythonCode
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
programmingWithPythonCode
/
loops
/
while_loop_search.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
19 lines (17 loc) · 1.09 KB
Breadcrumbs
programmingWithPythonCode
/
loops
/
while_loop_search.py
Copy path
File metadata and controls
19 lines (17 loc) · 1.09 KB
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
"""Using a `while` loop to implement Binary Search."""
data
:
str
=
"abdfjlmoqsuvwyz"
# A string of sorted characters.
for
search
in
[
"a"
,
"c"
,
"o"
,
"p"
,
"w"
,
"z"
]:
# Search six characters.
upper
:
int
=
len
(
data
)
# *Exclusive* upper index.
lower
:
int
=
0
# Lowest possible index = 0 (inclusive).
while
lower
<
upper
:
# Repeat until lower >= upper.
mid
:
int
=
(
lower
+
upper
)
//
2
# Works ONLY in Python 3 :-).
mid_str
:
str
=
data
[
mid
]
# Get the character at index mid.
if
mid_str
<
search
:
# If mid_str < search, then clearly...
lower
=
mid
+
1
# ...the index of search must be < mid.
elif
mid_str
>
search
:
# If mid_str > search, then clearly...
upper
=
mid
# ...the index of search must be > mid.
else
:
# If neither (mid_str < search) nor (mid_str > search)...
print
(
f"Found
{
search
!r
}
at index
{
mid
}
in
{
data
!r
}
."
)
break
# Exit while loop and skip over while loop's else.
else
:
# executed if the while condition is False; not after break
print
(
f"Did not find
{
search
!r
}
in
{
data
!r
}
."
)
Back
|
FazBrowse Home
|
New Git URL