Skip to content

Commit

Permalink
Merge branch 'main' into count_words
Browse files Browse the repository at this point in the history
  • Loading branch information
sashour82 authored Jan 7, 2025
2 parents bda59e4 + 375a9d3 commit be1a2ef
Show file tree
Hide file tree
Showing 11 changed files with 528 additions and 3 deletions.
19 changes: 17 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,22 @@

// Enable/disable update table of contents on save
"markdown.extension.toc.updateOnSave": false,

"[python]": {

"editor.defaultFormatter": "ms-python.black-formatter"
}
}
},
"cSpell.words": [
"catdog",
"cathatbat",
"Falaq",
"Truehello",
=======
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.ruff": "explicit",
"source.organizeImports.ruff": "explicit"
}
},

2 changes: 2 additions & 0 deletions solutions/IsPrime.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ def IsPrime(a: int) -> str:
prime
>>> IsPrime(2.5)
invalid input
>>> IsPrime(-1)
not prime
"""
if not isinstance(a, int):
return "invalid input"
Expand Down
57 changes: 57 additions & 0 deletions solutions/cumulative_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module: cumulative_sum
Description:
This module provides a function to calculate the cumulative sum of
a list of numbers(integers\float). It is useful for applications requiring progressive
accumulation of values, such as financial calculations, data analysis,
or custom mathematical operations.
Module Contents:
- cumulative_sum(numbers: list) -> list:
Computes and returns a list of cumulative sums from the input list.
Author: Falaq Youniss
Date: 29/12/2024
"""


def cumulative_sum(numbers: list) -> list:
"""
Computes the cumulative sum of a list of numbers.
Args:
numbers (list): A list of numeric values (integers or floats).
Returns:
list: A list where each element is the cumulative sum up to that index.
Raises:
AssertionError:
- If the input is not a list.
- If the list contains non-numeric values.
- If the input is `None`.
>>> cumulative_sum([1, 2, 3, 4])
[1, 3, 6, 10]
>>> cumulative_sum([-1, -2, -3, -4])
[-1, -3, -6, -10]
>>> cumulative_sum([1.0, 2.0, 3.0, 4.0])
[1.0, 3.0, 6.0, 10.0]
"""
# Validate input
assert numbers is not None, "Input cannot be None."
assert isinstance(numbers, list), "Input must be a list of numeric values."
assert all(
isinstance(num, (int, float)) for num in numbers
), "All elements in the list must be numeric."
# Compute cumulative sums
cumulative_list = []
current_sum = 0
for num in numbers:
current_sum += num
cumulative_list.append(current_sum)

return cumulative_list
56 changes: 56 additions & 0 deletions solutions/factorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A module for Computing the factorial of a non-negative integer n.
Module contents:
- factorial: is the product of all positive integers less than or equal to n.
Created on XX XX XX
@author: Saad M. Ashour
"""


def factorial(n: int) -> int:
"""
Computes the factorial of a non-negative integer n.
The factorial of a non-negative integer n
is the product of all positive integers less than or equal to n.
Parameters:
n (int): A non-negative integer.
Returns:
int: The factorial of the input integer n.
Raises:
ValueError: If n is negative, as factorial is not defined for negative numbers.
TypeError: If n is not an integer, as factorials are only defined for integers.
Examples:
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(5)
120
>>> factorial(3)
6
"""
# Validate input type and value
if not isinstance(n, int):
raise TypeError("Input must be an integer.")

if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")

# Base case for recursion: 0! = 1
if n == 0 or n == 1:
return 1

# Recursive case: n! = n * (n-1)!
return n * factorial(n - 1)
60 changes: 60 additions & 0 deletions solutions/list_to_string.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module: List to String Converter
Description:
This module provides a function to convert a list of elements (integers, floats,
strings, booleans) into a single concatenated string. It handles various data
types and ensures that all elements are appropriately converted to strings and joined together.
Module Contents:
- list_to_string(lst: list) -> str:
Converts a list of elements into a single concatenated string.
Ensures proper handling of different data types and raises appropriate errors
for invalid inputs.
Author: Falaq Youniss
Date: 30/12/2024
"""


def list_to_string(lst: list) -> str:
"""
Converts a list of elements into a single concatenated string.
Args:
lst (list): A list of items which can include integers, floats, strings,
or booleans.
Returns:
str: A string that combines all elements of the list.
Raises:
AssertionError:
- If the input is not a list.
- If the input is `None`.
- If the list is empty.
>>> list_to_string([1, -4, 3.14])
'1-43.14'
>>> list_to_string([True, 'hello'])
'Truehello'
>>> list_to_string(['cat', 'hat', 'bat'])
'cathatbat'
"""
# Validate Input
assert isinstance(lst, list), "Input must be a list."
assert lst is not None, "The input cannot be None."
assert len(lst) > 0, "The list cannot be empty."

