- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to 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.
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))
[4, 1, 12, 7, 6]
[1, 4, 6, 12, 7]
- Program to sort out phrases based on their appearances in Python
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Count numbers have all 1s together in binary representation in C++
- Python program to check if binary representation of two numbers are anagram.
- Python program to sort table based on given attribute index
- How to sort the Processes based on their property name using PowerShell?
- Program to sort an array based on the parity values in Python
- C program to sort triangles based on area
- Python program to check if binary representation is palindrome?
- Python Program to Count number of binary strings without consecutive 1’
- Program to perform bubble sort based on choice in 8085 Microprocessor
- Python program to Sort Tuples by their Maximum element
- Program to sort given set of Cartesian points based on polar angles in Python