Как найти единицы в python — Сайт, где вы сможете решить свои вопросы
How do you count the number of ones in a given integer’s binary representation.
Say you are given a number 20, which is 10100 in binary, so number of ones is 2.
jamylak
128k30 gold badges230 silver badges230 bronze badges
asked Mar 21, 2013 at 6:24
What you’re looking for is called the Hamming weight, and there are a lot of algorithms to do it. Here’s another straightforward one:
def ones(n):
w = 0
while (n):
w += 1
n &= n - 1
return w
answered Mar 21, 2013 at 6:31
CairnarvonCairnarvon
25.5k9 gold badges51 silver badges65 bronze badges
1
Use the awesome collections module.
>>> from collections import Counter
>>> binary = bin(20)[2:]
>>> Counter(binary)
Counter({'0': 3, '1': 2})
Or you can use the built-in function count():
>>> binary = bin(20)[2:]
>>> binary.count('1')
2
Or even:
>>> sum(1 for i in bin(20)[2:] if i == '1')
2
But that last solution is slower than using count()
answered Mar 21, 2013 at 6:27
TerryATerryA
58.5k11 gold badges114 silver badges142 bronze badges
9
>>> num = 20
>>> bin(num)[2:].count('1')
2
answered Mar 21, 2013 at 6:28
YarkeeYarkee
8,8965 gold badges28 silver badges29 bronze badges
1
The usual way to make this blinding fast is to use lookup tables:
table = [bin(i)[2:].count('1') for i in range(256)]
def pop_count(n):
cnt = 0
while n > 0:
cnt += table[n & 255]
n >>= 8
return cnt