1

please what is wrong with this code

def binary_converter(n):
    n = int(n)

    if n == 0:
        return '0'

    elif n not in (0,255):
        return 'Invalid input'


    elif n in range (0,255):
        return binary_converter(n//2) + str(n%2)


    else:
        return 'Invalid conversion'## Heading ##

here is the test
import unittest

class BinaryConverterTestCases(unittest.TestCase):
  def test_conversion_one(self):
    result = binary_converter(0)
    self.assertEqual(result, '0', msg='Invalid conversion')

  def test_conversion_two(self):
    result = binary_converter(62)
    self.assertEqual(result, '111110', msg='Invalid conversion')

  def test_no_negative_numbers(self):
    result = binary_converter(-1)
    self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed')

  def test_no_numbers_above_255(self):
    result = binary_converter(300)
    self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed')
3
  • why on earth 62 is special case? Commented Sep 16, 2016 at 8:38
  • @DarthKotik in the test it is supposed to return an invalid input aswell. Commented Sep 16, 2016 at 19:57
  • @PadraicCunningham your correct but i still get an error when submitting it.. P/S it is an assignement for andela home study.. i just need advices not the full code as i really want to learn this properly. thanks all Commented Sep 16, 2016 at 19:58

1 Answer 1

1

First, (0, 255) is a tuple not a range of numbers so 2 in (0, 255) etc.. is going to fail, ranges are half-open so range(0,255) goes from 0...254, again 255 in range (0,255) -> False. Your third test self.assertEqual(result, '111110', msg='Invalid conversion') fails as you always add a leading "0" in your base case so you get '0111110' not '111110':

def binary_converter(n):
    n = int(n)
    if n == 0:
        return '0'
    # same as checking "if n in xrange(256)"
    if 0 <= n <= 255:
        return (binary_converter(n // 2) + str(n % 2)).lstrip("0")
    elif 0 > n or n > 255:
        return 'Invalid input'  ## Heading ##
    return 'Invalid conversion'  ## Heading ##

Once you make the changes all the tests should pass.

You could also do it iteratively:

def binary_converter(n):
    if n < 0 or n > 255:
        return "Invalid input"
    tmp = []
    while n:
        n, i = divmod(n, 2)
        tmp.append(str(i))
    return "".join(tmp[::-1] or "0")
Sign up to request clarification or add additional context in comments.

1 Comment

you have done me a huge favour.. i failed to notice it was missing just a few bugs.. i really appreciate this, thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.