首页 > 编程学习 > 语法练习:string_match

语法练习:string_match

发布时间:2022/12/7 17:28:56

语法练习: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 = 0if len(a) < 2 or len(b) < 2:return 0else: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 += 1return 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 loopfor i in range(shorter-1):a_sub = a[i:i+2]b_sub = b[i:i+2]if a_sub == b_sub:count = count + 1return count

本文链接:https://www.ngui.cc/article/show-738632.html
Copyright © 2010-2022 ngui.cc 版权所有 |关于我们| 联系方式| 豫B2-20100000