Skip to content

Commit

Permalink
decimal to binary challenge
Browse files Browse the repository at this point in the history
  • Loading branch information
HebaShaheen committed Jan 1, 2025
1 parent 057c110 commit 11329c7
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
41 changes: 41 additions & 0 deletions solutions/decimal_to_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A function to convert decimal numbers to binary.
Created on 1/1/2025
@author: Heba Shaheen
"""


def decimal_to_binary(n: int) -> str:
"""Give the binary number for a decimal
Args:
n (int): Decimal number to be converted
Returns:
str: Binary representation of the decimal number
Raises:
AssertionError: if the input is not an integer
>>> decimal_to_binary(10)
"1010"
>>> decimal_to_binary(20)
"10100"
>>> decimal_to_binary(255)
"11111111"
"""
# Handle the edge case for 0
assert isinstance(n, int), "The input should be integer"
assert n >= 0, "Give a positive input"
if n == 0:
return "0"
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary
49 changes: 49 additions & 0 deletions solutions/tests/test_decimal_to_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unit tests for decimal_to_binary function.
@author: Heba Shaheen
"""

import unittest

from ..decimal_to_binary import decimal_to_binary


class TestBinary(unittest.TestCase):
"""Unit tests for decimal_to_binary function."""

def test_number_0(self):
"""It should give the binary"""
actual = decimal_to_binary(0)
expected = "0"
self.assertEqual(actual, expected)

def test_number_2(self):
"""It should give the binary"""
actual = decimal_to_binary(2)
expected = "10"
self.assertEqual(actual, expected)

def test_number_5(self):
"""It should give the binary"""
actual = decimal_to_binary(5)
expected = "101"
self.assertEqual(actual, expected)

def test_number_15(self):
"""It should give the binary"""
actual = decimal_to_binary(15)
expected = "1111"
self.assertEqual(actual, expected)

def test_non_integer_input(self):
"""It should raise an assertion error if the argument is not an integer"""
with self.assertRaises(AssertionError):
decimal_to_binary("1")

def test_non_negative_input(self):
"""It should raise an assertion error if the argument is negative"""
with self.assertRaises(AssertionError):
decimal_to_binary(-3)

0 comments on commit 11329c7

Please sign in to comment.