List Comprehension - count set bits

 # List Comprehension 


"""

Given a list of n integers, count the number of set bits (1’s) in the binary representation of each number present in the list

"""


# Read List

L = eval(input("Enter list of numbers : "))


# Convert each number in List to its binary equivalent and type cast to string

Lbinstr = [str(bin(N)) for N in L]


# Join the binary string and count number of 1's

print("Number of 1's = ",("".join(Lbinstr)).count("1"))


"""

Sample output

>python Listcomprehenstion.py

Enter list of numbers : [1,2,3,4,5]

Number of 1's =  7

"""


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu