2

Hi I wrote the following recursive decimal to binary function while studying for Andela.

def binary_converter(q):
    if q>255 or not isinstance(q, int) or q<0:
        return "Invalid input"
    if q==0:
        return '0'
    elif q!=0:
        q, r = divmod(q, 2)
        return str(r)+binary_converter(q)

The code works for the most part, except I haven't figured out a way to get rid of any preceding zeros to the final result.

For example:

binary_converter(62) '0111110' That's 0111110 with a preceding 0.

How in the world do I get rid of it without breaking the code?

I've tried returning an empty string for the if condition but that breaks my ability to convert the decimal 0 to it's binary which is still 0.

Edit: Here's the working code, updated with D.W's answer

def binary_converter_for_realz(q):
    if q>255 or not isinstance(q, int) or q<0:
        return "Invalid input"
    if q==0:
        return ''
    elif q!=0:
        q, r = divmod(q, 2)
        return binary_converter_for_realz(q)+str(r)

def binary_converter(q):
    if q==0:
        return '0'
    else:
        return binary_converter_for_realz(q)
Jonathan
  • 123
  • 5
  • 1
    In your original, you are outputting the binary digits in the wrong order. You just don't notice because you picked 62 where the output is symmetric. – gnasher729 Mar 16 '17 at 09:46
  • Even though this seems to be pseudocode rather than an actual language, I'm voting to close as off-topic, since the question is just "Please debug my code for me." – David Richerby Mar 16 '17 at 11:31
  • @DavidRicherby it's an algorithmic problem that I was looking for help to solve without actually writing another function but by somehow rearranging the already existing components. The code already did what I needed it to do. – Jonathan Mar 16 '17 at 14:40

1 Answers1

1

Change your code for binary_converter() to return the empty string ('') instead of '0', when you pass it the input zero.

Then, write a new function binary_converter_for_realz(), which checks whether the input is zero; if passed zero, it just returns '0', otherwise it invokes binary_converter() and returns whatever it returns.

This basically treats 0 as a special case, which it is: we don't want a leading zero, except when the integer is zero, in which case we do.

D.W.
  • 159,275
  • 20
  • 227
  • 470
  • Updated my answer with the working code. I guess I was looking for some really neat trick to not have to do anything outside the one function :) – Jonathan Mar 16 '17 at 06:29