Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
vicky1999 authored Nov 17, 2020
2 parents 2dbf296 + 8ebe8b5 commit d1b3f5b
Show file tree
Hide file tree
Showing 32 changed files with 1,007 additions and 103 deletions.
33 changes: 23 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ If you want to uninstall algorithms, it is as simple as:
- [move_zeros](algorithms/arrays/move_zeros.py)
- [n_sum](algorithms/arrays/n_sum.py)
- [automata](algorithms/automata)
- [DFA](algorithms/automata/DFA.py)
- [DFA](algorithms/automata/dfa.py)
- [backtrack](algorithms/backtrack)
- [general_solution.md](algorithms/backtrack/)
- [add_operators](algorithms/backtrack/add_operators.py)
Expand Down Expand Up @@ -166,7 +166,7 @@ If you want to uninstall algorithms, it is as simple as:
- [maximum_flow_dfs](algorithms/graph/maximum_flow_dfs.py)
- [all_pairs_shortest_path](algorithms/graph/all_pairs_shortest_path.py)
- [bellman_ford](algorithms/graph/bellman_ford.py)
- [Count Connected Components](algoritms/graph/count_connected_number_of_component.py)
- [Count Connected Components](algorithms/graph/count_connected_number_of_component.py)
- [heap](algorithms/heap)
- [merge_sorted_k_lists](algorithms/heap/merge_sorted_k_lists.py)
- [skyline](algorithms/heap/skyline.py)
Expand Down Expand Up @@ -196,19 +196,23 @@ If you want to uninstall algorithms, it is as simple as:
- [valid_sudoku](algorithms/map/valid_sudoku.py)
- [word_pattern](algorithms/map/word_pattern.py)
- [is_isomorphic](algorithms/map/is_isomorphic.py)
- [is_anagram](algorithms/map/is_anagram.py)
- [is_anagram](algorithms/map/is_anagram.py)
- [maths](algorithms/maths)
- [power](algorithms/maths/power.py)
- [base_conversion](algorithms/maths/base_conversion.py)
- [combination](algorithms/maths/combination.py)
- [cosine_similarity](algorithms/maths/cosine_similarity.py)
- [decimal_to_binary_ip](algorithms/maths/decimal_to_binary_ip.py)
- [euler_totient](algorithms/maths/euler_totient.py)
- [extended_gcd](algorithms/maths/extended_gcd.py)
- [factorial](algorithms/maths/factorial.py)
- [factorial](algorithms/maths/factorial.py)
- [gcd/lcm](algorithms/maths/gcd.py)
- [generate_strobogrammtic](algorithms/maths/generate_strobogrammtic.py)
- [is_strobogrammatic](algorithms/maths/is_strobogrammatic.py)
- [magic_number](algorithms/maths/magic_number.py)
- [krishnamurthy_number](algorithms/maths/krishnamurthy_number.py)
- [modular_exponential](algorithms/maths/modular_exponential.py)
- [modular_inverse](algorithms/maths/modular_inverse.py)
- [next_bigger](algorithms/maths/next_bigger.py)
- [next_perfect_square](algorithms/maths/next_perfect_square.py)
- [nth_digit](algorithms/maths/nth_digit.py)
Expand All @@ -222,14 +226,14 @@ If you want to uninstall algorithms, it is as simple as:
- [hailstone](algorithms/maths/hailstone.py)
- [recursive_binomial_coefficient](algorithms/maths/recursive_binomial_coefficient.py)
- [find_order](algorithms/maths/find_order_simple.py)
- [find_primitive_root](algorithms/maths/find_primitive_root_simple.py)
- [diffie_hellman_key_exchange](algorithms/maths/diffie_hellman_key_exchange.py)
- [find_primitive_root](algorithms/maths/find_primitive_root_simple.py)
- [diffie_hellman_key_exchange](algorithms/maths/diffie_hellman_key_exchange.py)
- [matrix](algorithms/matrix)
- [sudoku_validator](algorithms/matrix/sudoku_validator.py)
- [bomb_enemy](algorithms/matrix/bomb_enemy.py)
- [copy_transform](algorithms/matrix/copy_transform.py)
- [count_paths](algorithms/matrix/count_paths.py)
- [matrix_rotation.txt](algorithms/matrix/matrix_rotation.txt)
- [matrix_exponentiation](algorithms/matrix/matrix_exponentiation.py)
- [matrix_inversion](algorithms/matrix/matrix_inversion.py)
- [matrix_multiplication](algorithms/matrix/multiply.py)
- [rotate_image](algorithms/matrix/rotate_image.py)
Expand All @@ -240,6 +244,7 @@ If you want to uninstall algorithms, it is as simple as:
- [crout_matrix_decomposition](algorithms/matrix/crout_matrix_decomposition.py)
- [cholesky_matrix_decomposition](algorithms/matrix/cholesky_matrix_decomposition.py)
- [sum_sub_squares](algorithms/matrix/sum_sub_squares.py)
- [sort_matrix_diagonally](algorithms/matrix/sort_matrix_diagonally.py)
- [queues](algorithms/queues)
- [max_sliding_window](algorithms/queues/max_sliding_window.py)
- [moving_average](algorithms/queues/moving_average.py)
Expand All @@ -258,6 +263,7 @@ If you want to uninstall algorithms, it is as simple as:
- [search_rotate](algorithms/search/search_rotate.py)
- [jump_search](algorithms/search/jump_search.py)
- [next_greatest_letter](algorithms/search/next_greatest_letter.py)
- [interpolation_search](algorithms/search/interpolation_search.py)
- [set](algorithms/set)
- [randomized_set](algorithms/set/randomized_set.py)
- [set_covering](algorithms/set/set_covering.py)
Expand All @@ -277,11 +283,13 @@ If you want to uninstall algorithms, it is as simple as:
- [meeting_rooms](algorithms/sort/meeting_rooms.py)
- [merge_sort](algorithms/sort/merge_sort.py)
- [pancake_sort](algorithms/sort/pancake_sort.py)
- [pigeonhole_sort](algorithms/sort/pigeonhole_sort.py)
- [quick_sort](algorithms/sort/quick_sort.py)
- [radix_sort](algorithms/sort/radix_sort.py)
- [selection_sort](algorithms/sort/selection_sort.py)
- [shell_sort](algorithms/sort/shell_sort.py)
- [sort_colors](algorithms/sort/sort_colors.py)
- [stooge_sort](algorithms/sort/stooge_sort.py)
- [top_sort](algorithms/sort/top_sort.py)
- [wiggle_sort](algorithms/sort/wiggle_sort.py)
- [stack](algorithms/stack)
Expand Down Expand Up @@ -322,16 +330,18 @@ If you want to uninstall algorithms, it is as simple as:
- [judge_circle](algorithms/strings/judge_circle.py)
- [strong_password](algorithms/strings/strong_password.py)
- [caesar_cipher](algorithms/strings/caesar_cipher.py)
- [check_pangram](algorithms/strings/check_pangram.py)
- [contain_string](algorithms/strings/contain_string.py)
- [count_binary_substring](algorithms/strings/count_binary_substring.py)
- [repeat_string](algorithms/strings/repeat_string.py)
- [min_distance](algorithms/strings/min_distance.py)
- [longest_common_prefix](algorithms/strings/longest_common_prefix.py)
- [rotate](algorithms/strings/rotate.py)
- [first_unique_char](algorithms/strings/first_unique_char.py)
- [repeat_substring](algorithms/strings/repeat_substring.py)
- [atbash_cipher](algorithms/strings/atbash_cipher.py)
- [knuth_morris_pratt](algorithms/strings/knuth_morris_pratt.py)
- [repeat_substring](algorithms/strings/repeat_substring.py)
- [atbash_cipher](algorithms/strings/atbash_cipher.py)
- [longest_palindromic_substring](algorithms/strings/longest_palindromic_substring.py)
- [knuth_morris_pratt](algorithms/strings/knuth_morris_pratt.py)
- [tree](algorithms/tree)
- [bst](algorithms/tree/bst)
- [array_to_bst](algorithms/tree/bst/array_to_bst.py)
Expand All @@ -349,6 +359,8 @@ If you want to uninstall algorithms, it is as simple as:
- [count_left_node](algorithms/tree/bst/count_left_node.py)
- [num_empty](algorithms/tree/bst/num_empty.py)
- [height](algorithms/tree/bst/height.py)
- [fenwick_tree](algorithms/tree/fenwick_tree]
- [fenwick_tree](algorithms/tree/fenwick_tree/fenwick_tree.py)
- [red_black_tree](algorithms/tree/red_black_tree)
- [red_black_tree](algorithms/tree/red_black_tree/red_black_tree.py)
- [segment_tree](algorithms/tree/segment_tree)
Expand All @@ -366,6 +378,7 @@ If you want to uninstall algorithms, it is as simple as:
- [b_tree](algorithms/tree/b_tree.py)
- [binary_tree_paths](algorithms/tree/binary_tree_paths.py)
- [bin_tree_to_list](algorithms/tree/bin_tree_to_list.py)
- [construct_tree_preorder_postorder](algorithms/tree/construct_tree_postorder_preorder.py)
- [deepest_left](algorithms/tree/deepest_left.py)
- [invert_tree](algorithms/tree/invert_tree.py)
- [is_balanced](algorithms/tree/is_balanced.py)
Expand Down
4 changes: 2 additions & 2 deletions algorithms/arrays/flatten.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def flatten(input_arr, output_arr=None):
if output_arr is None:
output_arr = []
for ele in input_arr:
if isinstance(ele, Iterable):
if not isinstance(ele, str) and isinstance(ele, Iterable):
flatten(ele, output_arr) #tail-recursion
else:
output_arr.append(ele) #produce the result
Expand All @@ -25,7 +25,7 @@ def flatten_iter(iterable):
returns generator which produces one dimensional output.
"""
for element in iterable:
if isinstance(element, Iterable):
if not isinstance(element, str) and isinstance(element, Iterable):
yield from flatten_iter(element)
else:
yield element
14 changes: 14 additions & 0 deletions algorithms/dp/fib.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
'''
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence,
such that each number is the sum of the two preceding ones, starting from 0 and 1.
That is,
F0=0 , F1=1
and
Fn= F(n-1) + F(n-2)
The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Here, given a number n, print n-th Fibonacci Number.
'''
def fib_recursive(n):
"""[summary]
Computes the n-th fibonacci number recursive.
Expand Down
4 changes: 4 additions & 0 deletions algorithms/maths/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,7 @@
from .find_primitive_root_simple import *
from .diffie_hellman_key_exchange import *
from .num_digits import *
from .power import *
from .magic_number import *
from .krishnamurthy_number import *

