Как исправить несогласованную инструкцию возврата в python? - PullRequest
0 голосов
/ 20 февраля 2019

Я новичок в Python, и у меня есть этот проект. Я работаю над небольшим проектом с двумя функциями, первая из которых возвращает индекс первого раза, когда в строке обнаруживается разница.Следующая функция делает это, но в списке строк.Теперь, из-за того, что я любитель, я использовал чрезмерное количество операторов if и else, что привело к слишком большому количеству операторов return, особенно во второй функции, и я получаю ошибку [R1710: inconsistent-return-операторов].Как я могу это исправить, и кто-нибудь может дать мне четкие примеры для лучших кусков кода?Извините за столь длинный вопрос.

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.
    """
    len1 = len(line1)
    len2 = len(line2)
    minimum_length = min(len1, len2)

    if len1 != len2:
        if minimum_length == 0:
            return 0
        for idx in range(minimum_length):
            if line1[idx] == line2[idx]:
                pass
            else:
                return idx
        return idx + 1

    for idx in range(len1):
        if line1[idx] == line2[idx]:
            pass
        else:
            return idx
    return IDENTICAL

def multiline_diff(lines1, lines2):
    """
    Inputs:
      lines1 - list of single line strings
      lines2 - list of single line strings
    Output:
      Returns a tuple containing the line number (starting from 0) and
      the index in that line where the first difference between lines1
      and lines2 occurs.

      Returns (IDENTICAL, IDENTICAL) if the two lists are the same.
    """
    line_no = singleline_diff(lines1, lines2)

    len_lines1, len_lines2 = len(lines1), len(lines2)

    if len_lines1 == len_lines2:

        if (len_lines1 or len_lines2) == 0:
            if len_lines1 == len_lines2:
                return (IDENTICAL, IDENTICAL)
            else:
                idx = singleline_diff(lines1[line_no], lines2[line_no])
                return (line_no, idx)

        else:
            idx = singleline_diff(lines1[line_no], lines2[line_no])

            if line_no == IDENTICAL:
                return (IDENTICAL, IDENTICAL)
            elif line_no != IDENTICAL:
                return (line_no, idx)

    else:
        return (line_no, 0)

1 Ответ

0 голосов
/ 20 февраля 2019

Посмотрите на код здесь:

if len_lines1 == len_lines2:
    return (IDENTICAL, IDENTICAL)
else:
    idx = singleline_diff(lines1[line_no], lines2[line_no])
    return (line_no, idx)

Вы могли бы написать вышеупомянутую вещь как:

if len_lines1 == len_lines2:
    return (IDENTICAL, IDENTICAL)
idx = singleline_diff(lines1[line_no], lines2[line_no])
return (line_no, idx)

Вам просто не нужен блок else, чтобы вернуть это выражение какэта часть кода будет вызываться автоматически, если элемент управления не входит в блок if.Надеюсь, это поможет.

...