【问题标题】:Expected type 'int' but returned type 'NoneType'."预期类型为“int”,但返回类型为“NoneType”。”
【发布时间】:2018-04-10 22:21:34
【问题描述】:

我必须编写一个 python 函数,该函数将两个单行字符串作为输入并返回两者之间出现第一个差异的索引(如果它们相同,则返回负数)。这是我目前写的代码:

def singleline_diff(line1, line2):
    len1 = len(line1)
    len2 = len(line2)
    if len1 < len2:
        min_len = len1
    elif len1 > len2:
        min_len = len2
    else:
        min_len = len1
    indx1 = 0
    indx2 = 0
    if line1 == line2:
        return IDENTICAL
    elif line1 != line2:
        if min_len == len1:
            for word2 in line2:
                word2 = line2 [indx2]
                indx2 = indx2+1
                if word2 not in line1:
                    diff_idx_2 = int(indx2)
                    print (diff_idx_2)
        elif min_len == len2:
            for word1 in line1:
                word1 = line1 [indx1]
                indx1=indx1+1
                if word1 not in line2:
                    diff_idx_1 = int(indx1)
                    print (diff_idx_1)

【问题讨论】:

    标签: python-3.6 nonetype


    【解决方案1】:

    如果 line1 != line2,您的代码会将整数打印到控制台,而不是返回值,这是根据文档应该执行的操作。尝试return diff_idx_2 而不是print(diff_idx_2)(对于 diff_idx_1 也是如此)。

    【讨论】:

      【解决方案2】:
      def singleline_diff(line1, line2):
      
          min_len = min(len(line1), len(line2))
          for i in range(min_len):
              if line1[i] != line2[i]:
                  return i
      
          if min_len == len(line1) and min_len == len(line2):
              return -1      # they're identical
          return min_len     # one of the two lines has terminated, hence they differ
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 2017-06-14
        • 2021-07-09
        • 2019-10-16
        • 1970-01-01
        • 2013-12-16
        • 1970-01-01
        相关资源
        最近更新 更多