
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Numbers Based on 1 Count in Their Binary Representation in Python
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]
Advertisements