简体   繁体   English

需要帮助弄清楚为什么我的字符串比较不能通过所有测试用例

[英]Need Help Figuring Out Why My String Comparison Isn't Passing All Test Cases

Write a function called singleline_diff that takes two single line strings. 编写一个名为singleline_diff的函数,该函数需要两个单行字符串。 You may assume that both strings are always a single line and do not contain any newline characters. 您可以假设两个字符串始终都是一行,并且不包含任何换行符。 The function should return the index of the first character that differs between the two lines. 该函数应返回两行之间不同的第一个字符的索引。 If the lines are the same, the function should return the constant IDENTICAL, which is already defined to be -1. 如果行相同,则函数应返回常数IDENTICAL,该常数已经定义为-1。

If the lines are different lengths, but the entire shorter line matches the beginning of the longer line, then the first difference is located at the index that is one past the last character in the shorter line. 如果行的长度不同,但是整个较短的行与较长的行的开头匹配,则第一个差异位于索引处,该索引比较短的行中的最后一个字符晚一个。 In other words, no character after the end of the shorter line is defined to be different than whatever character exists in the longer line at that location. 换句话说,短行末尾的任何字符都没有定义为与该位置的长行中存在的任何字符都不同。

Hints: 1) You do not need to check whether or not the two inputs are a single line or not. 提示:1)您无需检查两个输入是否为单行。 You may assume that they are. 您可能会认为它们是。

2) You should first check the lengths of the two inputs and determine the length of the shorter line. 2)您应该首先检查两个输入的长度,然后确定较短线的长度。

3) Look for differences in the lines up to the last character in the shorter line. 3)查找直到最短行中最后一个字符的行中的差异。

4) If you do not find any differences, think about what you should do in the two possible cases: (1) the lines are the same length and (2) the lines are different lengths. 4)如果您没有发现任何差异,请考虑在两种可能的情况下应该采取的措施:(1)线长相同,(2)线长不同。

I have written up the function as specified in the instructions, and I used a series of conditionals to compare the lengths of the strings. 我已经按照指令中的说明编写了函数,并使用了一系列条件比较字符串的长度。 Once the lengths of the strings have been determined, I then initialize an indexing variable, i to 0, which I use with a for loop to go through the characters of the strings looking for the first difference. 一旦确定了字符串的长度,我便将索引变量i初始化为0,该变量与for循环一起使用以遍历字符串的字符以查找第一个差异。 I use conditional (if, elif, and else) along with returns to return the index where the difference occurred or return IDENTICAL (which equals -1). 我与返回一起使用条件(if,elif和else),以返回发生差异的索引或返回IDENTICAL(等于-1)。

IDENTICAL = -1

def singleline_diff(line1, line2):
    """
    Inputs:
      line1 - first single line string
      line2 - second single line string
    Output:
      Returns the index where the first difference between
      line1 and line2 occurs.

      Returns IDENTICAL if the two lines are the same.
    """
    if len(line1) > len(line2):
      i = 0 
      for i in range(len(line2)):
        if line1[i] == line2[i]:
          i += 1
        elif line1[i] != line2[i]:
          return i
        else:
          return i+1
    elif len(line1) < len(line2):
      i = 0
      for i in range(len(line1)):
        if line1[i] == line2[i]:
          i += 1
        elif line1[i] != line2[i]:
          return i
        else:
          return i+1
    else: #Condition where the lengths of the strings are equal
      i = 0
      for i in range(len(line1)):
        if line1[i] == line2[i]:
          i += 1
        elif line1[i] != line2[i]:
          return i
        else:
          return IDENTICAL

I created six test cases (see below). 我创建了六个测试用例(请参见下文)。 The way my code is written right now, I get half of my test cases correct. 现在,我的代码编写方式使一半的测试用例正确无误。 I am stumped trying to debug where my code is failing to return the expected values. 我在尝试调试我的代码未能返回期望值的位置时遇到了麻烦。

