# Program to sort numbers based on 1 count in their binary representation in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lists of numbers in nums. We have to sort the list in ascending order by the number of 1s present in the binary representation for each number. If two numbers have same number of 1s, then arrange them based on their values.

So, if the input is like nums = [4, 1, 12, 7, 6], then the output will be [1, 4, 6, 12, 7], because −

• Binary form of 4 is 0100
• Binary form of 1 is 0001
• Binary form of 6 is 0110
• Binary form of 12 is 1100
• Binary form of 7 is 0111

So the arrangement is [1, 4, 6, 12, 7], 1 comes first because its value is smaller, as well as 6 comes first for this same reason.

To solve this, we will follow these steps −

• define a function compare, this takes a number n
• this returns a pair p with (1 count in binary form of n, value of n)
• Sort nums by passing each value into compare function before comparison
• return nums.

## Example

Let us see the following implementation to get better understanding −

def solve(nums):
nums.sort(key=lambda num: (bin(num).count("1"), num))
return nums

nums = [4, 1, 12, 7, 6]
print(solve(nums))

## Input

[4, 1, 12, 7, 6]


## Output

[1, 4, 6, 12, 7]