为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥6287543 2022-01-18 20:58:55
给定 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 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

这实际上是一个缩进问题。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


查看完整回答
反对 回复 2022-01-18
  • 1 回答
  • 0 关注
  • 201 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号