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)

Counter using Tkinter GUI in Python

 import tkinter as tk

counter = 0
def counter_label(label):
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()

root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()

Generate random numbers with normal distribution

 1.Generate normal distribution data of Size 2 × 3

   from numpy import random
   x = random.normal(size=(23))

2. Generate normal distribution with mean 250 and standard deviation 10

    from numpy import random
    x = random.normal(loc=250, scale=10, size=(23))

Python Random Module

 import random

random.random() 

random.uniform(1, 10)

random.randint(1, 10)

random.randrange(0, 101, 2)

random.choice('abcdefghij') 

items = [1, 2, 3, 4, 5, 6, 7]

random.shuffle(items)

items

random.sample([1, 2, 3, 4, 5],  3)