1

I have this challenge:

Create a function called binary_converter. Inside the function, implement an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents.

For any invalid input, return string Invalid input

Example: For number 5 return string 101

Unit test code is below

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')

my code goes below

def binary_converter(n):
   
    if(n==0):
        return "0"
    
    elif(n>255):
        
        return "invalid input"
    elif(n < 0):
        return "invalid input"
    else:
        ans=""
        while(n>0):
            temp=n%2
            ans=str(temp)+ans
            n=n/2
        return ans

Unit test results

Total Specs: 4 Total Failures: 2

1. test_no_negative_numbers

    `Failure in line 19, in test_no_negative_numbers self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') AssertionError: Input below 0 not allowed`

2. test_no_numbers_above_255

    `Failure in line 23, in test_no_numbers_above_255 self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed') AssertionError: Input above 255 not allowed`
2
  • "Invalid" != "invalid" ? Commented Oct 8, 2016 at 1:31
  • No worries - you can spend forever staring at things like that without seeing the problem. Commented Oct 8, 2016 at 1:53

1 Answer 1

2

Comparing strings in Python cares cases.

>>> 'invalid input' == 'Invalid input'
False

You need to adjust test code or implementation code so that string literals matches exactly.

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

...

elif(n < 0):
    return "invalid input"
            ^--- (lowercase)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.