# Initialize an empty result string
result = ""

# Iterate through the list and convert each element to a string
for element in lst:
result += str(element) # Convert each element to string and concatenate

return result
34 changes: 34 additions & 0 deletions solutions/mean.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A module for finding the mean of a list of numbers.
Module contents:
- mean: finds the mean of a list of numbers.
Created on 29/12/2024
@author: Mohammed Elfadil
"""


def mean(a: list) -> float:
"""Finds the mean of a list of numbers.
Parameter:
a: list
Return -> float: the mean of the list
Raises:
AssertionError: if the argument is not a list
>>> mean([1, 2, 3, 4, 5])
3.0
>>> mean([10, 20, 30, 40, 50])
30.0
>>> mean([1.5, 2.5, 3.5])
2.5
>>>mean([2])
2.0
"""
# check if the argument is a list
assert isinstance(a, list), "invalid input"

# return the mean of the list by dividing the sum of the list by the length of the list
return sum(a) / len(a)
1 change: 0 additions & 1 deletion solutions/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@

94 changes: 94 additions & 0 deletions solutions/tests/test_cumulative_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module: test_cumulative_sum
Description:
This module contains test cases for the `cumulative_sum` function defined
in the `cumulative_sum.py` module. It tests the function's behavior with
various input scenarios, ensuring that it handles different edge cases and
returns the expected cumulative sums.
Test Categories:
- Standard cases: List of positive integers, negative integers, and floating-point numbers.
- Edge cases: Empty list, single-element list, list with zeros, large number list.
- Defensive tests: None input, Non-list inputs, list with non-numeric elements.
Author: Falaq Youniss
Date: 29/12/2024
"""

import unittest
from ..cumulative_sum import cumulative_sum


class TestCumulativeSum(unittest.TestCase):
"""Test for cumulative_sum function that handles different cases"""

# Standard test cases
def test_positive_int(self):
"""It should return a cumulative list of positive integers."""
self.assertEqual(cumulative_sum([1, 2, 3, 4]), [1, 3, 6, 10])

def test_negative_int(self):
"""It should return a cumulative list of negative integers."""
self.assertEqual(cumulative_sum([-1, -2, -3, -4]), [-1, -3, -6, -10])

def test_positive_float(self):
"""It should return a cumulative list of positive floats."""
self.assertEqual(cumulative_sum([1.0, 2.0, 3.0, 4.0]), [1.0, 3.0, 6.0, 10.0])

def test_negative_float(self):
"""It should return a cumulative list of negative floats."""
self.assertEqual(
cumulative_sum([-1.0, -2.0, -3.0, -4.0]), [-1.0, -3.0, -6.0, -10.0]
)

def test_positive_negative(self):
"""It should return a cumulative list of negative and positive integers."""
self.assertEqual(cumulative_sum([-1, 2, -3, 4]), [-1, 1, -2, 2])

def test_integer_float(self):
"""It should return a cumulative list of integers and floats."""
self.assertEqual(cumulative_sum([1.0, 2, 3.0, 4]), [1, 3, 6.0, 10.0])

def test_combination(self):
"""It should return a cumulative list of mixed positive and negative integers/floats."""
self.assertEqual(cumulative_sum([1.0, -2, -3.0, 4]), [1, -1, -4, 0])

def test_same(self):
"""It should return a cumulative list of positive integers."""
self.assertEqual(cumulative_sum([3, 3, 3]), [3, 6, 9])

# Edge cases
def test_zero(self):
"""It should return a list of zeros."""
self.assertEqual(cumulative_sum([0, 0, 0, 0]), [0, 0, 0, 0])

def test_empty(self):
"""It should return an empty list."""
self.assertEqual(cumulative_sum([]), [])

def test_one(self):
"""It should return the same single-item list."""
self.assertEqual(cumulative_sum([1]), [1])

def test_large_numbers(self):
"""It should correctly handle large numbers."""
self.assertEqual(cumulative_sum([1e6, 2e6, 3e6]), [1e6, 3e6, 6e6])

# Defensive tests
def test_none(self):
"""It should raise AssertionError for None input."""
with self.assertRaises(AssertionError):
cumulative_sum(None)

def test_not_list(self):
"""It should raise AssertionError for non-list input."""
with self.assertRaises(AssertionError):
cumulative_sum("hello")

def test_not_num(self):
"""It should raise AssertionError for non-numeric list elements."""
with self.assertRaises(AssertionError):
cumulative_sum([1, "cat", 3])
Loading

0 comments on commit be1a2ef

Please sign in to comment.