简体   繁体   English

给定 2 个字符串,返回两个字符串包含相同长度的位置数 2 substring

[英]Given 2 strings, return number of positions where the two strings contain the same length 2 substring

here is my code:这是我的代码:

def string_match(a, b):
  count = 0

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

  for i in range(len(a)):
    if a[i:i+2] == b[i:i+2]:
      count = count + 1
  return count

And here are the results:结果如下:

在此处输入图像描述

Correct me if I am wrong but, I see that it didn't work probably because the two string lengths are the same.如果我错了请纠正我,但我发现它不起作用可能是因为两个字符串长度相同。 If I were to change the for loop statement to:如果我将 for 循环语句更改为:

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

then it would work for all cases provided.那么它将适用于所有提供的案例。 But can someone explain to me why adding the -1 makes it work?但是有人可以向我解释为什么添加 -1 可以使它起作用吗? Perhaps I'm comprehending how the for loop works in this case.也许我正在理解 for 循环在这种情况下的工作方式。 And can someone tell me a more optimal way to write this because this is probably really bad code.谁能告诉我一种更优化的写法,因为这可能是非常糟糕的代码。 Thank you!谢谢!

But can someone explain to me why adding the -1 makes it work?但是有人可以向我解释为什么添加-1可以使它起作用吗?

Observe:观察:

test = 'food'
i = len(test) - 1
test[i:i+2] # produces 'd'

Using len(a) as your bound means that len(a) - 1 will be used as an i value, and therefore a slice is taken at the end of a that would extend past the end.使用len(a)作为您的边界意味着len(a) - 1将用作i值,因此在 a 的末尾获取a切片,该切片将延伸到末尾。 In Python, such slices succeed , but produce fewer characters.在 Python 中,这样的切片成功,但产生的字符较少。

String slicing can return strings that are shorter than requested.字符串切片可以返回比请求的字符串更短的字符串。 In your first failing example that checks "abc" against "abc", in the third iteration of the for loop, both a[i:i+2] and b[i:i+2] are equal to "c", and therefore count is incremented.在第一个检查“abc”与“abc”的失败示例中,在 for 循环的第三次迭代中, a[i:i+2]b[i:i+2]都等于“c”,并且因此计数增加。

Using range(len(a)-1) ensures that your loop stops before it gets to a slice that would be just one letter long.使用range(len(a)-1)可确保您的循环在到达只有一个字母长的切片之前停止。

Since the strings may be of different lengths, you want to iterate only up to the end of the shortest one.由于字符串的长度可能不同,因此您只想迭代到最短字符串的末尾。 In addition, you're accessing i+2 , so you only want i to iterate up to the index before the last item (otherwise you might get a false positive at the end of the string by going off the end and getting a single-character string).此外,您正在访问i+2 ,因此您只希望i迭代到最后一项之前的索引(否则您可能会在字符串末尾通过结束并获得单 -字符串)。

def string_match(a: str, b: str) -> int:
    return len([
        a[i:i+2]
        for i in range(min(len(a), len(b)) - 1)
        if a[i:i+2] == b[i:i+2]
    ])

(You could also do this counting with a sum , but this makes it easy to get the actual matches as well!) (您也可以使用sum进行此计数,但这也可以轻松获得实际匹配项!)

You can use this:你可以使用这个:

def string_match(a, b):
    if len(a) < 2 or len(b) < 0:
        return 0

    subs = [a[i:i+2] for i in range(len(a)-1)]
    occurence = list(map(lambda x: x in b, subs))

    return occurence.count(True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从两个字符串返回具有相同长度的交替字母 - Return Alternating Letters With the Same Length From two Strings 计算恰好一次包含给定单词的固定长度字符串的数量 - Calculate the number of fixed-length strings that contain a given word exactly once 根据它们所在的位置用两个不同的字符串替换一个子字符串 - Replace a substring with two different strings depending on where they are 在两个不同字符串的同一位置匹配 substring? - Matching substring in the same place on two different strings? 计算包含两个精确字符串的行数 - Count number of row that contain two exact strings 给定两个字符串列表,找出第二个列表中包含第一个列表中的任何字符串作为子字符串的字符串总数 - Given two lists of strings, find the total number of strings in the second list which contains any string in the first list as substring 检查两个字符串是否在python中包含相同的模式 - Check if two strings contain the same pattern in python 正则表达式匹配两个字符串,字符串之间有给定数量的单词 - Regex match two strings with given number of words in between strings 在具有相同和不同位置的两个字符串中查找匹配字符 - Find matching characters in two strings with same and different positions 在负位置提前搜索在特定位置出现子字符串的字符串 - Searching strings where substring occur at specific positions with negative look-ahead
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM