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 "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
stringMatch("xxcaazz", "xxbaaz") → 3 stringMatch("abc", "abc") → 2 stringMatch("abc", "axc") → 0
import doctest
def all_two_chars_occurencies(string):
"""
>>> list(all_two_chars_occurencies('abcd'))
['ab', 'bc', 'cd']
>>> list(all_two_chars_occurencies('xxcaazz'))
['xx', 'xc', 'ca', 'aa', 'az', 'zz']
"""
for index, char in enumerate(string[:-1]):
yield char + string[index + 1]
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.
>>> common_two_chars_occurences('xxcaazz', 'xxbaaz')
3
>>> common_two_chars_occurences('abc', 'abc')
2
>>> common_two_chars_occurences('abc', 'axc')
0
"""
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__ == "__main__":
doctest.testmod()