[Tutor] counting number of loops

Alan Gauld alan.gauld at yahoo.co.uk
Sat Feb 25 12:28:29 EST 2017


On 25/02/17 17:12, Rafael Knuth wrote:
> I want to compare two strings and count the number of identical letters:
> 
> stringB = "ABCD"
> stringA = "AABBCCDDEE"
> for b in stringB:
>     if b in stringA:
>         r = 0
>         r += 1
>         print (r)
> 
> How do I count the output (r) instead of printing it out?
> (result should be 4). Thanks!

You are very close.
You are doing too much inside the for loop.
1) initialise the counter 'r' before the loop starts
 - you only want it set to zero at the begiunning not
   everytime you go through the loop.

2) move the print(r) line out of the loop at the end
 - you only really need to know the final answer, not
   the answer after each loop iteration..

BTW If you have covered sets then there is an easier
solution by converting both strings to sets and
taking the intersection. But you may not have
done sets yet...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list