Added Dequeue in Python

This commit is contained in:
97arushisharma
2017-10-25 01:37:11 +05:30
commit 9bc80eac2d
105 changed files with 295341 additions and 0 deletions

View File

@ -0,0 +1,37 @@
import math
class Graph:
def __init__(self, N = 0): # a graph with Node 0,1,...,N-1
self.N = N
self.W = [[math.inf for j in range(0,N)] for i in range(0,N)] # adjacency matrix for weight
self.dp = [[math.inf for j in range(0,N)] for i in range(0,N)] # dp[i][j] stores minimum distance from i to j
def addEdge(self, u, v, w):
self.dp[u][v] = w;
def floyd_warshall(self):
for k in range(0,self.N):
for i in range(0,self.N):
for j in range(0,self.N):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])
def showMin(self, u, v):
return self.dp[u][v]
if __name__ == '__main__':
graph = Graph(5)
graph.addEdge(0,2,9)
graph.addEdge(0,4,10)
graph.addEdge(1,3,5)
graph.addEdge(2,3,7)
graph.addEdge(3,0,10)
graph.addEdge(3,1,2)
graph.addEdge(3,2,1)
graph.addEdge(3,4,6)
graph.addEdge(4,1,3)
graph.addEdge(4,2,4)
graph.addEdge(4,3,9)
graph.floyd_warshall()
graph.showMin(1,4)
graph.showMin(0,3)

View File

@ -0,0 +1,74 @@
"""
Author : Turfa Auliarachman
Date : October 12, 2016
This is a pure Python implementation of Dynamic Programming solution to the edit distance problem.
The problem is :
Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion, and substitution.
"""
class EditDistance:
"""
Use :
solver = EditDistance()
editDistanceResult = solver.solve(firstString, secondString)
"""
def __init__(self):
self.__prepare__()
def __prepare__(self, N = 0, M = 0):
self.dp = [[-1 for y in range(0,M)] for x in range(0,N)]
def __solveDP(self, x, y):
if (x==-1):
return y+1
elif (y==-1):
return x+1
elif (self.dp[x][y]>-1):
return self.dp[x][y]
else:
if (self.A[x]==self.B[y]):
self.dp[x][y] = self.__solveDP(x-1,y-1)
else:
self.dp[x][y] = 1+min(self.__solveDP(x,y-1), self.__solveDP(x-1,y), self.__solveDP(x-1,y-1))
return self.dp[x][y]
def solve(self, A, B):
if isinstance(A,bytes):
A = A.decode('ascii')
if isinstance(B,bytes):
B = B.decode('ascii')
self.A = str(A)
self.B = str(B)
self.__prepare__(len(A), len(B))
return self.__solveDP(len(A)-1, len(B)-1)
if __name__ == '__main__':
import sys
if sys.version_info.major < 3:
input_function = raw_input
else:
input_function = input
solver = EditDistance()
print("****************** Testing Edit Distance DP Algorithm ******************")
print()
print("Enter the first string: ", end="")
S1 = input_function()
print("Enter the second string: ", end="")
S2 = input_function()
print()
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
print()
print("*************** End of Testing Edit Distance DP Algorithm ***************")

View File

