From b9f34f62d0e643aaba4580a765719545d5ac39cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=A5=BC=E4=B8=80=E5=A4=9C=E5=90=AC=E6=98=A5?= =?UTF-8?q?=E9=9B=A8?= <674361437@qq.com> Date: Wed, 22 Aug 2018 21:21:54 +0800 Subject: [PATCH] =?UTF-8?q?Create=205.3=EF=BC=9A=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E7=BC=96=E8=BE=91=E8=B7=9D=E7=A6=BB.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...26\350\276\221\350\267\235\347\246\273.py" | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 "ebook/code/python/5.3\357\274\232\345\255\227\347\254\246\344\270\262\347\274\226\350\276\221\350\267\235\347\246\273.py" diff --git "a/ebook/code/python/5.3\357\274\232\345\255\227\347\254\246\344\270\262\347\274\226\350\276\221\350\267\235\347\246\273.py" "b/ebook/code/python/5.3\357\274\232\345\255\227\347\254\246\344\270\262\347\274\226\350\276\221\350\267\235\347\246\273.py" new file mode 100644 index 000000000..9d6350a46 --- /dev/null +++ "b/ebook/code/python/5.3\357\274\232\345\255\227\347\254\246\344\270\262\347\274\226\350\276\221\350\267\235\347\246\273.py" @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +最小编辑距离 +""" +def Edit_Distance(src, tar): + srcLength = len(src) + tarLength = len(tar) + matrix = [[i+j for j in range(tarLength + 1)] for i in range(srcLength + 1)] + for i in range(1,srcLength+1): + matrix[i][0] = i + for j in range(1,tarLength+1): + matrix[0][j] = j + for i in range(1,srcLength+1): + for j in range(1,tarLength+1): + if src[i-1] == tar[j-1]: + matrix[i][j] = matrix[i-1][j-1] + else: + matrix[i][j] =min(matrix[i-1][j-1] +1, 1+ min(matrix[i-1][j], matrix[i][j-1])) + for i in matrix: + print(i) + print(matrix[srcLength][tarLength]) + return matrix[srcLength][tarLength] + +if __name__ == "__main__": + # src = 'abddcdefdgbd22svb' + # tar = 'bcdefg34rdyvdfsd' + # src = 'ofailing' + # tar = 'osailn' + src = "string" + tar = "story" + Edit_Distance(src, tar)