Skip to content

add python implementation of some of the given algorithm #267

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 13 commits into from
89 changes: 89 additions & 0 deletions Competitive Coding/Backtrack/N-Queen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Python program to solve N Queen
# Problem using backtracking

global N
N = 4

def printSolution(board):
for i in range(N):
for j in range(N):
print board[i][j],
print


# A utility function to check if a queen can
# be placed on board[row][col]. Note that this
# function is called when "col" queens are
# already placed in columns from 0 to col -1.
# So we need to check only left side for
# attacking queens
def isSafe(board, row, col):

# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False

# Check upper diagonal on left side
for i,j in zip(range(row,-1,-1), range(col,-1,-1)):
if board[i][j] == 1:
return False

# Check lower diagonal on left side
for i,j in zip(range(row,N,1), range(col,-1,-1)):
if board[i][j] == 1:
return False

return True

def solveNQUtil(board, col):
# base case: If all queens are placed
# then return true
if col >= N:
return True

# Consider this column and try placing
# this queen in all rows one by one
for i in range(N):

if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1

# recur to place rest of the queens
if solveNQUtil(board, col+1) == True:
return True

# If placing queen in board[i][col
# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0

# if queen can not be place in any row in
# this colum col then return false
return False

# This function solves the N Queen problem using
# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]

if solveNQUtil(board, 0) == False:
print "Solution does not exist"
return False

printSolution(board)
return True

# driver program to test above function
solveNQ()
119 changes: 119 additions & 0 deletions Competitive Coding/Backtrack/sudoku.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# A Backtracking program in Pyhton to solve Sudoku problem


# A Utility Function to print the Grid
def print_grid(arr):
for i in range(9):
for j in range(9):
print arr[i][j],
print ('n')


# Function to Find the entry in the Grid that is still not used
# Searches the grid to find an entry that is still unassigned. If
# found, the reference parameters row, col will be set the location
# that is unassigned, and true is returned. If no unassigned entries
# remain, false is returned.
# 'l' is a list variable that has been passed from the solve_sudoku function
# to keep track of incrementation of Rows and Columns
def find_empty_location(arr,l):
for row in range(9):
for col in range(9):
if(arr[row][col]==0):
l[0]=row
l[1]=col
return True
return False

# Returns a boolean which indicates whether any assigned entry
# in the specified row matches the given number.
def used_in_row(arr,row,num):
for i in range(9):
if(arr[row][i] == num):
return True
return False

# Returns a boolean which indicates whether any assigned entry
# in the specified column matches the given number.
def used_in_col(arr,col,num):
for i in range(9):
if(arr[i][col] == num):
return True
return False

# Returns a boolean which indicates whether any assigned entry
# within the specified 3x3 box matches the given number
def used_in_box(arr,row,col,num):
for i in range(3):
for j in range(3):
if(arr[i+row][j+col] == num):
return True
return False

# Checks whether it will be legal to assign num to the given row,col
# Returns a boolean which indicates whether it will be legal to assign
# num to the given row,col location.
def check_location_is_safe(arr,row,col,num):

# Check if 'num' is not already placed in current row,
# current column and current 3x3 box
return not used_in_row(arr,row,num) and not used_in_col(arr,col,num) and not used_in_box(arr,row - row%3,col - col%3,num)

# Takes a partially filled-in grid and attempts to assign values to
# all unassigned locations in such a way to meet the requirements
# for Sudoku solution (non-duplication across rows, columns, and boxes)
def solve_sudoku(arr):

# 'l' is a list variable that keeps the record of row and col in find_empty_location Function
l=[0,0]

# If there is no unassigned location, we are done
if(not find_empty_location(arr,l)):
return True

# Assigning list values to row and col that we got from the above Function
row=l[0]
col=l[1]

# consider digits 1 to 9
for num in range(1,10):

# if looks promising
if(check_location_is_safe(arr,row,col,num)):

# make tentative assignment
arr[row][col]=num

# return, if sucess, ya!
if(solve_sudoku(arr)):
return True

# failure, unmake & try again
arr[row][col] = 0

# this triggers backtracking
return False

# Driver main function to test above functions
if __name__=="__main__":

# creating a 2D array for the grid
grid=[[0 for x in range(9)]for y in range(9)]

# assigning values to the grid
grid=[[3,0,6,5,0,8,4,0,0],
[5,2,0,0,0,0,0,0,0],
[0,8,7,0,0,0,0,3,1],
[0,0,3,0,1,0,0,8,0],
[9,0,0,8,6,3,0,0,5],
[0,5,0,0,9,0,6,0,0],
[1,3,0,0,0,0,2,5,0],
[0,0,0,0,0,0,0,7,4],
[0,0,5,2,0,6,3,0,0]]

# if sucess print the grid
if(solve_sudoku(grid)):
print_grid(grid)
else:
print "No solution exists"

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def lcs(X , Y):
m = len(X)
n = len(Y)