@ -0,0 +1,42 @@
"""
This program calculates the nth Fibonacci number in O(log(n)).
It's possible to calculate F(1000000) in less than a second.
"""
import sys
# returns F(n)
def fibonacci(n: int):
if n < 0:
raise ValueError("Negative arguments are not supported")
return _fib(n)[0]
# returns (F(n), F(n-1))
def _fib(n: int):
if n == 0:
# (F(0), F(1))
return (0, 1)
else:
# F(2n) = F(n)[2F(n+1) F(n)]
# F(2n+1) = F(n+1)^2+F(n)^2
a, b = _fib(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
if __name__ == "__main__":
args = sys.argv[1:]
if len(args) != 1:
print("Too few or too much parameters given.")
exit(1)
try:
n = int(args[0])
except ValueError:
print("Could not convert data to an integer.")
exit(1)
print("F(%d) = %d" % (n, fibonacci(n)))

View File

@ -0,0 +1,57 @@
"""
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem.
"""
class Fibonacci:
def __init__(self, N=None):
self.fib_array = []
if N:
N = int(N)
self.fib_array.append(0)
self.fib_array.append(1)
for i in range(2, N + 1):
self.fib_array.append(self.fib_array[i - 1] + self.fib_array[i - 2])
elif N == 0:
self.fib_array.append(0)
def get(self, sequence_no=None):
if sequence_no != None:
if sequence_no < len(self.fib_array):
return print(self.fib_array[:sequence_no + 1])
else:
print("Out of bound.")
else:
print("Please specify a value")
if __name__ == '__main__':
import sys
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
# otherwise 2.x's input builtin function is too "smart"
if sys.version_info.major < 3:
input_function = raw_input
else:
input_function = input
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
try:
N = eval(input())
fib = Fibonacci(N)
print(
"\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n")
while True:
print("Enter value: ", end=" ")
try:
i = eval(input())
if i < 0:
print("\n********* Good Bye!! ************\n")
break
fib.get(i)
except NameError:
print("\nInvalid input, please try again.")
except NameError:
print("\n********* Invalid input, good bye!! ************\n")

View File

@ -0,0 +1,141 @@
import tensorflow as tf
from random import choice, shuffle
from numpy import array
def TFKMeansCluster(vectors, noofclusters):
"""
K-Means Clustering using TensorFlow.
'vectors' should be a n*k 2-D NumPy array, where n is the number
of vectors of dimensionality k.
'noofclusters' should be an integer.
"""
noofclusters = int(noofclusters)
assert noofclusters < len(vectors)
#Find out the dimensionality
dim = len(vectors[0])
#Will help select random centroids from among the available vectors
vector_indices = list(range(len(vectors)))
shuffle(vector_indices)
#GRAPH OF COMPUTATION
#We initialize a new graph and set it as the default during each run
#of this algorithm. This ensures that as this function is called
#multiple times, the default graph doesn't keep getting crowded with
#unused ops and Variables from previous function calls.
graph = tf.Graph()
with graph.as_default():
#SESSION OF COMPUTATION
sess = tf.Session()
##CONSTRUCTING THE ELEMENTS OF COMPUTATION
##First lets ensure we have a Variable vector for each centroid,
##initialized to one of the vectors from the available data points
centroids = [tf.Variable((vectors[vector_indices[i]]))
for i in range(noofclusters)]
##These nodes will assign the centroid Variables the appropriate
##values
centroid_value = tf.placeholder("float64", [dim])
cent_assigns = []
for centroid in centroids:
cent_assigns.append(tf.assign(centroid, centroid_value))
##Variables for cluster assignments of individual vectors(initialized
##to 0 at first)
assignments = [tf.Variable(0) for i in range(len(vectors))]
##These nodes will assign an assignment Variable the appropriate
##value
assignment_value = tf.placeholder("int32")
cluster_assigns = []
for assignment in assignments:
cluster_assigns.append(tf.assign(assignment,
assignment_value))
##Now lets construct the node that will compute the mean
#The placeholder for the input
mean_input = tf.placeholder("float", [None, dim])
#The Node/op takes the input and computes a mean along the 0th
#dimension, i.e. the list of input vectors
mean_op = tf.reduce_mean(mean_input, 0)
##Node for computing Euclidean distances
#Placeholders for input
v1 = tf.placeholder("float", [dim])
v2 = tf.placeholder("float", [dim])
euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(
v1, v2), 2)))
##This node will figure out which cluster to assign a vector to,
##based on Euclidean distances of the vector from the centroids.
#Placeholder for input
centroid_distances = tf.placeholder("float", [noofclusters])
cluster_assignment = tf.argmin(centroid_distances, 0)
##INITIALIZING STATE VARIABLES
##This will help initialization of all Variables defined with respect
##to the graph. The Variable-initializer should be defined after
##all the Variables have been constructed, so that each of them
##will be included in the initialization.
init_op = tf.initialize_all_variables()
#Initialize all variables
sess.run(init_op)
##CLUSTERING ITERATIONS
#Now perform the Expectation-Maximization steps of K-Means clustering
#iterations. To keep things simple, we will only do a set number of
#iterations, instead of using a Stopping Criterion.
noofiterations = 100
for iteration_n in range(noofiterations):
##EXPECTATION STEP
##Based on the centroid locations till last iteration, compute
##the _expected_ centroid assignments.
#Iterate over each vector
for vector_n in range(len(vectors)):
vect = vectors[vector_n]
#Compute Euclidean distance between this vector and each
#centroid. Remember that this list cannot be named
#'centroid_distances', since that is the input to the
#cluster assignment node.
distances = [sess.run(euclid_dist, feed_dict={
v1: vect, v2: sess.run(centroid)})
for centroid in centroids]
#Now use the cluster assignment node, with the distances
#as the input
assignment = sess.run(cluster_assignment, feed_dict = {
centroid_distances: distances})
#Now assign the value to the appropriate state variable
sess.run(cluster_assigns[vector_n], feed_dict={
assignment_value: assignment})
##MAXIMIZATION STEP
#Based on the expected state computed from the Expectation Step,
#compute the locations of the centroids so as to maximize the
#overall objective of minimizing within-cluster Sum-of-Squares
for cluster_n in range(noofclusters):
#Collect all the vectors assigned to this cluster
assigned_vects = [vectors[i] for i in range(len(vectors))
if sess.run(assignments[i]) == cluster_n]
#Compute new centroid location
new_location = sess.run(mean_op, feed_dict={
mean_input: array(assigned_vects)})
#Assign value to appropriate variable
sess.run(cent_assigns[cluster_n], feed_dict={
centroid_value: new_location})
#Return centroids and assignments
centroids = sess.run(centroids)
assignments = sess.run(assignments)
return centroids, assignments

