I am trying to write a program that checks two strings and prints the number of common characters that are at the same position in both of the strings so if it checked, say:
You can use
zip() to iterate through both of them simultaneously:
sum(1 if c1 == c2 else 0 for c1, c2 in zip(string1, string2))
or even (using implicit integer values for
sum(c1 == c2 for c1, c2 in zip(string1, string2))
This creates a series of tuples with paired items from each of the inputs, for instance with
heron it looks like this:
[('h', 'h'), ('e', 'e'), ('l', 'r'), ('l', 'o'), ('o', 'n')].
for c1, c2 in
We're using a generator expression to iterate over these tuples, assigning each of the two elements to a variable.
1 if c1 == c2 else 0
We're going to emit a sequence of 1s and 0s, where the number of 1s is equal to the number of cases where the equivalent position characters were equal.
Finally, we sum the emitted sequence of 1s and 0s - effectively counting the total number of equal characters.
You can even shorten this a bit, because in Python you can treat boolean values
0 respectively, which leads to the second form above.
You might wonder: what happens if
string2 are different lengths? This expression will actually still work, because
zip() will stop as soon as it reaches the end of either. Since by definition the extra characters in the longer string will not be equal to the lack of characters in the shorter, this doesn't affect the count.