43 changes: 43 additions & 0 deletions algorithms/maths/krishnamurthy_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""
A Krishnamurthy number is a number whose sum total of the factorials of each digit is equal to the number itself.
Here's what I mean by that:
"145" is a Krishnamurthy Number because,
1! + 4! + 5! = 1 + 24 + 120 = 145
"40585" is also a Krishnamurthy Number.
4! + 0! + 5! + 8! + 5! = 40585
"357" or "25965" is NOT a Krishnamurthy Number
3! + 5! + 7! = 6 + 120 + 5040 != 357
The following function will check if a number is a Krishnamurthy Number or not and return a boolean value.
"""


def find_factorial(n):
fact = 1
while n != 0:
fact *= n
n -= 1
return fact


def krishnamurthy_number(n):
if n == 0:
return False
sum_of_digits = 0 # will hold sum of FACTORIAL of digits
temp = n

while temp != 0:

# get the factorial of of the last digit of n and add it to sum_of_digits
sum_of_digits += find_factorial(temp % 10)

# replace value of temp by temp/10
# i.e. will remove the last digit from temp
temp //= 10

# returns True if number is krishnamurthy
return (sum_of_digits == n)
36 changes: 36 additions & 0 deletions algorithms/maths/magic_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Magic Number
A number is said to be a magic number,
if the sum of its digits are calculated till a single digit recursively
by adding the sum of the digits after every addition.
If the single digit comes out to be 1,then the number is a magic number.
Example:
Number = 50113 => 5+0+1+1+3=10 => 1+0=1 [This is a Magic Number]
Number = 1234 => 1+2+3+4=10 => 1+0=1 [This is a Magic Number]
Number = 199 => 1+9+9=19 => 1+9=10 => 1+0=1 [This is a Magic Number]
Number = 111 => 1+1+1=3 [This is NOT a Magic Number]
The following function checks for Magic numbers and returns a Boolean accordingly.
"""


