问题以了解为什么代码不起作用

给定 2 个字符串 a 和 b,返回它们包含相同长度的 2 子字符串的位置数。所以 "xxcaazz" 和 "xxbaaz" 得到 3,因为 "xx"、"aa" 和 "az" 子字符串出现在两个字符串中的相同位置。


对于这个问题,我编写了以下代码:


  def string_match(a, b):

     result  = 0

     tiniest = b

     biggest = a

     if len(a) < 2 or len(b) < 2:

      return 0


     if len(a) < len(b):

       tiniest = a

       print('tiniest is {} and size minus 1 equals 

  {}'.format(str(tiniest), len(tiniest)-1))

       biggest = b

     else:

       tiniest = b

       print('ELSE tiniest is {} and size minus 1 equals {}'.format(str(tiniest), len(tiniest) - 1))

       biggest = a


       for i in range(len(tiniest) - 1):

         print(i)

         if tiniest[i:i+2] == biggest[i:i+2]:

             print('tiniest is {} and biggest is {} and i is 

  {}'.format(tiniest[i:i+2], biggest[i:i+2], i))

             result = result + 1

         else:

            continue

         print("result is ",result)

     return result

因此对于测试: string_match('helloooo', 'hello') 或 string_match('hello', 'hello') => 没问题,函数按预期返回 4


但是一旦第一个参数小于第二个参数,就不再起作用了,原因我不明白: string_match('hell', 'hello') => 什么都不做,为什么???


我看不出我的解决方案与这个问题的官方解决方案之间的区别是:


def string_match(a, b):

    # Figure which string is shorter.

    shorter = min(len(a), len(b))

    count = 0


    # Loop i over every substring starting spot.

    # Use length-1 here, so can use char str[i+1] in the loop

    for i in range(shorter - 1):

        a_sub = a[i:i + 2]

        b_sub = b[i:i + 2]

        if a_sub == b_sub:

            count = count + 1


    return count 

也可以 在函数的开头初始化变量结果最小和最大吗?


慕哥6287543
浏览 202回答 1
1回答

潇潇雨雨

这实际上是一个缩进问题。for 循环在 else 缩进中。将 for 循环放在 else 语句的同一级别,解决了它:def string_match(a, b):&nbsp; &nbsp;result&nbsp; = 0&nbsp; &nbsp;tiniest = b&nbsp; &nbsp;biggest = a&nbsp; &nbsp;if len(a) < 2 or len(b) < 2:&nbsp; &nbsp; return 0&nbsp; &nbsp;if len(a) < len(b):&nbsp; &nbsp; &nbsp;tiniest = a&nbsp; &nbsp; &nbsp;print('tiniest is {} and size minus 1 equals {}'.format(str(tiniest), len(tiniest)-1))&nbsp; &nbsp; &nbsp;biggest = b&nbsp; &nbsp;else:&nbsp; &nbsp; &nbsp;tiniest = b&nbsp; &nbsp; &nbsp;print('ELSE tiniest is {} and size minus 1 equals {}'.format(str(tiniest), len(tiniest) - 1))&nbsp; &nbsp; &nbsp;biggest = a&nbsp; &nbsp;for i in range(len(tiniest) - 1):&nbsp; &nbsp; &nbsp;print(i)&nbsp; &nbsp; &nbsp;if tiniest[i:i+2] == biggest[i:i+2]:&nbsp; &nbsp; &nbsp; &nbsp;print('tiniest is {} and biggest is {} and i is {}'.format(tiniest[i:i+2], biggest[i:i+2], i))&nbsp; &nbsp; &nbsp; &nbsp;result = result + 1&nbsp; &nbsp; &nbsp;else:&nbsp; &nbsp; &nbsp; &nbsp;continue&nbsp; &nbsp;print("result is ",result)&nbsp; &nbsp;return result
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python