Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query regarding Bit Counting (Python)

I tried to solve this Kata problem

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But the problem is my code gives the correct answers right for the first time around but when
it is run for 2nd time onward it gives wrong answers only. I think it has to do sth with how my code is recursive. Please help me figure it out.
for example when i run count_bits(24) it gives the output 2 which is correct but when i run the same function again it would give 4 and then 6 and so on . I dont know what’s wrong with this

My code.

  dec_num = []

  def count_bits(n):
    
    def DecimalToBinary(n):
        if n >= 1:
            DecimalToBinary(n // 2)
        dec_num.append( n % 2)
        return dec_num
    
    dec = DecimalToBinary(n)
    
    return dec.count(1)

>Solution :

That is because dec_num is outside the method, so it’s reused at every call, put it inside

def count_bits(n):
    dec_num = []
    def DecimalToBinary(n):
        if n >= 1:
            DecimalToBinary(n // 2)
        dec_num.append(n % 2)
        return dec_num

    dec = DecimalToBinary(n)
    return dec.count(1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading