0
点赞
收藏
分享

微信扫一扫

语法练习:string_match

ixiaoyang8 2022-12-07 阅读 134
python

语法练习:string_match

题目:string_match

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

我的解答:

def string_match(a, b):
  count = 0
  if len(a) < 2 or len(b) < 2:
    return 0
  else:
    for i in range(min(len(a),len(b)) - 1):
      sub_a = a[i:i+2]
      sub_b = b[i:i+2]
      if sub_a == sub_b:
        count += 1
    return count

Expected Run
string_match(‘xxcaazz’, ‘xxbaaz’) → 3 3 OK
string_match(‘abc’, ‘abc’) → 2 2 OK
string_match(‘abc’, ‘axc’) → 0 0 OK
string_match(‘hello’, ‘he’) → 1 1 OK
string_match(‘he’, ‘hello’) → 1 1 OK
string_match(‘h’, ‘hello’) → 0 0 OK
string_match(‘’, ‘hello’) → 0 0 OK
string_match(‘aabbccdd’, ‘abbbxxd’) → 1 1 OK
string_match(‘aaxxaaxx’, ‘iaxxai’) → 3 3 OK
string_match(‘iaxxai’, ‘aaxxaaxx’) → 3 3 OK

All Correct

标答:

def string_match(a, b):
  # Figure which string is shorter.
  shorter = min(len(a), len(b))
  count = 0
  
  # Loop i over every substring starting spot.
  # Use length-1 here, so can use char str[i+1] in the loop
  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
举报

相关推荐

0 条评论