function that counts...

Albert van der Horst albert at spenarnc.xs4all.nl
Wed Jun 9 05:57:28 EDT 2010


In article <l3172q.b4n at spenarnc.xs4all.nl>,
Albert van der Horst  <albert at spenarnc.xs4all.nl> wrote:
>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

Can't be made to work easily.

>
>or if you can't stand recursion:
>
>def x(i):
>   s= 0
>   while i:
>      s += i%10
>      i /= 10
>   return s

The above doesn't work.

This one has been tested:

"
def x(i):
   s= 0
   while i:
      s *= 10
      s += i%10
      i /= 10
   return s
"
(With as loop-invariant  the concatenation of i and reversed-s
and as loop-variant i)

Groetjes Albert

--
-- 
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