L = [[None]*(n+1) for i in xrange(m+1)]

for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0 :
L[i][j] = 0
elif X[i-1] == Y[j-1]:
L[i][j] = L[i-1][j-1]+1
else:
L[i][j] = max(L[i-1][j] , L[i][j-1])
return L[m][n]
X = "AGGTAB"
Y = "GXTXAYB"
print "Length of LCS is ", lcs(X, Y)
22 changes: 22 additions & 0 deletions Competitive Coding/Dynamic Programming/minCostPath/Mincostpath.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
R = 3
C = 3

def minCost(cost, m, n):
tc = [[0 for x in range(C)] for x in range(R)]

tc[0][0] = cost[0][0]


for i in range(1, m+1):
tc[i][0] = tc[i-1][0] + cost[i][0]
for j in range(1, n+1):
tc[0][j] = tc[0][j-1] + cost[0][j]
for i in range(1, m+1):
for j in range(1, n+1):
tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]

return tc[m][n]
cost = [[1, 2, 3],
[4, 8, 2],
[1, 5, 3]]
print(minCost(cost, 2, 2))
20 changes: 16 additions & 4 deletions Competitive Coding/Dynamic Programming/minCostPath/Readme.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed.
Given a cost matrix cost[ ][ ] and position (m, n) in cost[ ][ ].

1) Optimal Substructure
Write a function that returns cost of minimum cost path to reach (m, n) from (0, 0).

Each cell of the matrix represents a cost to traverse through that cell.

Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination).

You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed.



1. Optimal Substructure
The path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or (m, n-1). So minimum cost to reach (m, n) can be written as “minimum of the 3 cells plus cost[m][n]”.

minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]

2) Overlapping Subproblems


2. Overlapping Subproblems
Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be
avoided by constructing a temporary array tc[][] in bottom up manner.
avoided by constructing a temporary array tc[ ][ ] in bottom up manner.


Example:
Expand Down
17 changes: 10 additions & 7 deletions Competitive Coding/Dynamic Programming/subsetSum/Readme.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.

Examples: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Examples: set[ ] = {3, 34, 4, 12, 5, 2}, sum = 9

Output: True //There is a subset (4, 5) with sum 9.

Let isSubSetSum(int set[], int n, int sum) be the function to find whether there is a subset of set[] with sum equal to sum. n is the number of elements in set[].
Let isSubSetSum(int set[ ], int n, int sum) be the function to find whether there is a subset of set[] with sum equal to sum. n is the number of elements in set[ ].

The isSubsetSum problem can be divided into two subproblems:-

a) Include the last element, recur for n = n-1, sum = sum – set[n-1]
b) Exclude the last element, recur for n = n-1.

The isSubsetSum problem can be divided into two subproblems
…a) Include the last element, recur for n = n-1, sum = sum – set[n-1]
…b) Exclude the last element, recur for n = n-1.
If any of the above the above subproblems return true, then return true.

Following is the recursive formula for isSubsetSum() problem.
Following is the recursive formula for isSubsetSum() problem:-

isSubsetSum(set, n, sum) = isSubsetSum(set, n-1, sum) ||
isSubsetSum(set, n-1, sum-set[n-1])
Base Cases:
isSubsetSum(set, n, sum) = false, if sum > 0 and n == 0
isSubsetSum(set, n, sum) = true, if sum == 0

We can solve the problem in Pseudo-polynomial time using Dynamic programming. We create a boolean 2D table subset[][] and fill it in bottom up manner. The value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i., otherwise false. Finally, we return subset[sum][n]
We can solve the problem in Pseudo-polynomial time using Dynamic programming. We create a boolean 2D table subset[ ][ ] and fill it in bottom up manner. The value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i., otherwise false. Finally, we return subset[sum][n]
24 changes: 24 additions & 0 deletions Competitive Coding/Dynamic Programming/subsetSum/subsetsum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def isSubsetSum(st, n, sm) :
subset=[[True] * (sm+1)] * (n+1)

for i in range(0, n+1) :
subset[i][0] = True

for i in range(1, sm + 1) :
subset[0][i] = False

for i in range(1, n+1) :
for j in range(1, sm+1) :
if(j < st[i-1]) :
subset[i][j] = subset[i-1][j]
if (j >= st[i-1]) :
subset[i][j] = subset[i-1][j] or subset[i - 1][j-st[i-1]]
return subset[n][sm];

st = [1, 2, 3]
sm = 7
n = len(st)
if (isSubsetSum(st, n, sm) == True) :
print("Found a subset with given sum")
else :
print("No subset with given sum")
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@

### About the Project

This repository contains some of the most **intriguing and awesome algorithms** of daily life implemented in languages primarily in C/C++/Java/Python.
This repository contains some of the most **intriguing and awesome algorithms** of daily life implemented in languages primarily in
* C
* C++
* Java
* Python

--------------------------------------------------------------

Expand Down