2016-02-25 72 views
1
if s1 == s2: 
    return 0 


elif len(s1) == len(s2): 
    mismatch = 0 
    for i,j in zip(s1,s2): 
     if i != j: 
      mismatch +=1 

    if mismatch == 1: 
     return 1 

elif len(s1) != len(s2): 
    mismatch = 0 
    for i,j in zip(s1,s2): 
     if i != j: 
      mismatch +=1 

    if mismatch > 1: 
     return 2 

我被要求编写一个代码,比较两个字符串,这些字符串将作为函数的参数接收。在遍历它们时,如果它们都相同,则必须返回0;如果一个字符中存在不匹配,则返回1;如果两个字符的长度不相同,或者超过1个字符不匹配,则返回2。匹配字符串中的字符并返回值

当我尝试“罪”和“汇”作为输入字符串,我的代码不返回任何东西?我试图用许多不同的方法来改变我的代码,但它没有帮助。如果字符串中的空格和另一个字符之间存在一个字符的差异,它也不会返回任何内容。

这似乎是一个很简单的一段代码,但我不能似乎将它写的权利。如果我试图通过使用.lower()来解决空间和另一个字符的问题,那么它不会在字符串末尾的'k'处找到。如果我用.upper()修复它,它不会返回任何东西。我没有看到我做错了什么。

+2

可能的重复。有很多。不确定选哪一个。 http://stackoverflow.com/search?q=single_insert_or_delete+is%3Aquestion – Lafexlos

+0

对于“罪” /“汇”问题检查这个问题的答案: [Python的:拉链般的功能垫长度最长] (http://stackoverflow.com/questions/1277278/python-zip-like-function-that-pads-to-longest-length) – alexs

+0

所有我能说的是.... LOL –

回答

0

我认为这是正常的,因为在某些情况下,没有任何返回值的代码没有任何回报:如果长度相等,但是不匹配= 1,并在长度是不同的,但错配< = 1

因为你的榜样“罪”和“汇”你算错配仅在“罪”的一部分,所以在最后的不匹配等于0中

0

此功能可能会被你正在寻找

def match_string(s1,s2): 
s1=s1.lower() 
s2=s2.lower() 
if s1 == s2: 
    return 0 
elif abs(len(s1)-len(s2))<2: 
    mismatch=0 
    for i in range(0,min(len(s1),len(s2))): 
     if s1[i]!=s2[i]: 
      mismatch+=1 
    if mismatch<2: 
     return 1 
    else: 
     return 2 
else: 
    return 2 
+0

感谢您的SANKET!我必须将**空格**作为一个区分字符,这是迄今为止我的代码中唯一剩下的问题。 –

+0

对于** space **问题,删除'replace()'可能适用于你。我将编辑答案。 –

0

这就是终于把它交给工作的原因K:

DEF find_mismatch(S1,S2): 一个=列表(s1.lower()) B =列表(s2.lower()) C = LEN(一) d = LEN(b)中

match = 0 

for char in b: 
    if char in a: 
     match += 1 
     a.remove(char) 

g=list(s1.lower()) 
h=list(s2.lower()) 
i=len(g) 
j=len(h)   

match1 = 0 
for char in g: 
    if char in h: 
     match1 += 1 
     h.remove(char) 

if match == c and match1 == j: 
    return 0 
elif (match == 0 or match1 == 0) and a != h: 
    return 2 
elif a != h and len(a) == len(h): 
    return 1 
elif a != h and len(a) != len(h): 
    return 2 
相关问题