2017-09-19 73 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]