View File

@ -0,0 +1,14 @@
"""
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
"""
def knapsack(W, wt, val, n):
dp = [[0 for i in range(W+1)]for j in range(n+1)]
for i in range(1,n+1):
for w in range(1,W+1):
if(wt[i-1]<=w):
dp[i][w] = max(val[i-1]+dp[i-1][w-wt[i-1]],dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][w]

View File

@ -0,0 +1,48 @@
"""
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
Example:"abc", "abg" are subsequences of "abcdefgh".
"""
def LCS(x,y):
b=[[] for j in range(len(x)+1)]
c=[[] for i in range(len(x))]
for i in range(len(x)+1):
b[i].append(0)
for i in range(1,len(y)+1):
b[0].append(0)
for i in range(len(x)):
for j in range(len(y)):
if x[i]==y[j]:
b[i+1].append(b[i][j]+1)
c[i].append('/')
elif b[i][j+1]>=b[i+1][j]:
b[i+1].append(b[i][j+1])
c[i].append('|')
else :
b[i+1].append(b[i+1][j])
c[i].append('-')
return b,c
def print_lcs(x,c,n,m):
n,m=n-1,m-1
ans=[]
while n>=0 and m>=0:
if c[n][m]=='/':
ans.append(x[n])
n,m=n-1,m-1
elif c[n][m]=='|':
n=n-1
else:
m=m-1
ans=ans[::-1]
return ans
if __name__=='__main__':
x=['a','b','c','b','d','a','b']
y=['b','d','c','a','b','a']
b,c=LCS(x,y)
print('Given \nX : ',x)
print('Y : ',y)
print('LCS : ',print_lcs(x,c,len(x),len(y)))

View File

@ -0,0 +1,41 @@
'''
Author : Mehdi ALAOUI
This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence.
The problem is :
Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
'''
def longestSub(ARRAY): #This function is recursive
ARRAY_LENGTH = len(ARRAY)
if(ARRAY_LENGTH <= 1): #If the array contains only one element, we return it (it's the stop condition of recursion)
return ARRAY
#Else
PIVOT=ARRAY[0]
isFound=False
i=1
LONGEST_SUB=[]
while(not isFound and i<ARRAY_LENGTH):
if (ARRAY[i] < PIVOT):
isFound=True
TEMPORARY_ARRAY = [ element for element in ARRAY[i:] if element >= ARRAY[i] ]
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
LONGEST_SUB = TEMPORARY_ARRAY
else:
i+=1
TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= PIVOT ]
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
return TEMPORARY_ARRAY
else:
return LONGEST_SUB
#Some examples
print(longestSub([4,8,7,5,1,12,2,3,9]))
print(longestSub([9,8,7,6,5,7]))

