[Tutor] Count for loops

Mats Wichmann mats at wichmann.us
Mon Apr 3 15:24:51 EDT 2017


On 04/03/2017 10:16 AM, Alan Gauld via Tutor wrote:
> On 03/04/17 16:42, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
>> Sorry. That was  stupid of me. The loop does nothing.
> 
> Let me rewrite the code with some different variable names...
> 
>>>> with open(file_path) as a:
>>>>     b = a.read()
> 
> with open (file_path) as PI_text:
>      PI_as_a_long_string = PI_text.read()
> 
>>>> for year in b:
> 
> for each_char in PI_as_a_long_string:
> 
>>>>     if get_year in b:
>>>>         count += 1
> 
>       if get_year in PI_as_a_long_string:
>           count += 1
> 
>>>> print("Your birth date occurs %s times in PI!" % (count))
> 
> if count:
>    print("Your birth date occurs in PI, I checked, count, "times!")
> 
> 
> Aren't meaningful variable names great? We should all do
> them more often.


So the takeaways here are:

in the first ("non-counting") sample, there's no need to use a loop,
because you're going to quit after the outcome "in" or "not in" right
away - there's no loop behavior at all.

for year in b:
    if get_year in b:
        print("Your year of birth occurs in PI!")
        break
    else:
        print("Your year of birth does not occur in PI.")
        break

for the counting version you could do something that searches for the
year repeatedly, avoiding starting over from the beginning so you're
actually finding fresh instances, not the same one (hint, hint). There
are several ways to do this, including slicing, indexing, etc.  Alan's
suggestion looks as good as any.

Or, if you don't care about overlapping cases, the count method of a
string will do just fine:

PI_as_a_long_string.count(year)

If you're talking about 4-digit year numbers using a Western calendar in
digits of PI, the overlap effect seems unlikely to matter - let's say
the year is 1919, do we think PI contains the sequence 191919? count
would report back one instead of two in that case. In other cases it
might matter; count is written specifically to not care about overlaps:
"Return the number of (non-overlapping) occurrences"  So that's worth
keeping in mind when you think about what you need from
substrings-in-strings cases.





More information about the Tutor mailing list