1

这是问题:

给定两个单词中每个单词的字母数相同,计算出从第一个单词到第二个单词需要更改多少个字母。更复杂的编辑距离版本通常用于手机和文字处理器上的拼写自动更正算法,以找到候选更正。

这两个单词应该从用户那里读取,每行一个单词。例如:

Word 1: hello
Word 2: jelly
2

这就是我所得到的:

w1 = input('Word 1: ')
w2 = input('Word 2: ')
for i in w1:
  for o in w2:
    print(i, o)

我该怎么做呢?

4

4 回答 4

6

You can try something like:

sum(c1 != c2 for c1,c2 in zip(w1,w2))

zip(w1,w2) creates a generator that returns tuples consisting of corresponding letters of w1 and w2. i.e.:

>>> list(zip(w1,w2))
[('h', 'j'), ('e', 'e'), ('l', 'l'), ('l', 'l'), ('o', 'y')]

We iterate over these tuples (c1 gets assigned to each first char and c2 to each second char) and check if c1 != c2. We add up all the instances for which this condition is satisfied to arrive at out answer.

(See zip() and sum())


>>> w1 = 'hello'
>>> w2 = 'jelly'
>>> 
>>> sum(c1 != c2 for c1,c2 in zip(w1,w2))
2
于 2013-08-16T15:11:34.170 回答
3

使用difflib

>>> import difflib
>>> w1, w2 = 'hello', 'jelly'
>>> matcher = difflib.SequenceMatcher(None, w1, w2)
>>> m = sum(size for start, end, size in matcher.get_matching_blocks())
>>> n = max(map(len, (w1, w2))) # n = len(w1)
>>> n - m
2
于 2013-08-16T15:12:25.740 回答
2

一种功能性方法:

>>> from itertools import starmap
>>> from operator import ne
>>> sum(starmap(ne, zip(word1, word2)))
2
于 2013-08-16T15:12:30.783 回答
1

如果单词总是相同的长度,您可以使用zip一次循环遍历两个列表:

w1 = input('Word 1: ')
w2 = input('Word 2: ')
changes=0    
    for i, o in zip(w1, w2):
    if i != o:
        changes+=1

print "Changes needed: "+str(changes)
于 2013-08-16T15:14:01.177 回答