[Tutor] Count for loops

Alan Gauld alan.gauld at yahoo.co.uk
Mon Apr 3 20:07:44 EDT 2017


On 04/04/17 00:37, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> I will go for this modification of the original code.

> count = 0
> b= '3'+b[2:]
> n = len(b)
> for i in range(n-4):
>     if b[i:i+4] == get_year:
>         count += 1

While I think this works OK, I would probably suggest
that this is one of the rare valid cases for using
a regex(*) with a simple string. The findall() method
with a suitable pattern and flags should catch
overlaps. And is probably faster being written in C.

(*)Assuming you want to include overlapping cases,
otherwise just use b.count()...

-- 
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