function that counts...

Raymond Hettinger python at rcn.com
Mon May 24 10:14:43 EDT 2010


On May 19, 12:58 pm, superpollo <ute... at esempio.net> wrote:
> ... how many positive integers less than n have digits that sum up to m:
>
> In [197]: def prttn(m, n):
>      tot = 0
>      for i in range(n):
>          s = str(i)
>          sum = 0
>          for j in range(len(s)):
>              sum += int(s[j])
>          if sum == m:
>              tot += 1
>      return tot
>     .....:
>
> In [207]: prttn(25, 10000)
> Out[207]: 348
>
> any suggestion for pythonizin' it?

Your code is readable and does the job just fine.
Not sure it is an improvement to reroll it into a one-liner:

def prttn(m, n):
    return sum(m == sum(map(int, str(x))) for x in range(n))
>>> prttn(25, 10000)
348

Some people find the functional style easier to verify because of
fewer auxilliary variables and each step is testable independently.
The m==sum() part is not very transparent because it relies on
True==1, so it's only readable if it becomes a common idiom (which it
could when you're answering questions of the form "how many numbers
have property x").

If speed is important, the global lookups can be localized:

def prttn(m, n, map=itertools.imap, int=int, str=str, range=range):
    return sum(m == sum(map(int, str(x))) for x in range(n))

Raymond






More information about the Python-list mailing list