print(singleline_diff("abcd", "abcd")) #Should return -1, instead get None
print(singleline_diff("abcd", "abdf")) #Should return 2 (Works)
print(singleline_diff("1234566", "1234567")) #Should return 6 (works)
print(singleline_diff("123", "1234")) #Should return 3, instead get None
print(singleline_diff("4321", "321")) #Should return 0 (works)
print(singleline_diff("lollejrlke", "lollejrlkefa")) #Should return 10, instead get None

Your for loop runs off the end when it never finds an unequal character (which is the case when one of the strings is the starting substring of the other), so it doesn't hit a return statement, so it will return None . 当您的for循环永远不会找到不相等的字符时(例如,其中一个字符串是另一个字符串的起始子字符串),它就从结尾处结束,因此它不会命中return语句,因此它将返回None

Your else: return IDENTICAL clauses are not hit because if line1[i] == line2[i]: and elif line1[i] != line2[i]: cover all the possible cases for that index. 您的else: return IDENTICAL子句未命中,因为if line1[i] == line2[i]: and elif line1[i] != line2[i]:涵盖了该索引的所有可能情况。

Also, manually incrementing i is redundant, because you are iterating through a range, which already prescribes which number will be given at each iteration. 另外,手动递增i是多余的,因为您要遍历一个范围,该范围已经规定了每次迭代将给出的数字。

Consider something like this: 考虑这样的事情:

def singleline_diff(line1, line2):
    """
    Inputs:
      line1 - first single line string
      line2 - second single line string
    Output:
      Returns the index where the first difference between
      line1 and line2 occurs.

      Returns IDENTICAL if the two lines are the same.
    """
    if len(line1) > len(line2):
        for i in range(len(line2)):
            if line1[i] != line2[i]:
                return i
        # We've checked all the characters in the range and found no differences
        # but we know line1 is longer, so this is the position at which they differ
        return len(line2)
    elif len(line1) < len(line2):
        for i in range(len(line1)):
            if line1[i] != line2[i]:
                return i
        return len(line1)
    else:
        for i in range(len(line1)):
            if line1[i] != line2[i]:
                return i
        # They're the same length, and we've found no differences,
        # therefore the strings are identical
        return IDENTICAL

You can further simplify this and only write the for loop once. 您可以进一步简化此操作,只需编写一次for循环。

def singleline_diff(line1, line2):
    end = min(len(line1), len(line2))
    for i in range(end):
        if line1[i] != line2[i]:
            return i
    if len(line1) != len(line2):
        return end
    return IDENTICAL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 需要帮助弄清楚为什么我的骰子游戏计数器不正确 - Need help figuring out why my dice game counter isn't accurate 在我的功能无法正常工作时需要帮助(PYTHON) - Need help figuring out while my function isn't working (PYTHON) 需要帮助弄清楚为什么我的csv输出为空白吗? - Need help figuring out why my csv output is blank? 我需要帮助弄清楚为什么我的正则表达式似乎不确定 - I need help figuring out why my regular expression doesn't seem deterministic 需要帮助找出为什么这行不通 - Need help figuring out why this wont work 需要深入了解为什么我的 Python 函数没有对字符串进行正确的比较 - Need insight into why my Python function isn't doing a proper comparison of strings 按钮在 pygame 中无法正常工作,需要帮​​助找出为什么它们不动态更改文本 - buttons arent working correctly in pygame, need help figuring out why they dont dynamically change the text 需要帮助了解为什么我的find()方法的使用没有正确执行 - Need Help Understanding Why My Usage of the find() Method Isn't Executing Correctly 需要帮助弄清楚为什么方法 update_sitting 和 custmor_increment 没有按照它们应该的方式添加和打印 - need help figuring out why method updating_sitting and custmor_increment are not adding and printing out the way they should 需要帮助找出python脚本的最后一部分 - Need Help figuring out last part of python script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM