Codingbat练习中是否存在错误:Warmup-2> string_match?还是我的代码有什么问题?

问题描述 投票:0回答:1

练习题(链接:https://codingbat.com/prob/p182414):

给出2个字符串a和b,返回其中它们包含相同长度的2个子字符串。因此,“ xxcaazz”和“ xxbaaz”产生3,因为“ xx”,“ aa”和“ az”子字符串出现在相同的位置放在两个字符串中。

string_match('xxcaazz','xxbaaz')→3 string_match('abc','abc')→2string_match('abc','axc')→0

我的代码:

def string_match(a, b):
  lista = []
  listb = []
  for i in range(len(a)-1):
    itema = a[i:i+2]
    if itema not in lista:
      lista.append(itema)

  for i in range(len(b)-1):
    itemb = b[i:i+2]
    if itemb not in listb:
      listb.append(itemb)

  list=[]
  count = 0
  for item in lista:
    if item in listb and item not in list:
      list.append(item)
      count = count + 1

  return count

结果:请参阅所附图片

[1]:https://i.stack.imgur.com/Bfz9U.png

我的问题:对于string_match('aabbccdd','abbbxxd'),运行结果为2,即“ ab”和“ bb”?

python
1个回答
0
投票

据我所知,两个子字符串必须位于相同的索引处。即:

“” abcd“和” xabcd“将返回0,但是,

“” abdc“和” abcdc“将返回1,因为两个字符串中的” ab“处于相同的索引,但是两个字符串中的” dc“处于不同的索引]

因此,“ aabbccdd”和“ abbbxxd”将仅返回1,因为两个字符串中的“ ab”具有不同的索引,但是两个字符串中的“ bb”具有相同的索引

© www.soinside.com 2019 - 2024. All rights reserved.