def magic_number(n):
total_sum = 0

# will end when n becomes 0
# AND
# sum becomes single digit.
while n > 0 or total_sum > 9:

# when n becomes 0 but we have a total_sum,
# we update the value of n with the value of the sum digits
if n == 0:
n = total_sum # only when sum of digits isn't single digit
total_sum = 0
total_sum += n % 10
n //= 10

# Return true if sum becomes 1
return total_sum == 1


34 changes: 34 additions & 0 deletions algorithms/maths/modular_inverse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# extended_gcd(a, b) modified from
# https://github.com/keon/algorithms/blob/master/algorithms/maths/extended_gcd.py

def extended_gcd(a: int, b: int) -> [int, int, int]:
"""Extended GCD algorithm.
Return s, t, g
such that a * s + b * t = GCD(a, b)
and s and t are co-prime.
"""

old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = a, b

while r != 0:
quotient = old_r // r

old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t

return old_s, old_t, old_r


def modular_inverse(a: int, m: int) -> int:
"""
Returns x such that a * x = 1 (mod m)
a and m must be coprime
"""

s, t, g = extended_gcd(a, m)
if g != 1:
raise ValueError("a and m must be coprime")
return s % m
45 changes: 45 additions & 0 deletions algorithms/maths/power.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
def power(a: int, n: int, r: int = None):
"""
Iterative version of binary exponentiation
Calculate a ^ n
if r is specified, return the result modulo r
Time Complexity : O(log(n))
Space Complexity : O(1)
"""
ans = 1
while n:
if n & 1:
ans = ans * a
a = a * a
if r:
ans %= r
a %= r
n >>= 1
return ans


