Skip to content

Commit 24d3715

Browse files
JostMigendaRobadob
authored andcommitted
improve clarity of "searching an element in a list" example
1 parent 2dfaaab commit 24d3715

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

episodes/optimisation-using-python.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ It is often best to tell the interpreter/library at a high level *what you want*
104104
## Example: Searching an element in a list
105105

106106
A simple example of this is performing a linear search on a list. (Though as we’ll see in the next section, this isn't the most efficient approach!)
107-
In the following example, we create a list of 2500 integers in the (inclusive-exclusive) range `[0, 5000)`.
108-
The goal is to search for all even numbers within that range.
107+
In the following example, we create a list of 2500 random integers in the (inclusive-exclusive) range `[0, 5000)`.
108+
The goal is to count how many even numbers are in the list.
109109

110110
The function `manualSearch()` manually iterates through the list (`ls`) and checks each individual item using Python code. On the other hand, `operatorSearch()` uses the `in` operator to perform each search, which allows CPython to implement the inner loop in its C back-end.
111111

@@ -118,18 +118,18 @@ M = 2 # N*M == Range over which the elements span
118118
ls = [random.randint(0, int(N*M)) for i in range(N)]
119119

120120
def manualSearch():
121-
ct = 0
122-
for i in range(0, int(N*M), M):
123-
for j in range(0, len(ls)):
124-
if ls[j] == i:
125-
ct += 1
121+
count = 0
122+
for even_number in range(0, int(N*M), M):
123+
for i in range(0, len(ls)):
124+
if ls[i] == even_number:
125+
count += 1
126126
break
127127

128128
def operatorSearch():
129-
ct = 0
130-
for i in range(0, int(N*M), M):
131-
if i in ls:
132-
ct += 1
129+
count = 0
130+
for even_number in range(0, int(N*M), M):
131+
if even_number in ls:
132+
count += 1
133133

134134
repeats = 1000
135135
print(f"manualSearch: {timeit(manualSearch, number=repeats):.2f}ms")

0 commit comments

Comments
 (0)