Skip to content
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
68 changes: 68 additions & 0 deletions projects/003-string-edit-distance/python/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
'''
The edit distance between two strings is a measure of their similarity.

The smaller the edit distance, the more similar the strings are with regard to the minimum number of insert,
delete and substitute operations needed to transform one string into the other.

Consider the strings kitten and sitting.
The first string can be transformed into the second string with the following operations:
Substitute the k with an s, substitute the e with an i, and insert a g at the end of the string.
This is the smallest number of operations that can be performed to transform kitten into sitting.

As a result, the edit distance is 3.

Write a recursive function that computes the edit distance between two strings.

Use the following algorithm:

Let s and t be the strings

If the length of s is 0 then
Return the length of t

Else if the length of t is 0 then
Return the length of s

Else
Set cost to 0

If the last character in s does not equal the last character in t then

Set cost to 1
Set d1 equal to the edit distance between all characters except the last one
in s, and all characters in t, plus 1
Set d2 equal to the edit distance between all characters in s, and all
characters except the last one in t, plus 1
Set d3 equal to the edit distance between all characters except the last one
in s, and all characters except the last one in t, plus cost Return the minimum of d1, d2 and d3



Use your recursive function to write a program that reads two strings from the user and displays the edit distance between them.
'''

def editdistance(s, t):
if len(s) == 0:
return len(t)
elif len(t) == 0:
return len(s)
else:
cost = 0

if s[-1] != t[-1]:
cost = 1

d1 = editdistance(s[:-1], t) + 1
d2 = editdistance(s, t[:-1]) + 1
d3 = editdistance(s[:-1], t[:-1]) + cost

return min(d1, d2, d3)

def main():
s = input("Please input first string: ")
t = input("Please input second string: ")
x = editdistance(s, t)
print(x)

if __name__ == '__main__':
main()