Count set bits using Python List comprehension
set bits means finding how many 1s are in the binary form of a number. The set bit is any bit that is 1. List comprehension offers a quick and simple way to count these set bits. In this article, we will count set bits using Python list comprehension.
Using bin()
bin() function converts a number to binary, and list comprehension counts the '1' bits. This method is simple and efficient for counting set bits in small to moderate numbers.
Example:
n = 6
res= sum([1 for bit in bin(n)[2:] if bit == '1'])
print(res)
Output
2
Explanation:
- This converts the number
n
to binary and removes the '0b' prefix. It
counts the number of '1' bits in the binary representation.
Let's understand more method to count set bits using python list comprehension.
Table of Content
Using format()
format()
function converts a number to its binary representation without the '0b' prefix. List comprehension then counts the number of '1' bits in the binary string.
Example:
n = 6
res= sum([1 for bit in format(n, 'b') if bit == '1'])
print(res)
Output
2
Explanation:
- This converts the number
n
to its binary representation without the '0b' prefix. This
counts the number of '1' bits in the binary string.
Using Bitwise AND
Bitwise AND with list comprehension checks each bit of the number. It efficiently counts set bits by shifting bits and summing the occurrences of 1s.
Example:
n = 6
res= sum([1 for i in range(n.bit_length()) if n & (1 << i)])
print(res)
Output
2
Explanation:
- It gives the number of bits in n.
- This checks each bit, summing 1 for set bits.