TheAlgorithms-Python
32 строки · 1.1 Кб
1def edit_distance(source: str, target: str) -> int:2"""3Edit distance algorithm is a string metric, i.e., it is a way of quantifying how
4dissimilar two strings are to one another. It is measured by counting the minimum
5number of operations required to transform one string into another.
6
7This implementation assumes that the cost of operations (insertion, deletion and
8substitution) is always 1
9
10Args:
11source: the initial string with respect to which we are calculating the edit
12distance for the target
13target: the target string, formed after performing n operations on the source string
14
15>>> edit_distance("GATTIC", "GALTIC")
161
17"""
18if len(source) == 0:19return len(target)20elif len(target) == 0:21return len(source)22
23delta = int(source[-1] != target[-1]) # Substitution24return min(25edit_distance(source[:-1], target[:-1]) + delta,26edit_distance(source, target[:-1]) + 1,27edit_distance(source[:-1], target) + 1,28)29
30
31if __name__ == "__main__":32print(edit_distance("ATCGCTG", "TAGCTAA")) # Answer is 433