Performance improvement goodies
Let's spend some time discussing miscellaneous tips and tricks that help improve the runtime performance of the code. You can still apply a few of these techniques to the Gold Hunt problem, but let's just use generic examples to explain these concepts.
Tip
All the illustrations in this section can be found in the supporting file, misc_performance.py
. To compare the performance, we will use the timeit
module that was discussed in Chapter 7, Performance – Identifying Bottlenecks (refer to the Measuring runtime of small code snippets section). See also the timeit
documentation, https://docs.python.org/3/library/timeit.html.
List comprehension
List comprehension
is a compact way of creating a Python list
. It is often used to replace the nested for
loops or the map
and filter
functionality. Besides being compact, it is also efficient compared to, for instance, an equivalent for
loop. The basic syntax is as follows:
a = [i*i for i in range(5)]
This creates a list with...