This is much easier with zip()
and the filter()
built in function:
Python 2.x:
In [23]: word1 = 'frog'
In [24]: word2 = 'friend'
In [25]: print len(filter(lambda (x, y): x == y, zip(word1, word2)))
2
Python 3.x (see comments for pointers re: changes):
>>> word1 = 'frog'
>>> word2 = 'friend'
>>> len(list(filter(lambda xy: xy[0] == xy[1], zip(word1, word2))))
2
Update: since you're new to programming, I'll attempt to explain this solution a bit:
Python has support for sequences (commonly thought of as an ordered list of items), such as [1,2,3]
or ['a', 'b', 'c', 123, 456]
. However, Python treats strings as an ordered list of characters as well, so 'hello world'
is also a list. As a result, you may apply Python's list-related operators/built-in functions on strings as well. Therefore your problem reduces to treat word1
and word2
as lists and find indexes on these lists where their items match.
So let's use Python's special functions for this.zip
is a nifty function that takes more than one sequence, and makes a new list with each item at index X made up of the values at index X in each of the input sequences. For instance, zip([1,2], [3,4])
becomes [(1,3), (2,4)]
and zip('foo', 'bar')
becomes [('f', 'b'), ('o', 'a'), ('o', 'r')]
. This last result is very useful for your problem -- now you just need to run a function through each tuple (i.e. a value of the form (x,y)
) through a function to check if the values are equal. You could do that in a loop as in other languages, but you can also make Python do the looping for you and provide just a function that returns the result of applying equality to each tuple on a list by using a function such as filter()
or map()
. In your case, you want filter()
which runs through the input list and includes every value in the original list that causes the value of a passed in function (the lambda
in the solution) to be True
. The length of the "filtered" list is essentially the number of matches.
Hope this helps. Note that if you are new to Python, you will want to look up list/sequences, tuples, zip, filter, and lambda in a good book or the official Python reference to fully understand the solution.
Oh, and welcome to programming :-)