Skip to content
This repository was archived by the owner on Jun 13, 2025. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions api/gen_ai/math.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import math
from statistics import mean, variance
from datetime import datetime

Check warning on line 3 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L1-L3

Added lines #L1 - L3 were not covered by tests

# Basic arithmetic functions
def add(a, b):
return a + b

Check warning on line 7 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L6-L7

Added lines #L6 - L7 were not covered by tests

def subtract(a, b):
return a - b

Check warning on line 10 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L9-L10

Added lines #L9 - L10 were not covered by tests

def divide(a, b):
if b == 0:
raise ValueError("Division by zero is not allowed")
return a / b

Check warning on line 15 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L12-L15

Added lines #L12 - L15 were not covered by tests

# Factorial using iterative approach
def factorial(n):
if n < 0:
raise ValueError("Negative numbers do not have factorials")
result = 1
for i in range(1, n + 1):
result *= i
return result

Check warning on line 24 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L18-L24

Added lines #L18 - L24 were not covered by tests
Comment on lines +17 to +24
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The factorial implementation currently uses an iterative approach which could encounter stack overflow for large numbers. Consider adding a maximum input validation to prevent potential resource exhaustion attacks. Also, consider documenting the maximum supported input value in the docstring.

Suggested change
# Factorial using iterative approach
def factorial(n):
if n < 0:
raise ValueError("Negative numbers do not have factorials")
result = 1
for i in range(1, n + 1):
result *= i
return result
def factorial(n):
if n < 0:
raise ValueError("Negative numbers do not have factorials")
if n > 900: # Prevent stack overflow/resource exhaustion
raise ValueError("Input too large. Maximum supported value is 900")
result = 1
for i in range(1, n + 1):
result *= i
return result


# Check if a number is prime
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True

Check warning on line 39 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L27-L39

Added lines #L27 - L39 were not covered by tests

# Fibonacci number generator (nth number)
def fibonacci(n):
if n < 0:
raise ValueError("n must be a non-negative integer")
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b

Check warning on line 52 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L42-L52

Added lines #L42 - L52 were not covered by tests

# Calculator class with memory
class Calculator:
def __init__(self):
self.memory = 0

Check warning on line 57 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L55-L57

Added lines #L55 - L57 were not covered by tests

def add(self, a, b):
return a + b

Check warning on line 60 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L59-L60

Added lines #L59 - L60 were not covered by tests

def subtract(self, a, b):
return a - b

Check warning on line 63 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L62-L63

Added lines #L62 - L63 were not covered by tests

def multiply(self, a, b):
return a * b

Check warning on line 66 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L65-L66

Added lines #L65 - L66 were not covered by tests

def divide(self, a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b

Check warning on line 71 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L68-L71

Added lines #L68 - L71 were not covered by tests

def store(self, value):
self.memory = value

Check warning on line 74 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L73-L74

Added lines #L73 - L74 were not covered by tests

def recall(self):
return self.memory

Check warning on line 77 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L76-L77

Added lines #L76 - L77 were not covered by tests

# String manipulation functions
class StringManipulator:
@staticmethod
def reverse_string(s):
return s[::-1]

Check warning on line 83 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L80-L83

Added lines #L80 - L83 were not covered by tests

@staticmethod
def is_palindrome(s):
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]

Check warning on line 88 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L85-L88

Added lines #L85 - L88 were not covered by tests

# Data processing class for numerical lists
class DataProcessor:
def __init__(self, data):
if not data:
raise ValueError("Data list cannot be empty")
self.data = data

Check warning on line 95 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L91-L95

Added lines #L91 - L95 were not covered by tests

def get_mean(self):
return mean(self.data)

Check warning on line 98 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L97-L98

Added lines #L97 - L98 were not covered by tests

def get_variance(self):
if len(self.data) < 2:
raise ValueError("At least two data points are required to compute variance")
return variance(self.data)

Check warning on line 103 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L100-L103

Added lines #L100 - L103 were not covered by tests

def normalize(self):
m = self.get_mean()
try:
std_dev = math.sqrt(variance(self.data))
except Exception:
raise ValueError("Could not compute standard deviation")
Comment on lines +102 to +110
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The normalize method in DataProcessor is not handling potential division by zero correctly. While there is a check for std_dev == 0, the sqrt operation could still raise a ValueError. Consider adding proper error handling and documentation about expected behavior in edge cases.

Suggested change
raise ValueError("At least two data points are required to compute variance")
return variance(self.data)
def normalize(self):
m = self.get_mean()
try:
std_dev = math.sqrt(variance(self.data))
except Exception:
raise ValueError("Could not compute standard deviation")
def normalize(self):
m = self.get_mean()
try:
std_dev = math.sqrt(self.get_variance())
if std_dev == 0:
raise ValueError("Standard deviation is zero, cannot normalize.")
return [(x - m) / std_dev for x in self.data]
except ValueError as e:
raise ValueError(f"Normalization failed: {str(e)}")

if std_dev == 0:
raise ValueError("Standard deviation is zero, cannot normalize.")
return [(x - m) / std_dev for x in self.data]

Check warning on line 113 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L105-L113

Added lines #L105 - L113 were not covered by tests

# Date parsing function with a default format
def parse_date(date_str, fmt="%Y-%m-%d"):
try:
return datetime.strptime(date_str, fmt)
except ValueError:
raise ValueError("Incorrect date format, should be YYYY-MM-DD")

Check warning on line 120 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L116-L120

Added lines #L116 - L120 were not covered by tests

# Safe access to list elements with default value
def safe_list_access(lst, index, default=None):
try:
return lst[index]
except IndexError:
return default

Check warning on line 127 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L123-L127

Added lines #L123 - L127 were not covered by tests

# Merge two dictionaries recursively
def merge_dicts(dict1, dict2):
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = merge_dicts(result[key], value)

Check warning on line 134 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L130-L134

Added lines #L130 - L134 were not covered by tests
Comment on lines +127 to +134
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The merge_dicts function could potentially cause runtime errors with very deep dictionaries due to recursive calls. Consider adding a depth limit parameter and check to prevent stack overflow in case of maliciously crafted input.

Suggested change
return default
# Merge two dictionaries recursively
def merge_dicts(dict1, dict2):
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = merge_dicts(result[key], value)
def merge_dicts(dict1, dict2, max_depth=10, current_depth=0):
if current_depth >= max_depth:
raise ValueError(f"Maximum merge depth of {max_depth} exceeded")
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = merge_dicts(result[key], value, max_depth, current_depth + 1)
else:
result[key] = value
return result

else:
result[key] = value
return result

Check warning on line 137 in api/gen_ai/math.py

View check run for this annotation

Codecov Notifications / codecov/patch

api/gen_ai/math.py#L136-L137

Added lines #L136 - L137 were not covered by tests

Loading
Loading