2017-09-19 72 views
-1

具有相同數量「1」的數字應按十進制表示排序。如何按二進制表示法對二進制數組進行排序

例如:

srt([3,7,8,9]) => [8,3,9,7] # 1000, 11, 1001, 111 
+0

順便說一句,如何計算一個數字中的位數是相當有趣的本身https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in -a-32-bit-integer – algrid

回答

3

在Ruby中,你可以用一個非常簡單的方法:

def srt list 
    list.sort_by { |number| number.to_s(2).count('1') } 
end 

這是不是真的表現高效,而易於閱讀。

3

可以傳遞數組sort_by

[1,2,3,4,5,6,7,8,9].sort_by { |i| [i.digits(2).count(1), i] } 
#=> [1, 2, 4, 8, 3, 5, 6, 9, 7] 

這將經由Array#<=>的項目,通過1-位和數字具有相同數目的由數字本身1比特的數,即進行排序:

[ 
    1, 2, 4, 8, # 1 1-bit (0b0001, 0b0010, 0b0100, 0b1000) 
    3, 5, 6, 9, # 2 1-bits (0b0011, 0b0101, 0b0110, 0b1001) 
    7   # 3 1-bits (0b0111) 
] 
+1

你可以用'sum'來代替'count(1)'。它沒有被讀取,但是對於[Code Golf](https://codegolf.stackexchange.com)會更好。很高興看到'數字'而不是'to_s'這種問題。好答案。 –

0

如果你的問題是:升序排序整數1層的在他們的二進制表示的數量。例如,(7)10→(111)2和(8)10→(1000)2,所以8(其中有1個二進制數)將在7之前排序(其中3個1的二進制數爲,

然後,我們可以做到這一點在下文蟒蛇。

一步一步的解釋

myList = [1,11,7] 

# function to get binary 1's 
def get_len_of_ones(val): 
    getbinary =lambda val : bin(val)[2:].count('1') 
    return getbinary(val) 

# mapping function to every element and then zipping it with myList  
myTuple = zip(myList, map(get_len_of_ones,myList)) 
print myTuple 
Out[1]: [(1, 1), (11, 3), (7, 3)] 


# Applying sorting on the second element of the tuple in the List 
sortedList = sorted(myTuple , key=lambda tup: tup[1],reverse=True) 

print sortedList 
Out[1]: [(11, 3), (7, 3), (1, 1)] 

# Unzip myList out and display myList at index 0 and convert to list 
print list(zip(*sortedList)[0]) 
Out[1]: [11, 7, 1] 

我們可以做到這一點Python的藏漢

myList = [1,11,7] 

# Using get_len_of_ones function from above code 

l= lambda x : list(zip(*sorted(zip(x,map(get_len_of_ones,x)), key=lambda tup: tup[1],reverse=True))[0]) 

l(myList) 
Out[1]: [11, 7, 1]