理解为什么代码不起作用的问题

时间:2019-04-23 03:39:30

标签: python python-3.x

给出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 

还可以在函数开始时初始化变量结果最小最大吗?

谢谢

1 个答案:

答案 0 :(得分:0)

这实际上是一个缩进问题。 for循环位于else缩进内部。将for循环置于else语句的相同级别,即可解决该问题:

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