Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to sort numbers based on 1 count in their binary representation in Python
Sorting numbers based on the count of 1s in their binary representation is a common programming problem. When two numbers have the same count of 1s, we sort them by their actual values in ascending order.
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 100 (one 1)
- Binary form of 1 is 1 (one 1)
- Binary form of 6 is 110 (two 1s)
- Binary form of 12 is 1100 (two 1s)
- Binary form of 7 is 111 (three 1s)
So the arrangement is [1, 4, 6, 12, 7]. Among numbers with one 1, value 1 comes before 4. Among numbers with two 1s, value 6 comes before 12.
Algorithm
To solve this, we will follow these steps −
- Define a function that takes a number n
- Return a tuple with (count of 1s in binary form of n, value of n)
- Sort nums using this function as the key
- Return the sorted list
Using Lambda Function with sort()
The most concise approach uses a lambda function with the sort() method ?
def solve(nums):
nums.sort(key=lambda num: (bin(num).count("1"), num))
return nums
nums = [4, 1, 12, 7, 6]
print("Original list:", nums)
result = solve(nums.copy()) # Use copy to preserve original
print("Sorted list:", result)
Original list: [4, 1, 12, 7, 6] Sorted list: [1, 4, 6, 12, 7]
Using Custom Function
We can also define a separate function to make the logic clearer ?
def count_ones_and_value(num):
ones_count = bin(num).count("1")
return (ones_count, num)
def solve(nums):
nums.sort(key=count_ones_and_value)
return nums
nums = [4, 1, 12, 7, 6]
print("Original list:", nums)
result = solve(nums.copy())
print("Sorted list:", result)
# Let's see the sorting keys for each number
print("\nSorting keys:")
for num in [4, 1, 12, 7, 6]:
print(f"{num} -> binary: {bin(num)} -> key: {count_ones_and_value(num)}")
Original list: [4, 1, 12, 7, 6] Sorted list: [1, 4, 6, 12, 7] Sorting keys: 4 -> binary: 0b100 -> key: (1, 4) 1 -> binary: 0b1 -> key: (1, 1) 12 -> binary: 0b1100 -> key: (2, 12) 7 -> binary: 0b111 -> key: (3, 7) 6 -> binary: 0b110 -> key: (2, 6)
Using bit_count() Method (Python 3.10+)
For Python 3.10 and later, you can use the more efficient bit_count() method ?
def solve(nums):
nums.sort(key=lambda num: (num.bit_count(), num))
return nums
nums = [4, 1, 12, 7, 6]
result = solve(nums.copy())
print("Sorted list:", result)
How It Works
The sort() method uses a tuple as the sorting key: (ones_count, value). Python compares tuples element by element, so it first sorts by the count of 1s, and if two numbers have the same count, it sorts by their actual values.
Conclusion
Use bin(num).count("1") to count 1s in binary representation. Sort using a tuple key (ones_count, value) for proper ordering. The lambda approach provides the most concise solution.
