简体   繁体   中英

Matching substring in the same place on two different strings?

I have been trying to solve one of the codingbat problem in 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. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.

string_match('xxcaazz', 'xxbaaz') → 3

string_match('abc', 'abc') → 2

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:

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. If you would like to check it for n length, you might need an inner loop. Also it works for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM