[英]Matching substring in the same place on two different strings?
I have been trying to solve one of the codingbat problem in Python.我一直在尝试解决 Python 中的一个编码问题。
Here is the problem definition:这是问题定义:
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring.
给定 2 个字符串 a 和 b,返回它们包含相同长度 2 substring 的位置数。 So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
所以 "xxcaazz" 和 "xxbaaz" 得到 3,因为 "xx"、"aa" 和 "az" 子字符串出现在两个字符串中的相同位置。
string_match('xxcaazz', 'xxbaaz') → 3
string_match('xxcaazz', 'xxbaaz') → 3
string_match('abc', 'abc') → 2
string_match('abc', 'abc') → 2
string_match('abc', 'axc') → 0
string_match('abc', 'axc') → 0
Here is my code for it:这是我的代码:
def string_match(a, b):
count = 0
for i in range(len(a)-1):
for j in range(len(b)-1):
if a[i:i+2] == b[j:j+2]:
count += 1
return count
The output from Above code:上述代码中的 output:
I could not figure out what is wrong with my code.我无法弄清楚我的代码有什么问题。
Hope you can help me out.希望你能帮助我。 Looking forward for the response.
期待回复。
This should do the work, passed all your test cases.这应该可以完成工作,通过了所有测试用例。
def string_match(a, b):
found = 0
for i in range(min([len(a), len(b)])-1):
if a[i] == b[i] and a[i+1] == b[i+1]:
found += 1
return found
print(string_match('iaxxai', 'aaxxaaxx'))
You dont need to split the string, you only need to check if the chars at i
and i + 1
are equal.您不需要拆分字符串,您只需要检查
i
和i + 1
处的字符是否相等。 If you would like to check it for n
length, you might need an inner loop.如果您想检查它的
n
长度,您可能需要一个内部循环。 Also it works for len(a) != len(b)
.它也适用于
len(a) != len(b)
。
def string_match(a, b): shorter = min(len(a), len(b)) count = 0 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.