View File

@ -0,0 +1,40 @@
#############################
# Author: Aravind Kashyap
# File: lis.py
# comments: This programme outputs the Longest Strictly Increasing Subsequence in O(NLogN)
# Where N is the Number of elements in the list
#############################
def CeilIndex(v,l,r,key):
while r-l > 1:
m = (l + r)/2
if v[m] >= key:
r = m
else:
l = m
return r
def LongestIncreasingSubsequenceLength(v):
if(len(v) == 0):
return 0
tail = [0]*len(v)
length = 1
tail[0] = v[0]
for i in range(1,len(v)):
if v[i] < tail[0]:
tail[0] = v[i]
elif v[i] > tail[length-1]:
tail[length] = v[i]
length += 1
else:
tail[CeilIndex(tail,-1,length-1,v[i])] = v[i]
return length
v = [2, 5, 3, 7, 11, 8, 10, 13, 6]
print LongestIncreasingSubsequenceLength(v)

View File

@ -0,0 +1,32 @@
'''
Auther : Yvonne
This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem.
The problem is :
Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array.
'''
class SubArray:
def __init__(self, arr):
# we need a list not a string, so do something to change the type
self.array = arr.split(',')
print("the input array is:", self.array)
def solve_sub_array(self):
rear = [int(self.array[0])]*len(self.array)
sum_value = [int(self.array[0])]*len(self.array)
for i in range(1, len(self.array)):
sum_value[i] = max(int(self.array[i]) + sum_value[i-1], int(self.array[i]))
rear[i] = max(sum_value[i], rear[i-1])
return rear[len(self.array)-1]
if __name__ == '__main__':
whole_array = input("please input some numbers:")
array = SubArray(whole_array)
re = array.solve_sub_array()
print("the results is:", re)

View File

@ -0,0 +1,59 @@
"""
author : Mayank Kumar Jha (mk9440)
"""
import time
import matplotlib.pyplot as plt
from random import randint
def find_max_sub_array(A,low,high):
if low==high:
return low,high,A[low]
else :
mid=(low+high)//2
left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
if left_sum>=right_sum and left_sum>=cross_sum:
return left_low,left_high,left_sum
elif right_sum>=left_sum and right_sum>=cross_sum :
return right_low,right_high,right_sum
else:
return cross_left,cross_right,cross_sum
def find_max_cross_sum(A,low,mid,high):
left_sum,max_left=-999999999,-1
right_sum,max_right=-999999999,-1
summ=0
for i in range(mid,low-1,-1):
summ+=A[i]
if summ > left_sum:
left_sum=summ
max_left=i
summ=0
for i in range(mid+1,high+1):
summ+=A[i]
if summ > right_sum:
right_sum=summ
max_right=i
return max_left,max_right,(left_sum+right_sum)
if __name__=='__main__':
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
tim=[]
for i in inputs:
li=[randint(1,i) for j in range(i)]
strt=time.time()
(find_max_sub_array(li,0,len(li)-1))
end=time.time()
tim.append(end-strt)
print("No of Inputs Time Taken")
for i in range(len(inputs)):
print(inputs[i],'\t\t',tim[i])
plt.plot(inputs,tim)
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
plt.show()

View File

@ -0,0 +1,28 @@
"""
Partition a set into two subsets such that the difference of subset sums is minimum
"""
def findMin(arr):
n = len(arr)
s = sum(arr)
dp = [[False for x in range(s+1)]for y in range(n+1)]
for i in range(1, n+1):
dp[i][0] = True
for i in range(1, s+1):
dp[0][i] = False
for i in range(1, n+1):
for j in range(1, s+1):
dp[i][j]= dp[i][j-1]
if (arr[i-1] <= j):
dp[i][j] = dp[i][j] or dp[i-1][j-arr[i-1]]
for j in range(s/2, -1, -1):
if dp[n][j] == True:
diff = s-2*j
break;
return diff