function that counts...

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Wed May 19 17:51:23 EDT 2010


On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:

> ... how many positive integers less than n have digits that sum up to m:
> 
> In [197]: def prttn(m, n):

Does the name "prttn" mean anything? I'm afraid I keep reading it as a 
mispelling of "print n".


[...]
>          s = str(i)
>          sum = 0
>          for j in range(len(s)):
>              sum += int(s[j])

Rather than iterating over an index j = 0, 1, 2, ... and then fetching 
the jth character of the string, you can iterate over the characters 
directly. So the inner loop is better written:

for c in s:
    sum += int(c)




-- 
Steven



More information about the Python-list mailing list