Skip to content

Commit

Permalink
Merge branch 'Crafting-solution's-readme.md' of https://github.com/MI…
Browse files Browse the repository at this point in the history
…T-Emerging-Talent/ET6-foundations-group-18 into Crafting-solution's-readme.md
  • Loading branch information
sashour82 committed Jan 12, 2025
2 parents 46e8fb2 + 203710c commit b1068d1
Show file tree
Hide file tree
Showing 11 changed files with 479 additions and 1 deletion.
47 changes: 47 additions & 0 deletions solutions/area_of_circle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
A module for calculating the area of a circle.
Module contents:
- area_of_circle: calculates the area of a circle given its radius.
Created on 01 04 2025
@author: Raghad
"""

import math


# Define a function to calculate the area of a circle.
def area_of_circle(radius: float) -> float:
"""Calculate the area of a circle given its radius.
Parameters:
radius: float, the radius of the circle
Returns -> float: area of the circle
Raises:
ValueError: if the radius is negative
Examples:
>>> area_of_circle(5)
78.53981633974483
>>> area_of_circle(0)
0.0
>>> area_of_circle(3.5)
38.48451000647496
"""
# Raise an error if the radius is negative.
if radius < 0:
raise ValueError("Radius cannot be negative")

# Calculate and return the area using the formula: area = π * r^2
return math.pi * radius**2


# Entry point for script execution
if __name__ == "__main__":
# Example usage: Calculate the area of a circle with a radius of 5.
radius = 5
area = area_of_circle(radius)
print("Area of the circle:", area)
42 changes: 42 additions & 0 deletions solutions/binary_to_hex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
Module: Binary to Hexadecimal Converter
This module provides a utility function to convert binary strings to their
corresponding hexadecimal representations. It validates the input to ensure
that it contains only binary digits (0s and 1s) and performs the conversion
accurately.
@author: Marc Darazi
"""


def binary_to_hex(binary_str):
"""
Convert a binary string to its hexadecimal representation.
Parameters:
binary_str (str): A string of 0s and 1s representing a binary number.
Returns:
str: The hexadecimal representation of the binary number.
Raises:
ValueError: If the input is not a valid binary string.
Example:
>>> binary_to_hex("1101")
'D'
>>> binary_to_hex("11110000")
'F0'
>>> binary_to_hex("101010101010")
'AAA'
"""
# Validate input
if not all(char in "01" for char in binary_str):
raise ValueError("Input must be a binary string containing only 0s and 1s.")

# Convert binary string to integer
decimal_value = int(binary_str, 2)

# Convert integer to hexadecimal string and return
return hex(decimal_value)[2:].upper()
44 changes: 44 additions & 0 deletions solutions/hex_to_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
This module provides a utility function to convert a hexadecimal string
to its binary representation.
Functions:
- hex_to_binary: Converts a hexadecimal string to its binary equivalent.
Author: Marc Darazi
"""


def hex_to_binary(hex_string):
"""
Convert a hexadecimal string to its binary representation.
Parameters:
hex_string (str): A string representing a hexadecimal number.
It can include a leading '0x' prefix or not.
Returns:
str: A binary string representation of the given hexadecimal number,
with leading zeros preserved.
Raises:
ValueError: If the input string is not a valid hexadecimal number.
Example:
>>> hex_to_binary("1A")
'11010'
>>> hex_to_binary("0xFF")
'11111111'
>>> hex_to_binary("0x0")
'0'
"""
# Remove '0x' prefix if present
if hex_string.startswith("0x"):
hex_string = hex_string[2:]

try:
# Convert to integer, then to binary
binary_string = bin(int(hex_string, 16))[2:] # Remove '0b' prefix
return binary_string
except ValueError:
raise ValueError("Invalid hexadecimal string")
36 changes: 36 additions & 0 deletions solutions/leap_year.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The module checks whether a given year is a leap year.
create by Muna Sattouf on January 9, 2025
Completed on January 10, 2024
A year is a leap year if it is divisible by 4,
and if it is divisible by 100, it must also be divisible by 400.
"""


def leap_year(year: int) -> bool:
"""
Checks whether the given year is a leap year.
Argument:
year, a positive integer
Returns:
boolean: True if the year is a leap year, false otherwise.
Examples:
>>> leap_year(2024)
True
>>> leap_year(1900)
False
>>> leap_year(2021)
False
"""
if not isinstance(year, int):
raise ValueError("Year must be an integer")
if year < 0:
raise ValueError("Year must be positive integer")

