单个字母插入或删除功能

时间:2016-02-24 09:54:54

标签: python

编写一个名为single_insert_or_delete的函数,它接受两个字符串作为输入参数并返回:

如果两个字符串完全匹配,则

0。 如果第一个字符串可以通过插入或删除单个字符与第二个字符串相同,则为1。请注意,插入和删除字符与替换字符不同。 2否则

Problem statement

这就是我到目前为止所得到的

def single_insert_or_delete (word1,word2):
    word1=word1.lower()
    word2=word2.lower()
    limit=min(len(word1),len(word2))
    list1=[]
    list2=[]
    common=[]
    if word1==word2:
        return 0
    for i in range(0,len(word1)):
        list1.append(word1[i])
    for k in range(0,len(word2)):
        list2.append(word2[k])
    if abs(len(word1)-len(word2))==1:
        for c in range(0,limit+1):
            if list1[c]==list2[c] or list1[c]==list2[c+1] or   list1[c+1]==list2[c]:
                return 1
            else:
                return 2
    else:
         return 2

它实际上运作良好但是如果你尝试过像''那样的棘手的话。并且'那'它会给1而不是2这是错误的

2 个答案:

答案 0 :(得分:1)

我不确定您是否想要如何来完成它,或者您是否只想解决它,但如果后者可以使用difflib.ndiff()

from difflib import ndiff

def single_insert_or_delete(word1, word2):
    change_count = sum(1 for s in ndiff(word1.lower(), word2.lower()) if (s[0] == '-' or s[0] == '+'))
    if change_count > 1:
        return 2
    return change_count

word_pairs = [('Python', 'Java'), ('book', 'boot'), ('sin', 'sink'), ('dog', 'Dog'), ('poke', 'spoke'), ('poker', 'poke'), ('programing', 'programming')]

for pair in word_pairs:
    print('{}: {}'.format(single_insert_or_delete(*pair), pair))

<强>输出

2: ('Python', 'Java')
2: ('book', 'boot')
1: ('sin', 'sink')
0: ('dog', 'Dog')
1: ('poke', 'spoke')
1: ('poker', 'poke')
1: ('programing', 'programming')

答案 1 :(得分:0)

你可能必须在for循环之外返回并重新检查if中的比较逻辑。

对于范围内的c(0,限制+ 1):

        if (list1[c]==list2[c] or list1[c]==list2[c+1] or list1[c+1]==list2[c]):
              return 1

这里的问题是,当比较单词(the和this)时,它满足t等于t的第一个条件,并进入if条件,返回1并退出函数。它不会继续使用for循环。

如果你想要类似的东西而不是difflib,你也可以使用以下代码。

import numpy


def single_insert_or_delete(s1,s2):

    s1 = s1.lower()
    s2 = s2.lower()

    l1 = [i for i in s1] # convert the string into an array
    l2 = [j for j in s2] # convert the second string in an array

    if s1 == s2:
        flag = 0

    elif abs(len(s1)-len(s2)) == 1:
        if len(l2) > len(l1):
            l1,l2 = l2,l1
        l3 = list(numpy.in1d(l1,l2)) 
    # This will compare the elements of 2 arrays and return bool values based on the match

        if l3.count(False) > 1: # count the number of false values
            flag = 2
        else:
            flag = 1
    else:
        flag = 2

    return flag


print "Output-1 ", single_insert_or_delete("book","boot")
print "Output-2 ", single_insert_or_delete("Java","Python")
print "Output-3 ", single_insert_or_delete("dog","Dog")
print "Output-4 ", single_insert_or_delete("sin","sink")
print "Output-5 ", single_insert_or_delete("programming","programing")

输出:

C:\ Python27 \ python.exe D:/Python/Mylist.py

输出-1 2

输出-2 2

输出-3 0

输出-4 1

输出-5 1

处理完成,退出代码为0