[英]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.