2
$\begingroup$

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)
$\endgroup$
  • 1
    $\begingroup$ 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. $\endgroup$ – gnasher729 Mar 16 '17 at 9:46
  • $\begingroup$ 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." $\endgroup$ – David Richerby Mar 16 '17 at 11:31
  • $\begingroup$ @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. $\endgroup$ – Jonathan Mar 16 '17 at 14:40
1
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ 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 :) $\endgroup$ – Jonathan Mar 16 '17 at 6:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.