Skip to content

added dijkstra's bankers algorithm implementation to 'other' directory #1645

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 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions dynamic_programming/FloydWarshall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
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)
9 changes: 9 additions & 0 deletions dynamic_programming/coin_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
the given types of coins?
https://www.hackerrank.com/challenges/coin-change/problem
"""
<<<<<<< HEAD
from __future__ import print_function
=======
>>>>>>> upstream/master


def dp_count(S, m, n):
Expand Down Expand Up @@ -38,6 +42,11 @@ def dp_count(S, m, n):


if __name__ == "__main__":
<<<<<<< HEAD
print(dp_count([1, 2, 3], 3, 4)) # answer 4
print(dp_count([2, 5, 3, 6], 4, 10)) # answer 5
=======
import doctest

doctest.testmod()
>>>>>>> upstream/master
20 changes: 20 additions & 0 deletions dynamic_programming/edit_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ def solve(self, A, B):
return self.__solveDP(len(A) - 1, len(B) - 1)


<<<<<<< HEAD
if __name__ == "__main__":
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3

=======
def min_distance_bottom_up(word1: str, word2: str) -> int:
"""
>>> min_distance_bottom_up("intention", "execution")
Expand Down Expand Up @@ -88,16 +96,28 @@ def min_distance_bottom_up(word1: str, word2: str) -> int:


if __name__ == "__main__":
>>>>>>> upstream/master
solver = EditDistance()

print("****************** Testing Edit Distance DP Algorithm ******************")
print()

<<<<<<< HEAD
print("Enter the first string: ", end="")
S1 = raw_input().strip()

print("Enter the second string: ", end="")
S2 = raw_input().strip()

print()
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
=======
S1 = input("Enter the first string: ").strip()
S2 = input("Enter the second string: ").strip()

print()
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
print("The minimum Edit Distance is: %d" % (min_distance_bottom_up(S1, S2)))
>>>>>>> upstream/master
print()
print("*************** End of Testing Edit Distance DP Algorithm ***************")
12 changes: 12 additions & 0 deletions dynamic_programming/fibonacci.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,25 @@ def get(self, sequence_no=None):

if __name__ == "__main__":
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
<<<<<<< HEAD
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3

=======
>>>>>>> upstream/master
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
try:
N = int(input().strip())
fib = Fibonacci(N)
print(
<<<<<<< HEAD
"\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n"
=======
"\n********* Enter different values to get the corresponding fibonacci "
"sequence, enter any negative number to exit. ************\n"
>>>>>>> upstream/master
)
while True:
try:
Expand Down
28 changes: 28 additions & 0 deletions dynamic_programming/integer_partition.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
<<<<<<< HEAD
from __future__ import print_function

try:
xrange # Python 2
except NameError:
xrange = range # Python 3

try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3

=======
>>>>>>> upstream/master
"""
The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts
plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts
Expand All @@ -6,12 +21,21 @@


def partition(m):
<<<<<<< HEAD
memo = [[0 for _ in xrange(m)] for _ in xrange(m + 1)]
for i in xrange(m + 1):
memo[i][0] = 1

for n in xrange(m + 1):
for k in xrange(1, m):
=======
memo = [[0 for _ in range(m)] for _ in range(m + 1)]
for i in range(m + 1):
memo[i][0] = 1

for n in range(m + 1):
for k in range(1, m):
>>>>>>> upstream/master
memo[n][k] += memo[n][k - 1]
if n - k > 0:
memo[n][k] += memo[n - k - 1][k]
Expand All @@ -24,7 +48,11 @@ def partition(m):

if len(sys.argv) == 1:
try:
<<<<<<< HEAD
n = int(raw_input("Enter a number: "))
=======
n = int(input("Enter a number: ").strip())
>>>>>>> upstream/master
print(partition(n))
except ValueError:
print("Please enter a number.")
Expand Down
11 changes: 11 additions & 0 deletions dynamic_programming/knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ def knapsack(W, wt, val, n):
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]
<<<<<<< HEAD
=======

return dp[n][W], dp

Expand Down Expand Up @@ -89,11 +91,14 @@ def knapsack_with_example_solution(W: int, wt: list, val: list):
"All weights must be integers but "
f"got weight of type {type(wt[i])} at index {i}"
)
>>>>>>> upstream/master

optimal_val, dp_table = knapsack(W, wt, val, num_items)
example_optional_set = set()
_construct_solution(dp_table, wt, num_items, W, example_optional_set)

<<<<<<< HEAD
=======
return optimal_val, example_optional_set


Expand Down Expand Up @@ -127,6 +132,7 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
optimal_set.add(i)
_construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set)

>>>>>>> upstream/master

if __name__ == "__main__":
"""
Expand All @@ -137,6 +143,10 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
n = 4
w = 6
F = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)]
<<<<<<< HEAD
print(knapsack(w, wt, val, n))
print(MF_knapsack(n, wt, val, w)) # switched the n and w
=======
optimal_solution, _ = knapsack(w, wt, val, n)
print(optimal_solution)
print(MF_knapsack(n, wt, val, w)) # switched the n and w
Expand All @@ -148,3 +158,4 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
assert optimal_subset == {3, 4}
print("optimal_value = ", optimal_solution)
print("An optimal subset corresponding to the optimal value", optimal_subset)
>>>>>>> upstream/master
29 changes: 29 additions & 0 deletions dynamic_programming/longest_common_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@
Example:"abc", "abg" are subsequences of "abcdefgh".
"""

<<<<<<< HEAD
try:
xrange # Python 2
except NameError:
xrange = range # Python 3


def lcs_dp(x, y):
=======

def longest_common_subsequence(x: str, y: str):
"""
Expand All @@ -28,6 +37,7 @@ def longest_common_subsequence(x: str, y: str):
>>> longest_common_subsequence("computer", "food")
(1, 'o')
"""
>>>>>>> upstream/master
# find the length of strings

assert x is not None
Expand All @@ -37,12 +47,25 @@ def longest_common_subsequence(x: str, y: str):
n = len(y)

# declaring the array for storing the dp values
<<<<<<< HEAD
L = [[None] * (n + 1) for i in xrange(m + 1)]
seq = []

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
seq.append(x[i - 1])
=======
L = [[0] * (n + 1) for _ in range(m + 1)]

for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
match = 1
>>>>>>> upstream/master
else:
match = 0

Expand Down Expand Up @@ -70,6 +93,11 @@ def longest_common_subsequence(x: str, y: str):


if __name__ == "__main__":
<<<<<<< HEAD
x = "AGGTAB"
y = "GXTXAYB"
print(lcs_dp(x, y))
=======
a = "AGGTAB"
b = "GXTXAYB"
expected_ln = 4
Expand All @@ -80,3 +108,4 @@ def longest_common_subsequence(x: str, y: str):
import doctest

doctest.testmod()
>>>>>>> upstream/master
40 changes: 40 additions & 0 deletions dynamic_programming/longest_increasing_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,45 @@
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
"""
<<<<<<< HEAD
from __future__ import print_function


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]))
=======
from typing import List


Expand Down Expand Up @@ -54,3 +93,4 @@ def longest_subsequence(array: List[int]) -> List[int]: # This function is recu
import doctest

doctest.testmod()
>>>>>>> upstream/master
42 changes: 42 additions & 0 deletions dynamic_programming/longest_increasing_subsequence_O(nlogn).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from __future__ import print_function

#############################
# 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))
Loading