Python 中的 CodingBat 是否有更简单的方法来完成 string_match?

Is there a simpler way to do string_match from CodingBat in Python?

这就是问题所在。 http://codingbat.com/prob/p182414

总结一下,给定两个字符串(a 和 b)return 字符串 a 中的子字符串 2 在字符串 b 中出现了多少次。例如,string_match('xxcaazz', 'xxbaaz') → 3.

def string_match(a, b):
    amount = 0
    for i in range(len(a)):
        if (len(a[i:i+2]) == 2) and a[i:i+2]  == b[i:i+2]:
            amount += 1
    return amount

没那么简单,但是如果你把i的范围限制在len(a)-1,你就不需要检查它是否定义了足够长的a的子串。

我的做法是这样的:

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