Algorithms lab (help)


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


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

Where is your attempt at writing the converter? Are we expected to just give you code? We may be able to give you examples once we see what you have so far.

1 Like

So you don’t think we are blowing wind up your skirt, my ten line solution gave this result from the unit test:

=============== RESTART: D:/Python35/users/ ===============
Ran 4 tests in 0.010s


Sorry i forgot to.

This is my code below:

def binary_converter(x):
  if not (isinstance(x, int) and x >= 0 and x <= 255):
    return "Invalid input"
  return bin(x)[2:]

Thanks for you help mtf.

1 Like

A clever solution. Not to be critical, but this does not resemble an algorithm in the classic sense. There are no steps, which is usually implied in an algo. Can we do this without using Python built-ins?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.