2013-03-21 66 views

回答

1

使用真棒collections模塊。

>>> from collections import Counter 
>>> binary = bin(20)[2:] 
>>> Counter(binary) 
Counter({'0': 3, '1': 2}) 

或者你可以使用內置的功能count()

>>> binary = bin(20)[2:] 
>>> binary.count('1') 
2 

甚至:

>>> sum(1 for i in bin(20)[2:] if i == '1') 
2 

但是,最後的解決辦法是比使用count()

+0

沒有理由對此使用'Counter' – jamylak 2013-03-21 07:02:42

+2

即使是製作Counter的人也沒有使用它來解決這個問題;) – jamylak 2013-03-21 07:19:01

+1

@jamylak這仍然是一個解決方案:) – TerryA 2013-03-21 08:14:27

0

如果輸入數目是「編號」

number =20 
len(bin(number)[2:].replace('0','')) 

另一種解決方案是

from collections import Counter 

Counter(list(bin(number))[2:])['1'] 
+1

你的第一個解決方案就像用大錘撲蒼蠅。你可以使用'str.count('1')'。如果您使用計數器 – jamylak 2013-03-21 07:14:41

+0

@jamylak :),也無需轉換爲列表,謝謝 – Neil 2013-03-25 08:38:32

4
>>> num = 20 
>>> bin(num)[2:].count('1') 
2 
1

str.count方法和bin功能使這個小難題的短期工作:

>>> def ones(x): 
     "Count the number of ones in an integer's binary representation" 
     return bin(x).count('1') 

>>> ones(20) 
2 
8

你正在尋找被稱爲Hamming weight什麼,並且有很多的算法來做到這一點。下面是另一個簡單的一個:

def ones(n): 
    w = 0 
    while (n): 
     w += 1 
     n &= n - 1 
    return w 
+0

&=做什麼? – jimifiki 2013-03-21 07:31:35

+0

'a&= b'等價於'a = a&(b)'。'&'是[按位與運算符](http://docs.python.org/2/reference/expressions.html#binary-bitwise-operations)。 – Cairnarvon 2013-03-21 07:33:02

3

的常用方法,使這個致盲快是使用查找表:

table = [bin(i)[2:].count('1') for i in range(256)] 

def pop_count(n): 
    cnt = 0 
    while n > 0: 
    cnt += table[n & 256] 
    n >>= 8 
    return cnt 

在Python中,使用binlist.count會更快的任何解決方案,但這是好的如果你想用匯編編寫它。

+2

如果你正在使用匯編,'n&255'將顯着快於'n%256'。 – Cairnarvon 2013-03-21 06:57:23

+0

確實,相應地更新了代碼。謝謝。 – 2013-03-24 10:48:05

+1

你的代碼有一個錯字,你寫了'n&256'而不是'n&255'。 – 2017-12-14 11:21:25

0

我是一個新的編碼器,我發現這個邏輯很簡單。新手可能更容易理解。

def onesInDecimal(n): 
    count = 0 
    while(n!=0): 
    if (n%2!=0): 
     count = count+1 
     n = n-1 
     n = n/2 
    else: 
     n = n/2 
    return count 
相關問題