#### 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 :
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 :
import random

In :
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 :
%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 :
import numpy as np

In :
positions = np.random.rand(10000000, 2)

In :
positions.ndim, positions.shape

Out:
(2, (10000000L, 2L))
In :
positions.size

Out:
20000000

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

In :
x, y = positions[:,0], positions[:,1] # x and y contain the 1st and 2nd cols, respectively.

In :
distances = np.sqrt( (x - 0.5)**2 + (y - 0.5)**2 )

In :
%timeit exec(In)

1 loop, best of 3: 223 ms per loop

In [ ]: