function that counts...

René 'Necoro' Neumann lists at necoro.eu
Wed May 19 16:24:42 EDT 2010


Am 19.05.2010 21:58, schrieb superpollo:
> ... 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?
> 
> bye

An idea would be:

>>> def prttn(m, n):
...	return sum(1 for x in range(n) if sum(map(int, str(x))) == m)

A small oneliner :)

(I first had "return len([x for x in ...])" but the above avoids
creating an intermediate list)

- René

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 262 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100519/54af5c21/attachment-0001.sig>


More information about the Python-list mailing list