function that counts...

superpollo utente at esempio.net
Wed May 19 16:30:56 EDT 2010


René 'Necoro' Neumann ha scritto:
> 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)

TypeError: 'int' object is not callable

on 2.5.4

> 
> A small oneliner :)
> 
> (I first had "return len([x for x in ...])" but the above avoids
> creating an intermediate list)
> 
> - René
> 



More information about the Python-list mailing list