mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Refactor bottom-up edit distance function to be class method (#7347)
* Refactor bottom-up function to be class method * Add type hints * Update convolve function namespace * Remove depreciated np.float * updating DIRECTORY.md * updating DIRECTORY.md * updating DIRECTORY.md * updating DIRECTORY.md * Renamed function for consistency * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Chris O <46587501+ChrisO345@users.noreply.github.com>
This commit is contained in:
parent
f8958ebe20
commit
39e5bc5980
15
DIRECTORY.md
15
DIRECTORY.md
|
@ -46,6 +46,7 @@
|
||||||
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
|
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
|
||||||
* [Gray Code Sequence](bit_manipulation/gray_code_sequence.py)
|
* [Gray Code Sequence](bit_manipulation/gray_code_sequence.py)
|
||||||
* [Highest Set Bit](bit_manipulation/highest_set_bit.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)
|
* [Is Even](bit_manipulation/is_even.py)
|
||||||
* [Reverse Bits](bit_manipulation/reverse_bits.py)
|
* [Reverse Bits](bit_manipulation/reverse_bits.py)
|
||||||
* [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.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 Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py)
|
||||||
* [Max Sub Array](dynamic_programming/max_sub_array.py)
|
* [Max Sub Array](dynamic_programming/max_sub_array.py)
|
||||||
* [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.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 Coin Change](dynamic_programming/minimum_coin_change.py)
|
||||||
* [Minimum Cost Path](dynamic_programming/minimum_cost_path.py)
|
* [Minimum Cost Path](dynamic_programming/minimum_cost_path.py)
|
||||||
* [Minimum Partition](dynamic_programming/minimum_partition.py)
|
* [Minimum Partition](dynamic_programming/minimum_partition.py)
|
||||||
* [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.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)
|
* [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py)
|
||||||
* [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.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)
|
* [Rod Cutting](dynamic_programming/rod_cutting.py)
|
||||||
* [Subset Generation](dynamic_programming/subset_generation.py)
|
* [Subset Generation](dynamic_programming/subset_generation.py)
|
||||||
* [Sum Of Subset](dynamic_programming/sum_of_subset.py)
|
* [Sum Of Subset](dynamic_programming/sum_of_subset.py)
|
||||||
* [Viterbi](dynamic_programming/viterbi.py)
|
* [Viterbi](dynamic_programming/viterbi.py)
|
||||||
|
|
||||||
## Electronics
|
## Electronics
|
||||||
|
* [Builtin Voltage](electronics/builtin_voltage.py)
|
||||||
* [Carrier Concentration](electronics/carrier_concentration.py)
|
* [Carrier Concentration](electronics/carrier_concentration.py)
|
||||||
* [Coulombs Law](electronics/coulombs_law.py)
|
* [Coulombs Law](electronics/coulombs_law.py)
|
||||||
* [Electric Conductivity](electronics/electric_conductivity.py)
|
* [Electric Conductivity](electronics/electric_conductivity.py)
|
||||||
* [Electric Power](electronics/electric_power.py)
|
* [Electric Power](electronics/electric_power.py)
|
||||||
* [Electrical Impedance](electronics/electrical_impedance.py)
|
* [Electrical Impedance](electronics/electrical_impedance.py)
|
||||||
* [Ohms Law](electronics/ohms_law.py)
|
* [Ohms Law](electronics/ohms_law.py)
|
||||||
|
* [Resistor Equivalence](electronics/resistor_equivalence.py)
|
||||||
* [Resonant Frequency](electronics/resonant_frequency.py)
|
* [Resonant Frequency](electronics/resonant_frequency.py)
|
||||||
|
|
||||||
## File Transfer
|
## File Transfer
|
||||||
|
@ -426,6 +431,7 @@
|
||||||
* [Adler32](hashes/adler32.py)
|
* [Adler32](hashes/adler32.py)
|
||||||
* [Chaos Machine](hashes/chaos_machine.py)
|
* [Chaos Machine](hashes/chaos_machine.py)
|
||||||
* [Djb2](hashes/djb2.py)
|
* [Djb2](hashes/djb2.py)
|
||||||
|
* [Elf](hashes/elf.py)
|
||||||
* [Enigma Machine](hashes/enigma_machine.py)
|
* [Enigma Machine](hashes/enigma_machine.py)
|
||||||
* [Hamming Code](hashes/hamming_code.py)
|
* [Hamming Code](hashes/hamming_code.py)
|
||||||
* [Luhn](hashes/luhn.py)
|
* [Luhn](hashes/luhn.py)
|
||||||
|
@ -491,6 +497,7 @@
|
||||||
* [Abs Max](maths/abs_max.py)
|
* [Abs Max](maths/abs_max.py)
|
||||||
* [Abs Min](maths/abs_min.py)
|
* [Abs Min](maths/abs_min.py)
|
||||||
* [Add](maths/add.py)
|
* [Add](maths/add.py)
|
||||||
|
* [Addition Without Arithmetic](maths/addition_without_arithmetic.py)
|
||||||
* [Aliquot Sum](maths/aliquot_sum.py)
|
* [Aliquot Sum](maths/aliquot_sum.py)
|
||||||
* [Allocation Number](maths/allocation_number.py)
|
* [Allocation Number](maths/allocation_number.py)
|
||||||
* [Arc Length](maths/arc_length.py)
|
* [Arc Length](maths/arc_length.py)
|
||||||
|
@ -581,12 +588,15 @@
|
||||||
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
|
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
|
||||||
* [Pollard Rho](maths/pollard_rho.py)
|
* [Pollard Rho](maths/pollard_rho.py)
|
||||||
* [Polynomial Evaluation](maths/polynomial_evaluation.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)
|
* [Power Using Recursion](maths/power_using_recursion.py)
|
||||||
* [Prime Check](maths/prime_check.py)
|
* [Prime Check](maths/prime_check.py)
|
||||||
* [Prime Factors](maths/prime_factors.py)
|
* [Prime Factors](maths/prime_factors.py)
|
||||||
* [Prime Numbers](maths/prime_numbers.py)
|
* [Prime Numbers](maths/prime_numbers.py)
|
||||||
* [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py)
|
* [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py)
|
||||||
* [Primelib](maths/primelib.py)
|
* [Primelib](maths/primelib.py)
|
||||||
|
* [Print Multiplication Table](maths/print_multiplication_table.py)
|
||||||
* [Proth Number](maths/proth_number.py)
|
* [Proth Number](maths/proth_number.py)
|
||||||
* [Pythagoras](maths/pythagoras.py)
|
* [Pythagoras](maths/pythagoras.py)
|
||||||
* [Qr Decomposition](maths/qr_decomposition.py)
|
* [Qr Decomposition](maths/qr_decomposition.py)
|
||||||
|
@ -676,12 +686,15 @@
|
||||||
* [Magicdiamondpattern](other/magicdiamondpattern.py)
|
* [Magicdiamondpattern](other/magicdiamondpattern.py)
|
||||||
* [Maximum Subarray](other/maximum_subarray.py)
|
* [Maximum Subarray](other/maximum_subarray.py)
|
||||||
* [Nested Brackets](other/nested_brackets.py)
|
* [Nested Brackets](other/nested_brackets.py)
|
||||||
|
* [Pascal Triangle](other/pascal_triangle.py)
|
||||||
* [Password Generator](other/password_generator.py)
|
* [Password Generator](other/password_generator.py)
|
||||||
|
* [Quine](other/quine.py)
|
||||||
* [Scoring Algorithm](other/scoring_algorithm.py)
|
* [Scoring Algorithm](other/scoring_algorithm.py)
|
||||||
* [Sdes](other/sdes.py)
|
* [Sdes](other/sdes.py)
|
||||||
* [Tower Of Hanoi](other/tower_of_hanoi.py)
|
* [Tower Of Hanoi](other/tower_of_hanoi.py)
|
||||||
|
|
||||||
## Physics
|
## Physics
|
||||||
|
* [Archimedes Principle](physics/archimedes_principle.py)
|
||||||
* [Casimir Effect](physics/casimir_effect.py)
|
* [Casimir Effect](physics/casimir_effect.py)
|
||||||
* [Centripetal Force](physics/centripetal_force.py)
|
* [Centripetal Force](physics/centripetal_force.py)
|
||||||
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.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)
|
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
|
||||||
* [Potential Energy](physics/potential_energy.py)
|
* [Potential Energy](physics/potential_energy.py)
|
||||||
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.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
|
## Project Euler
|
||||||
* Problem 001
|
* Problem 001
|
||||||
|
|
|
@ -19,74 +19,72 @@ class EditDistance:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.__prepare__()
|
self.word1 = ""
|
||||||
|
self.word2 = ""
|
||||||
|
self.dp = []
|
||||||
|
|
||||||
def __prepare__(self, n=0, m=0):
|
def __min_dist_top_down_dp(self, m: int, n: int) -> int:
|
||||||
self.dp = [[-1 for y in range(0, m)] for x in range(0, n)]
|
if m == -1:
|
||||||
|
return n + 1
|
||||||
def __solve_dp(self, x, y):
|
elif n == -1:
|
||||||
if x == -1:
|
return m + 1
|
||||||
return y + 1
|
elif self.dp[m][n] > -1:
|
||||||
elif y == -1:
|
return self.dp[m][n]
|
||||||
return x + 1
|
|
||||||
elif self.dp[x][y] > -1:
|
|
||||||
return self.dp[x][y]
|
|
||||||
else:
|
else:
|
||||||
if self.a[x] == self.b[y]:
|
if self.word1[m] == self.word2[n]:
|
||||||
self.dp[x][y] = self.__solve_dp(x - 1, y - 1)
|
self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1)
|
||||||
else:
|
else:
|
||||||
self.dp[x][y] = 1 + min(
|
insert = self.__min_dist_top_down_dp(m, n - 1)
|
||||||
self.__solve_dp(x, y - 1),
|
delete = self.__min_dist_top_down_dp(m - 1, n)
|
||||||
self.__solve_dp(x - 1, y),
|
replace = self.__min_dist_top_down_dp(m - 1, n - 1)
|
||||||
self.__solve_dp(x - 1, y - 1),
|
self.dp[m][n] = 1 + min(insert, delete, replace)
|
||||||
)
|
|
||||||
|
|
||||||
return self.dp[x][y]
|
return self.dp[m][n]
|
||||||
|
|
||||||
def solve(self, a, b):
|
def min_dist_top_down(self, word1: str, word2: str) -> int:
|
||||||
if isinstance(a, bytes):
|
"""
|
||||||
a = a.decode("ascii")
|
>>> 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))]
|
||||||
|
|
||||||
if isinstance(b, bytes):
|
return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1)
|
||||||
b = b.decode("ascii")
|
|
||||||
|
|
||||||
self.a = str(a)
|
def min_dist_bottom_up(self, word1: str, word2: str) -> int:
|
||||||
self.b = str(b)
|
"""
|
||||||
|
>>> EditDistance().min_dist_bottom_up("intention", "execution")
|
||||||
|
5
|
||||||
|
>>> EditDistance().min_dist_bottom_up("intention", "")
|
||||||
|
9
|
||||||
|
>>> EditDistance().min_dist_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)]
|
||||||
|
|
||||||
self.__prepare__(len(a), len(b))
|
for i in range(m + 1):
|
||||||
|
for j in range(n + 1):
|
||||||
return self.__solve_dp(len(a) - 1, len(b) - 1)
|
if i == 0: # first string is empty
|
||||||
|
self.dp[i][j] = j
|
||||||
|
elif j == 0: # second string is empty
|
||||||
def min_distance_bottom_up(word1: str, word2: str) -> int:
|
self.dp[i][j] = i
|
||||||
"""
|
elif word1[i - 1] == word2[j - 1]: # last characters are equal
|
||||||
>>> min_distance_bottom_up("intention", "execution")
|
self.dp[i][j] = self.dp[i - 1][j - 1]
|
||||||
5
|
else:
|
||||||
>>> min_distance_bottom_up("intention", "")
|
insert = self.dp[i][j - 1]
|
||||||
9
|
delete = self.dp[i - 1][j]
|
||||||
>>> min_distance_bottom_up("", "")
|
replace = self.dp[i - 1][j - 1]
|
||||||
0
|
self.dp[i][j] = 1 + min(insert, delete, replace)
|
||||||
"""
|
return self.dp[m][n]
|
||||||
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]
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
@ -99,7 +97,7 @@ if __name__ == "__main__":
|
||||||
S2 = input("Enter the second string: ").strip()
|
S2 = input("Enter the second string: ").strip()
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print(f"The minimum Edit Distance is: {solver.solve(S1, S2)}")
|
print(f"The minimum edit distance is: {solver.min_dist_top_down(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_bottom_up(S1, S2)}")
|
||||||
print()
|
print()
|
||||||
print("*************** End of Testing Edit Distance DP Algorithm ***************")
|
print("*************** End of Testing Edit Distance DP Algorithm ***************")
|
||||||
|
|
Loading…
Reference in New Issue
Block a user