return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
39 changes: 39 additions & 0 deletions solutions/sum_of.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on XX XX XX
A module gives a summation of two numbers.
@author: Tagwa Hashim
"""


def sum_of(num1, num2):
"""
Adds two numbers and returns their sum.
Args:
num1: The first number. Can be an integer or a float.
num2: The second number. Can be an integer or a float.
Returns:
The sum of num1 and num2.
Raises:
AssertionError: If either num1 or num2 is not a number (int or float).
Examples:
>>> sum_of(3, 5)
8
>>> sum_of(2.5, 3.7)
6.2
>>> sum_of("hello", 2.718)
Traceback (most recent call last):
...
AssertionError: Both arguments must be numbers (int or float).
"""
assert isinstance(num1, (int, float)) and isinstance(num2, (int, float)), (
"Both arguments must be numbers (int or float)."
)
return num1 + num2
20 changes: 19 additions & 1 deletion solutions/tests/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
# Tests
# Test Folder 🗂️

This folder contains test files designed to validate the functionality of the
functions in the [solutions](https://github.com/MIT-Emerging-Talent/ET6-foundations-group-18/tree/main/solutions)
folder. ✅

## Structure 🏗️

- Each test file corresponds to a function in the [solutions](https://github.com/MIT-Emerging-Talent/ET6-foundations-group-18/tree/main/solutions)
folder. 🔗
- Tests are written using Python's `unittest` framework. 🐍
- Folder structure: `test_file_1.py`, `test_file_2.py`, etc. 📂

## Running Tests ▶️

To run all tests in the folder, use the following command:

```bash
python -m unittest path/to/test/folder
38 changes: 38 additions & 0 deletions solutions/tests/test_area_of_circle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import unittest
from solutions.area_of_circle import area_of_circle


class TestCircleArea(unittest.TestCase):
"""Unit tests for the area_of_circle function."""

def test_positive_radius(self):
"""Test the function with positive radius values."""
self.assertAlmostEqual(area_of_circle(5), 78.53981633974483)
self.assertAlmostEqual(area_of_circle(10), 314.1592653589793)

def test_zero_radius(self):
"""Test the function with a zero radius."""
self.assertEqual(area_of_circle(0), 0.0)

def test_large_radius(self):
"""Test the function with a very large radius."""
self.assertAlmostEqual(area_of_circle(1000), 3141592.653589793)

def test_negative_radius(self):
"""Test the function with a negative radius."""
with self.assertRaises(ValueError) as context:
area_of_circle(-5)
self.assertEqual(str(context.exception), "Radius cannot be negative")

def test_invalid_type(self):
"""Test the function with an invalid type for radius."""
with self.assertRaises(TypeError):
area_of_circle("string")
with self.assertRaises(TypeError):
area_of_circle([1, 2, 3])
with self.assertRaises(TypeError):
area_of_circle(None)


if __name__ == "__main__":
unittest.main()
49 changes: 49 additions & 0 deletions solutions/tests/test_binary_to_hex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
Module: Binary to Hexadecimal Converter
This module provides a utility function to convert binary strings to their
corresponding hexadecimal representations. It validates the input to ensure
that it contains only binary digits (0s and 1s) and performs the conversion
accurately.
Author: Marc Darazi
"""

import unittest
from solutions.binary_to_hex import binary_to_hex


class TestBinaryToHex(unittest.TestCase):
# Unit Tests
def test_binary_to_hex_valid(self):
"""
Test binary_to_hex with valid binary input.
Asserts the correct hexadecimal output is produced.
"""
assert binary_to_hex("1101") == "D"

def test_binary_to_hex_large(self):
"""
Test binary_to_hex with a larger binary input.
Asserts the correct hexadecimal output is produced.
"""
assert binary_to_hex("11110000") == "F0"

def test_binary_to_hex_minimum(self):
"""
Test binary_to_hex with the smallest valid binary input.
Asserts the correct hexadecimal output is produced.
"""
assert binary_to_hex("0") == "0"

def test_binary_to_hex_invalid(self):
"""
Test binary_to_hex with invalid input containing non-binary characters.
Asserts that a ValueError is raised.
"""
try:
binary_to_hex("11012")
except ValueError as e:
assert str(e) == "Input must be a binary string containing only 0s and 1s."
else:
assert False, "ValueError was not raised for invalid input."
60 changes: 60 additions & 0 deletions solutions/tests/test_hex_to_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
This module provides a utility function to convert a hexadecimal string
to its binary representation.
Functions:
- hex_to_binary: Converts a hexadecimal string to its binary equivalent.
Author: Marc Darazi
"""

import unittest
from ..hex_to_binary import hex_to_binary


class TestHexToBinary(unittest.TestCase):
"""
Unit tests for the hex_to_binary function.
These tests validate that the hex_to_binary function correctly converts
hexadecimal strings to binary strings, handling both cases with and
without the '0x' prefix and invalid inputs.
"""

def test_valid_hex_without_prefix(self):
"""
Test converting a valid hexadecimal string without the '0x' prefix.
"""
self.assertEqual(hex_to_binary("1A"), "11010")

def test_valid_hex_with_prefix(self):
"""
Test converting a valid hexadecimal string with the '0x' prefix.
"""
self.assertEqual(hex_to_binary("0xFF"), "11111111")

def test_single_digit_hex(self):
"""
Test converting a single digit hexadecimal string.
"""
self.assertEqual(hex_to_binary("9"), "1001")

def test_hex_with_lowercase_letters(self):
"""
Test converting a hexadecimal string with lowercase letters.
"""
self.assertEqual(hex_to_binary("a"), "1010")

def test_invalid_hex_with_non_hex_characters(self):
"""
Test an invalid hexadecimal string with non-hex characters.
"""
with self.assertRaises(ValueError):
hex_to_binary("G1")

def test_empty_string(self):
"""
Test an empty string as input, which should raise a ValueError.
"""
with self.assertRaises(ValueError):
hex_to_binary("")
Loading

0 comments on commit b1068d1

Please sign in to comment.