Numbers with identical amount of "1"s should be ordered by decimal representation.
For example:
srt([3,7,8,9]) => [8,3,9,7] # 1000, 11, 1001, 111
Numbers with identical amount of "1"s should be ordered by decimal representation.
For example:
srt([3,7,8,9]) => [8,3,9,7] # 1000, 11, 1001, 111
You can pass an array to 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]
This will sort the items via Array#<=>
, i.e. by the numbers of 1-bits and numbers with the same number of 1-bits by the number itself:
[
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)
]
In Ruby you can use a really simple approach:
def srt list
list.sort_by { |number| number.to_s(2).count('1') }
end
It is not really performance efficient, but rather easy to read.
If your question is : Sort the integers in ascending order by the number of 1's in their binary representations. For example, (7)10 → (111)2 and (8)10 → (1000)2, so 8 (which has one 1 in binary) would be ordered before 7 (which has three 1's in binary.
Then, we can do that in python as below.
Step By Step Explanation
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]
We can do it pythonic aswell
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]
import pandas as pd
df = pd.DataFrame([1,2,3,4,5,8],columns=['Integers'])
def countSetBits(n): count = 0 while (n): count += n & 1 n >>= 1 return count
df["Count_of_set_bits"]=df.apply(lambda x: countSetBits(x['Integers']),axis=1)
df['value']=df['Integers']
df=df.sort_values(['Count_of_set_bits', 'value'], ascending=[True, True])
results=list(df['Integers'])