Levenshein distance minimum editing Distance Algorithm Implementation

Source: Internet
Author: User

Levenshein distance, the Chinese name is the minimum editing distance, which aims to find the number of characters to be changed between two strings and then become consistent. The algorithm uses a dynamic programming algorithm. This problem has the optimal sub-structure. The minimum editing distance includes the minimum editing distance of the sub-part. The following formula is provided.


Where d [I-1, J] + 1 represents string S2 insert a letter, d [I, J-1] + 1 represents string S1 delete a letter, then when xi = YJ, no cost, so the price is the same as the price of the previous d [I-1, J-1]; otherwise + 1, then d [I, j] is the smallest of the above three.

Algorithm Implementation (Python ):

Assume that the two strings are S1 and S2, and their lengths are M and N. First, apply for a matrix (m + 1) * (n + 1, initialize the first row and the first column, d [I, 0] = I, d [0, J] = J, and then find other elements in the matrix according to the formula, the editing distance between two strings is the value of d [n, m]. The Code is as follows:

#!/usr/bin/env python# -*- coding: utf-8 -*-__author__ = 'xanxus's1, s2 = raw_input('String 1:'), raw_input('String 2:')m, n = len(s1), len(s2)colsize, matrix = m + 1, []for i in range((m + 1) * (n + 1)):    matrix.append(0)for i in range(colsize):    matrix[i] = ifor i in range(n + 1):    matrix[i * colsize] = ifor i in range(n + 1)[1:n + 1]:    for j in range(m + 1)[1:m + 1]:        cost = 0        if s1[j - 1] == s2[i - 1]:            cost = 0        else:            cost = 1        minValue = matrix[(i - 1) * colsize + j] + 1        if minValue > matrix[i * colsize + j - 1] + 1:            minValue = matrix[i * colsize + j - 1] + 1        if minValue > matrix[(i - 1) * colsize + j - 1] + cost:            minValue = matrix[(i - 1) * colsize + j - 1] + cost        matrix[i * colsize + j] = minValueprint matrix[n * colsize + m]


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.