Program for time Comparsion difference between Python Lists and Numpy Arrays



Creation time for adding  two python list is the order of 500 compared to the adding two numpy array. 

Time metric in seconds 

Creation time for Python List : 0.310 

Creation time for Numpy Array: 0.002



import time
import numpy as np
size = 100000

def python_method():
    t1 = time.time()
    X = range(size)
    Y = range(size)
    Z = [X[i] + Y[i] for i in range(len(X)) ]
    return time.time() - t1

def numpy_method():
    t1 = time.time()
    X = np.arange(size)
    Y = np.arange(size)
    Z = X + Y
    return time.time() - t1

t1 = python_method()
t2 = numpy_method()
print("Python",t1,"Numpy",t2)


Python program to find distance measure - Hamming ,Euclidean , Manhattan, Minkowski

# Calculating distance between bit strings

# Hamming Distance
def hamming_distance(a, b):
return sum(abs(e1 - e2) for e1, e2 in zip(a, b)) / len(a)
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = hamming_distance(r1, r2)
print(dist)

#Euclidean Distance
from math import sqrt
def euclidean_distance(a, b):
return sqrt(sum((e1-e2)**2 for e1, e2 in zip(a,b)))
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = euclidean_distance(r1, r2)
print(dist)

#Manhattan Distance
from math import sqrt
def manhattan_distance(a, b):
return sum(abs(e1-e2) for e1, e2 in zip(a,b))
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = manhattan_distance(r1, r2)
print(dist)

#Minkowski Distance
from math import sqrt
def minkowski_distance(a, b, p):
return sum(abs(e1-e2)**p for e1, e2 in zip(a,b))**(1/p)
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = minkowski_distance(r1, r2, 1) #  p=1: Manhattan distance.
print(dist)
dist = minkowski_distance(r1, r2, 2) #  p=2: Euclidean distance.
print(dist)