Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5.3:最小编辑距离 #462

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions ebook/code/python/5.3:字符串编辑距离.py
Original file line number Diff line number Diff line change
@@ -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)