Counting length-2 substrings that are common to two strings at the same offset -- Python I solved the CodingBat task:

Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So &quot;xxcaazz&quot; and &quot;xxbaaz&quot;
yields 3, since the &quot;xx&quot;, &quot;aa&quot;, and &quot;az&quot; substrings appear in the same
place in both strings.
stringMatch(&quot;xxcaazz&quot;, &quot;xxbaaz&quot;) → 3  
stringMatch(&quot;abc&quot;, &quot;abc&quot;) → 2  
stringMatch(&quot;abc&quot;, &quot;axc&quot;) → 0


import doctest


def all_two_chars_occurencies(string):
    &quot;&quot;&quot;
    &gt;&gt;&gt; list(all_two_chars_occurencies('abcd'))
    ['ab', 'bc', 'cd']
    &gt;&gt;&gt; list(all_two_chars_occurencies('xxcaazz'))
    ['xx', 'xc', 'ca', 'aa', 'az', 'zz']
    &quot;&quot;&quot;
    for index, char in enumerate(string[:-1]):
        yield char + string[index + 1]


def common_two_chars_occurences(a, b):
    &quot;&quot;&quot;
    Given 2 strings, a and b, return the number of the positions where
    they contain the same length 2 substring.

    &gt;&gt;&gt; common_two_chars_occurences('xxcaazz', 'xxbaaz')
    3
    &gt;&gt;&gt; common_two_chars_occurences('abc', 'abc')
    2
    &gt;&gt;&gt; common_two_chars_occurences('abc', 'axc')
    0
    &quot;&quot;&quot;
    equal_duets = 0
    for a_duet, b_duet in zip(all_two_chars_occurencies(a),
                              all_two_chars_occurencies(b)):
        if a_duet == b_duet:
            equal_duets += 1
    return equal_duets


if __name__ == &quot;__main__&quot;:
    doctest.testmod()
There is no such word as "occurencies".  In any case, all_two_chars_occurencies is a very long name.  I suggest pairwise_chars.  Note that it could also be written in a style similar to the pairwise() recipe in Python's documentation.

In Python, explicit looping is slightly cumbersome.  Fortunately, Python offers many ways to just do what you want as a "one-liner", without looping.  Here's one approach, which uses a generator expression, and this technique to find its length.

def common_two_chars_occurences(a, b):
    """
    Given 2 strings, a and b, return the number of the positions where
    they contain the same length 2 substring.

    &gt;&gt;&gt; common_two_chars_occurences('xxcaazz', 'xxbaaz')
    3
    &gt;&gt;&gt; common_two_chars_occurences('abc', 'abc')
    2
    &gt;&gt;&gt; common_two_chars_occurences('abc', 'axc')
    0
    """
    return sum(1 for pair
                 in zip(pairwise_chars(a), pairwise_chars(b))
                 if pair[0] == pair[1])