One final example
Before we finish off this chapter, let's go through one last example. We could write a function to generate a list of prime numbers up to a limit; we've already seen the code for this in Chapter 3, so let's make it a function and, to keep it interesting, let's optimize it a bit.
It turns out that we don't need to divide by all numbers from 2 to N-1 to decide whether a number, N, is prime. We can stop at √N (the square root of N). Moreover, we don't need to test the division for all numbers from 2 to √N, as we can just use the primes in that range. We leave it up to you to figure out why this works, if you're interested in the beauty of mathematics.
Let's see how the code changes:
# primes.py
from math import sqrt, ceil
def get_primes(n):
"""Calculate a list of primes up to n (included). """
primelist = []
for candidate in range(2, n + 1):
is_prime...