What I learned today
duncan smith
duncan at invalid.invalid
Fri Feb 14 20:24:33 EST 2020
On 14/02/2020 23:21, Dan Stromberg wrote:
> On Fri, Feb 14, 2020 at 3:10 PM Stefan Ram <ram at zedat.fu-berlin.de> wrote:
>
>> By trial and error (never read documentation!) I found
>> that you can count the number of e's in a text by just
>>
>> Counter( text ).get( 'e' )
>>
>> (after »from collections import Counter« that is).
>>
> Even simpler, though not suitable for all situations:
> "abcbdbe".count("b")
>
[snip]
And by far the quickest way (that I've found) for counting the number of
set bits in an int.
>>> def popcount(n):
cnt = 0
while n:
n &= n-1
cnt += 1
return cnt
>>> import timeit
>>> timeit.timeit("popcount(19847998494279)", "from __main__ import
popcount", number=10000)
0.034410387044772506
>>> timeit.timeit("bin(19847998494279).count('1')", number=10000)
0.004501901799812913
>>>
OK, things turn around for large integers with very few set bits. But
for my use case bin(n).count('1') wins hands down (which surprised me a
little).
Duncan
More information about the Python-list
mailing list