0
0
DSA Pythonprogramming~10 mins

Count Set Bits Brian Kernighan Algorithm in DSA Python - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the count variable to zero.

DSA Python
def count_set_bits(n):
    count = [1]
    while n > 0:
        n = n & (n - 1)
        count += 1
    return count
Drag options to blanks, or click blank then click option'
A-1
B1
Cn
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1 or n instead of 0.
2fill in blank
medium

Complete the code to update n by removing the rightmost set bit.

DSA Python
def count_set_bits(n):
    count = 0
    while n > 0:
        n = n [1] (n - 1)
        count += 1
    return count
Drag options to blanks, or click blank then click option'
A|
B&
C^
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using OR or XOR instead of AND.
3fill in blank
hard

Fix the error in the loop condition to correctly count set bits.

DSA Python
def count_set_bits(n):
    count = 0
    while n [1] 0:
        n = n & (n - 1)
        count += 1
    return count
Drag options to blanks, or click blank then click option'
A>
B==
C<=
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' or '<=' which cause incorrect loop behavior.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps numbers to their set bit counts.

DSA Python
numbers = [3, 5, 7, 9]
set_bits_count = { [1]: count_set_bits([2]) for [1] in numbers }
Drag options to blanks, or click blank then click option'
Anum
Bn
Ccount
Dbit
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing errors.
5fill in blank
hard

Fill all three blanks to filter numbers with more than one set bit and create a dictionary of their counts.

DSA Python
numbers = [1, 2, 3, 4, 5]
filtered_counts = { [1]: count_set_bits([2]) for [1] in numbers if count_set_bits([3]) > 1 }
Drag options to blanks, or click blank then click option'
Anum
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing variable names causing NameError.