Let's consider the problem of finding the closest restaurant to our current GPS coordinates. Let's assume the current position is given as an (x,y) coordinate, and that we have coordinates of various restaurants stored in a list of positions.

In [1]:
import math
def closest(position, positions):
    x0, y0 = position
    dbest, ibest = None, None
    for i, (x,y) in enumerate(positions):
        # compute the Euclidean distance
        dist = ((x - x0) ** 2) + ((y - y0) ** 2)
        dist = math.sqrt(dist)
        if dbest is None or dist < dbest:
            dbest, ibest = dist, i
    return ibest

First we'll create a random list of coordinates. To make it realistic, let's create 10 M coordinates.

In [2]:
import random
In [3]:
positions = [(random.random(), random.random()) for i in xrange(10000000)]

Let's see how long it takes to compute the closest distance to our current coordinates: (0.5,0.5)

In [4]:
%timeit closest((.5, .5), positions)
1 loop, best of 3: 6.03 s per loop

Now let's try doing something similar with Numpy. Numpy arrays are much more efficient, and so is the method for random number generation.

In [5]:
import numpy as np
In [6]:
positions = np.random.rand(10000000, 2)
In [7]:
positions.ndim, positions.shape
(2, (10000000L, 2L))
In [8]:

Now let's again compute the distances to our position (0.5, 0.5)

In [9]:
x, y = positions[:,0], positions[:,1] # x and y contain the 1st and 2nd cols, respectively.
In [10]:
distances = np.sqrt( (x - 0.5)**2 + (y - 0.5)**2 )
In [11]:
%timeit exec(In[10])
1 loop, best of 3: 223 ms per loop