Solution: Decimal to Binary
Contents
Solution: Decimal to Binary#
Write a function that returns the binary value (as string) for a positive integer decimal number
Function definition#
def dec_to_binary(n):
binary = ""
while n != 0:
binary = str(n % 2) + binary
n = n // 2
return binary
Using a recursive function:
def dec_to_binary(n):
if n==0: return '' # condition to stop the recursive process
else:
return dec_to_binary(n // 2) + str(n % 2) # recursive function call
Testing#
Check if your function returns the expected value using the cell below.
import unittest
class UnitTests(unittest.TestCase):
def test_type(self):
self.assertEqual(type(dec_to_binary(10)), type('1010'), 'The function should return a string')
def test_size(self):
self.assertEqual(len(dec_to_binary(100)), 7, 'The function should return a string with lenght=7')
def test_result_odd(self):
self.assertEqual(dec_to_binary(101), '1100101', 'The binarie for 200 should be 1100101')
def test_result_even(self):
self.assertEqual(dec_to_binary(200), '11001000', 'The binarie for 200 should be 11001000')
unittest.main(argv=[''], verbosity=2,exit=False)
test_result_even (__main__.UnitTests) ...
ok
test_result_odd (__main__.UnitTests) ...
ok
test_size (__main__.UnitTests) ...
ok
test_type (__main__.UnitTests) ...
ok
----------------------------------------------------------------------
Ran 4 tests in 0.003s
OK
<unittest.main.TestProgram at 0x7fe148afae10>