function that counts...

Albert van der Horst albert at spenarnc.xs4all.nl
Wed May 26 10:32:50 EDT 2010


In article <4bf442cd$0$31377$4fafbaef at reader1.news.tin.it>,
superpollo  <utente 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?

I don't like the excursion to string and back.

def x(i) : return  x(i/10)+i%10 if i else 0

or if you can't stand recursion:

def x(i):
   s= 0
   while i:
      s += i%10
      i /= 10
   return s

(All untested but you get the idea.)

>
>bye


--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst




More information about the Python-list mailing list