Skip to content

Commit 4959522

Browse files
committed
OR updates
1 parent 6a85993 commit 4959522

File tree

7 files changed

+1319
-52
lines changed

7 files changed

+1319
-52
lines changed

python-first/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
# How to Find the First Match from an Iterable in Python
22

33
The code samples and supporting materials for the corresponding tutorial on Real Python.
4+
5+
Country data obtained from https://github.com/samayo/country-json

python-first/chart.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,38 @@
22

33
import matplotlib.pyplot as plt
44

5-
from test_cases import build_list
5+
from test_fixtures import build_list
66

77
TIMEIT_TIMES = 100_000
88
LIST_SIZE = 500
99
POSITION_INCREMENT = 10
1010

1111
looping_times = []
1212
generator_times = []
13+
in_times = []
1314
positions = []
1415

16+
17+
def find_match_loop(list_to_search, item_to_find):
18+
for val in list_to_search:
19+
if val == item_to_find:
20+
return val
21+
return None
22+
23+
24+
def find_match_gen(list_to_search, item_to_find):
25+
return next((val for val in list_to_search if val == item_to_find), None)
26+
27+
28+
def find_match_in(list_to_search, item_to_find):
29+
if item_to_find in list_to_search:
30+
return item_to_find
31+
32+
1533
for position in range(0, LIST_SIZE, POSITION_INCREMENT):
1634
print(
1735
f"Progress {position/LIST_SIZE:.0%}",
18-
end=f"{3 * ' '}\r", # Clear previous characters and reset cursor
36+
end=f"{3 * ' '}\r", # Clear previous characters and resets cursor
1937
)
2038

2139
positions.append(position)
@@ -26,16 +44,21 @@
2644

2745
looping_times.append(
2846
timeit(
29-
"find_match_loop(list_to_search, 'Real Python', None)",
30-
setup="from looping import find_match_loop",
47+
"find_match_loop(list_to_search, 'Real Python')",
3148
globals=globals(),
3249
number=TIMEIT_TIMES,
3350
)
3451
)
3552
generator_times.append(
3653
timeit(
37-
"find_match_gen(list_to_search, 'Real Python', None)",
38-
setup="from generator import find_match_gen",
54+
"find_match_gen(list_to_search, 'Real Python')",
55+
globals=globals(),
56+
number=TIMEIT_TIMES,
57+
)
58+
)
59+
in_times.append(
60+
timeit(
61+
"find_match_in(list_to_search, 'Real Python')",
3962
globals=globals(),
4063
number=TIMEIT_TIMES,
4164
)
@@ -47,6 +70,7 @@
4770

4871
plot = ax.plot(positions, looping_times, label="loop")
4972
plot = ax.plot(positions, generator_times, label="generator")
73+
plot = ax.plot(positions, in_times, label="in")
5074

5175
plt.xlim([0, LIST_SIZE])
5276
plt.xlabel("Position of element to be found")

0 commit comments

Comments
 (0)