From afd78dad67f12517a8977dd507c24ca6db9c5fee Mon Sep 17 00:00:00 2001 From: Tianyi Zheng Date: Sun, 16 Oct 2022 21:27:05 -0400 Subject: [PATCH 01/11] Refactor bottom-up function to be class method --- dynamic_programming/edit_distance.py | 134 +++++++++++++-------------- 1 file changed, 66 insertions(+), 68 deletions(-) diff --git a/dynamic_programming/edit_distance.py b/dynamic_programming/edit_distance.py index fe23431a7ea6..914f3017eac0 100644 --- a/dynamic_programming/edit_distance.py +++ b/dynamic_programming/edit_distance.py @@ -19,74 +19,72 @@ class EditDistance: """ 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 __solve_dp(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] + self.word1 = "" + self.word2 = "" + self.dp = [] + + def __min_dist_top_down_dp(self, m, n): + if m == -1: + return n + 1 + elif n == -1: + return m + 1 + elif self.dp[m][n] > -1: + return self.dp[m][n] else: - if self.a[x] == self.b[y]: - self.dp[x][y] = self.__solve_dp(x - 1, y - 1) + if self.word1[m] == self.word2[n]: + self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1) else: - self.dp[x][y] = 1 + min( - self.__solve_dp(x, y - 1), - self.__solve_dp(x - 1, y), - self.__solve_dp(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.__solve_dp(len(a) - 1, len(b) - 1) - - -def min_distance_bottom_up(word1: str, word2: str) -> int: - """ - >>> min_distance_bottom_up("intention", "execution") - 5 - >>> min_distance_bottom_up("intention", "") - 9 - >>> min_distance_bottom_up("", "") - 0 - """ - m = len(word1) - n = len(word2) - dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] - for i in range(m + 1): - for j in range(n + 1): - - if i == 0: # first string is empty - dp[i][j] = j - elif j == 0: # second string is empty - dp[i][j] = i - elif ( - word1[i - 1] == word2[j - 1] - ): # last character of both substing is equal - dp[i][j] = dp[i - 1][j - 1] - else: - insert = dp[i][j - 1] - delete = dp[i - 1][j] - replace = dp[i - 1][j - 1] - dp[i][j] = 1 + min(insert, delete, replace) - return dp[m][n] + insert = self.__min_dist_top_down_dp(m, n - 1) + delete = self.__min_dist_top_down_dp(m - 1, n) + replace = self.__min_dist_top_down_dp(m - 1, n - 1) + self.dp[m][n] = 1 + min(insert, delete, replace) + + return self.dp[m][n] + + def min_dist_top_down(self, word1: str, word2: str) -> int: + """ + >>> EditDistance().min_dist_top_down("intention", "execution") + 5 + >>> EditDistance().min_dist_top_down("intention", "") + 9 + >>> EditDistance().min_dist_top_down("", "") + 0 + """ + self.word1 = word1 + self.word2 = word2 + self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))] + + return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1) + + def min_distance_bottom_up(self, word1: str, word2: str) -> int: + """ + >>> EditDistance().min_distance_bottom_up("intention", "execution") + 5 + >>> EditDistance().min_distance_bottom_up("intention", "") + 9 + >>> EditDistance().min_distance_bottom_up("", "") + 0 + """ + self.word1 = word1 + self.word2 = word2 + m = len(word1) + n = len(word2) + self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] + + for i in range(m + 1): + for j in range(n + 1): + if i == 0: # first string is empty + self.dp[i][j] = j + elif j == 0: # second string is empty + self.dp[i][j] = i + elif word1[i - 1] == word2[j - 1]: # last characters are equal + self.dp[i][j] = self.dp[i - 1][j - 1] + else: + insert = self.dp[i][j - 1] + delete = self.dp[i - 1][j] + replace = self.dp[i - 1][j - 1] + self.dp[i][j] = 1 + min(insert, delete, replace) + return self.dp[m][n] if __name__ == "__main__": @@ -99,7 +97,7 @@ def min_distance_bottom_up(word1: str, word2: str) -> int: S2 = input("Enter the second string: ").strip() print() - print(f"The minimum Edit Distance is: {solver.solve(S1, S2)}") - print(f"The minimum Edit Distance is: {min_distance_bottom_up(S1, S2)}") + print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}") + print(f"The minimum edit distance is: {solver.min_distance_bottom_up(S1, S2)}") print() print("*************** End of Testing Edit Distance DP Algorithm ***************") From f4eeecc38782404124f39ac5c72dee740f436080 Mon Sep 17 00:00:00 2001 From: Tianyi Zheng Date: Sun, 16 Oct 2022 21:29:05 -0400 Subject: [PATCH 02/11] Add type hints --- dynamic_programming/edit_distance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/edit_distance.py b/dynamic_programming/edit_distance.py index 914f3017eac0..9c6556866483 100644 --- a/dynamic_programming/edit_distance.py +++ b/dynamic_programming/edit_distance.py @@ -23,7 +23,7 @@ def __init__(self): self.word2 = "" self.dp = [] - def __min_dist_top_down_dp(self, m, n): + def __min_dist_top_down_dp(self, m: int, n: int) -> int: if m == -1: return n + 1 elif n == -1: From 167e5ab86806bc10229c87f4b9e92fba562f5ddc Mon Sep 17 00:00:00 2001 From: Tianyi Zheng Date: Mon, 17 Oct 2022 18:40:53 -0400 Subject: [PATCH 03/11] Update convolve function namespace --- computer_vision/horn_schunck.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/computer_vision/horn_schunck.py b/computer_vision/horn_schunck.py index 2a153d06ddae..b63e0268294c 100644 --- a/computer_vision/horn_schunck.py +++ b/computer_vision/horn_schunck.py @@ -12,7 +12,7 @@ from typing import SupportsIndex import numpy as np -from scipy.ndimage.filters import convolve +from scipy.ndimage import convolve def warp( From 5386e57271cac993c422b9fbb5120923af445a4f Mon Sep 17 00:00:00 2001 From: Tianyi Zheng Date: Tue, 18 Oct 2022 04:27:11 -0400 Subject: [PATCH 04/11] Remove depreciated np.float --- machine_learning/decision_tree.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/machine_learning/decision_tree.py b/machine_learning/decision_tree.py index 4a86e5322a27..7cd1b02c4181 100644 --- a/machine_learning/decision_tree.py +++ b/machine_learning/decision_tree.py @@ -24,13 +24,13 @@ def mean_squared_error(self, labels, prediction): estimate the labels >>> tester = DecisionTree() >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10]) - >>> test_prediction = np.float(6) + >>> test_prediction = float(6) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... TestDecisionTree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True >>> test_labels = np.array([1,2,3]) - >>> test_prediction = np.float(2) + >>> test_prediction = float(2) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... TestDecisionTree.helper_mean_squared_error_test(test_labels, ... test_prediction)) @@ -145,11 +145,11 @@ def helper_mean_squared_error_test(labels, prediction): @param prediction: a floating point value return value: helper_mean_squared_error_test calculates the mean squared error """ - squared_error_sum = np.float(0) + squared_error_sum = float(0) for label in labels: squared_error_sum += (label - prediction) ** 2 - return np.float(squared_error_sum / labels.size) + return float(squared_error_sum / labels.size) def main(): From cdb6991903d2a9cf17235356ee33359876ba45d5 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 19 Oct 2022 17:47:44 +0000 Subject: [PATCH 05/11] updating DIRECTORY.md --- DIRECTORY.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c1fad8d9d794..1fad287988c4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -27,6 +27,7 @@ * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) + * [Minmax](backtracking/minmax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Rat In Maze](backtracking/rat_in_maze.py) @@ -157,6 +158,7 @@ * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) + * [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) @@ -513,6 +515,7 @@ * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) + * [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) @@ -601,6 +604,7 @@ * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) + * [Max Area Of Island](matrix/max_area_of_island.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) From 78761087294a7ee3dc9ed0e6cf921b3101d84eb3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 20 Oct 2022 21:09:20 +0000 Subject: [PATCH 06/11] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 1fad287988c4..350764ec0042 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -360,6 +360,7 @@ * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) + * [Dijkstra Alternate](graphs/dijkstra_alternate.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) @@ -936,6 +937,7 @@ * [Not Gate](quantum/not_gate.py) * [Q Full Adder](quantum/q_full_adder.py) * [Quantum Entanglement](quantum/quantum_entanglement.py) + * [Quantum Random](quantum/quantum_random.py) * [Ripple Adder Classic](quantum/ripple_adder_classic.py) * [Single Qubit Measure](quantum/single_qubit_measure.py) From 15594ff293e5c48f67d3da980ecd0c162b7ec48c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 21 Oct 2022 21:14:22 +0000 Subject: [PATCH 07/11] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 350764ec0042..70644d0639dc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -461,6 +461,7 @@ * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) + * [Xgboostclassifier](machine_learning/xgboostclassifier.py) ## Maths * [3N Plus 1](maths/3n_plus_1.py) @@ -535,6 +536,7 @@ * [Line Length](maths/line_length.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) + * [Maclaurin Sin](maths/maclaurin_sin.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) From 46b7978a340ec752da0c39beb6177a76bfb4bb8b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 22 Oct 2022 19:30:58 +0000 Subject: [PATCH 08/11] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 70644d0639dc..7e43184824f5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -536,7 +536,7 @@ * [Line Length](maths/line_length.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) - * [Maclaurin Sin](maths/maclaurin_sin.py) + * [Maclaurin Series](maths/maclaurin_series.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) From 466dc4efb09e06c7cedca5de2b28c8753b4375e8 Mon Sep 17 00:00:00 2001 From: Chris O <46587501+ChrisO345@users.noreply.github.com> Date: Mon, 31 Oct 2022 18:07:54 +1300 Subject: [PATCH 09/11] Renamed function for consistency --- dynamic_programming/edit_distance.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/dynamic_programming/edit_distance.py b/dynamic_programming/edit_distance.py index 9c6556866483..774aa047326e 100644 --- a/dynamic_programming/edit_distance.py +++ b/dynamic_programming/edit_distance.py @@ -56,13 +56,13 @@ def min_dist_top_down(self, word1: str, word2: str) -> int: return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1) - def min_distance_bottom_up(self, word1: str, word2: str) -> int: + def min_dist_bottom_up(self, word1: str, word2: str) -> int: """ - >>> EditDistance().min_distance_bottom_up("intention", "execution") + >>> EditDistance().min_dist_bottom_up("intention", "execution") 5 - >>> EditDistance().min_distance_bottom_up("intention", "") + >>> EditDistance().min_dist_bottom_up("intention", "") 9 - >>> EditDistance().min_distance_bottom_up("", "") + >>> EditDistance().min_dist_bottom_up("", "") 0 """ self.word1 = word1 @@ -98,6 +98,6 @@ def min_distance_bottom_up(self, word1: str, word2: str) -> int: print() print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}") - print(f"The minimum edit distance is: {solver.min_distance_bottom_up(S1, S2)}") + print(f"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}") print() print("*************** End of Testing Edit Distance DP Algorithm ***************") From eed1195aa253939e7ae7cd9ec17dca9bf11d37e3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 31 Oct 2022 05:11:11 +0000 Subject: [PATCH 10/11] updating DIRECTORY.md --- DIRECTORY.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 38fd1d656488..be3a121c80bd 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -46,6 +46,7 @@ * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Highest Set Bit](bit_manipulation/highest_set_bit.py) + * [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py) * [Is Even](bit_manipulation/is_even.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) @@ -307,24 +308,28 @@ * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Sub Array](dynamic_programming/max_sub_array.py) * [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py) + * [Min Distance Up Bottom](dynamic_programming/min_distance_up_bottom.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) + * [Palindrome Partitioning](dynamic_programming/palindrome_partitioning.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) * [Viterbi](dynamic_programming/viterbi.py) ## Electronics + * [Builtin Voltage](electronics/builtin_voltage.py) * [Carrier Concentration](electronics/carrier_concentration.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Conductivity](electronics/electric_conductivity.py) * [Electric Power](electronics/electric_power.py) * [Electrical Impedance](electronics/electrical_impedance.py) * [Ohms Law](electronics/ohms_law.py) + * [Resistor Equivalence](electronics/resistor_equivalence.py) * [Resonant Frequency](electronics/resonant_frequency.py) ## File Transfer @@ -426,6 +431,7 @@ * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) + * [Elf](hashes/elf.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) @@ -491,6 +497,7 @@ * [Abs Max](maths/abs_max.py) * [Abs Min](maths/abs_min.py) * [Add](maths/add.py) + * [Addition Without Arithmetic](maths/addition_without_arithmetic.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Arc Length](maths/arc_length.py) @@ -581,12 +588,15 @@ * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) + * Polynomials + * [Single Indeterminate Operations](maths/polynomials/single_indeterminate_operations.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) + * [Print Multiplication Table](maths/print_multiplication_table.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) @@ -676,12 +686,15 @@ * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subarray](other/maximum_subarray.py) * [Nested Brackets](other/nested_brackets.py) + * [Pascal Triangle](other/pascal_triangle.py) * [Password Generator](other/password_generator.py) + * [Quine](other/quine.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) ## Physics + * [Archimedes Principle](physics/archimedes_principle.py) * [Casimir Effect](physics/casimir_effect.py) * [Centripetal Force](physics/centripetal_force.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) @@ -694,7 +707,7 @@ * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) * [Potential Energy](physics/potential_energy.py) * [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py) - * [Sheer Stress](physics/sheer_stress.py) + * [Shear Stress](physics/shear_stress.py) ## Project Euler * Problem 001 From e73523ebce16f54f15dec99aff1c5717fa045c31 Mon Sep 17 00:00:00 2001 From: Tianyi Zheng Date: Tue, 27 Dec 2022 16:48:26 -0800 Subject: [PATCH 11/11] Remove extra imports in gamma.py doctests --- maths/gamma.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/maths/gamma.py b/maths/gamma.py index 69cd819ef186..d5debc58764b 100644 --- a/maths/gamma.py +++ b/maths/gamma.py @@ -11,42 +11,27 @@ def gamma(num: float) -> float: used extension of the factorial function to complex numbers. The gamma function is defined for all complex numbers except the non-positive integers - - >>> gamma(-1) Traceback (most recent call last): ... ValueError: math domain error - - - >>> gamma(0) Traceback (most recent call last): ... ValueError: math domain error - - >>> gamma(9) 40320.0 - >>> from math import gamma as math_gamma >>> all(.99999999 < gamma(i) / math_gamma(i) <= 1.000000001 ... for i in range(1, 50)) True - - - >>> from math import gamma as math_gamma >>> gamma(-1)/math_gamma(-1) <= 1.000000001 Traceback (most recent call last): ... ValueError: math domain error - - - >>> from math import gamma as math_gamma >>> gamma(3.3) - math_gamma(3.3) <= 0.00000001 True """ - if num <= 0: raise ValueError("math domain error")