def power_recur(a: int, n: int, r: int = None):
"""
Recursive version of binary exponentiation
Calculate a ^ n
if r is specified, return the result modulo r
Time Complexity : O(log(n))
Space Complexity : O(log(n))
"""
if n == 0:
ans = 1
elif n == 1:
ans = a
else:
ans = power_recur(a, n // 2, r)
ans = ans * ans
if n % 2:
ans = ans * a
if r:
ans %= r
return ans

1 change: 0 additions & 1 deletion algorithms/matrix/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@

41 changes: 41 additions & 0 deletions algorithms/matrix/matrix_exponentiation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
def multiply(matA: list, matB: list) -> list:
"""
Multiplies two square matrices matA and matB od size n x n
Time Complexity: O(n^3)
"""
n = len(matA)
matC = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
for j in range(n):
for k in range(n):
matC[i][j] += matA[i][k] * matB[k][j]

return matC

def identity(n: int) -> list:
"""
Returns the Identity matrix of size n x n
Time Complecity: O(n^2)
"""
I = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
I[i][i] = 1

return I

def matrix_exponentiation(mat: list, n: int) -> list:
"""
Calculates mat^n by repeated squaring
Time Complexity: O(d^3 log(n))
d: dimesion of the square matrix mat
n: power the matrix is raised to
"""
if n == 0:
return identity(len(mat))
elif n % 2 == 1:
return multiply(matrix_exponentiation(mat, n - 1), mat)
else:
tmp = matrix_exponentiation(mat, n // 2)
return multiply(tmp, tmp)
Loading

0 comments on commit d1b3f5b

Please sign in to comment.