【问题标题】:matching characters in strings and returning values匹配字符串中的字符并返回值
【发布时间】:2016-02-25 09:45:13
【问题描述】:
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。

当我尝试将“sin”和“sink”作为输入字符串时,我的代码没有返回任何内容?我试图以许多不同的方式改变我的代码,但它没有帮助。如果一个字符(如字符串中的空格)与另一个字符不同,它也不会返回任何内容。

这似乎是一段足够简单的代码,但我似乎无法正确编写它。如果我尝试通过使用 .lower() 来解决空格和另一个字符的问题,它不会在字符串末尾包含“k”。如果我用 .upper() 修复它,它不会返回任何东西。我看不出我做错了什么。

【问题讨论】:

标签: python string


【解决方案1】:

我认为您的代码没有返回任何内容是正常的,因为在某些情况下没有任何返回值:如果长度相等但不匹配 != 1 以及长度不同但不匹配

因为在您的示例中,“sin”和“sink”只计算“sin”部分的不匹配,所以最后不匹配等于 0。

【讨论】:

    【解决方案2】:

    这个函数可能就是你要找的

    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
    

    【讨论】:

    • 感谢您提供的 Sanket!我也必须将 space 视为一个区别字符,这是迄今为止我的代码中唯一剩下的问题。
    • 对于 space 问题,删除 replace() 可能对您有用。我将编辑答案。
    【解决方案3】:

    这就是最终让它发挥作用的原因:

    def find_mismatch(s1,s2): 一个=列表(s1.lower()) b=列表(s2.lower()) c=len(a) 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
    

    【讨论】:

      猜你喜欢
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      相关资源
      最近更新 更多