#!/usr/bin/env python # coding: utf-8 # #### 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 range(10000000)] # In[4]: for i in range(0, 10): print(positions[i]) # #### Let's see how long it takes to compute the closest distance to our current coordinates: (0.5,0.5) # In[5]: get_ipython().run_line_magic('timeit', 'p = closest((.5, .5), positions)') # In[6]: print( positions[closest((.5, .5), positions)] ) # #### 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[7]: import numpy as np # In[8]: positions = np.array(positions) # In[9]: positions.shape # In[10]: print(positions[:10,:]) # #### Now let's again compute the distances to our position (0.5, 0.5) # In[11]: x, y = positions[:,0], positions[:,1] # x and y are arrays containing the 1st and 2nd cols, respectively. # In[12]: distances = np.sqrt((x - 0.5)**2 + (y - 0.5)**2) closest_dist = distances.min() # In[13]: get_ipython().run_cell_magic('timeit', '', 'distances = np.sqrt( (x - 0.5)**2 + (y - 0.5)**2 )\n') # In[14]: get_ipython().run_cell_magic('timeit', '', 'closest_dist = distances.min()\n') # In[ ]: