commit db78cde367a2fbb8bf90e3592be0824f37cb85e9
parent ac0b68f991db1ca245fea0cdc04fb1183783a32d
Author: Amit Dutta <amitdutta4255@gmail.com>
Date: Sun, 17 Aug 2025 19:35:39 +0530
Add files via upload
Diffstat:
| A | adcustom.py | | | 650 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | finance.py | | | 116 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | test1.py | | | 335 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | test2.py | | | 191 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | test3.py | | | 106 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | test4.py | | | 25 | +++++++++++++++++++++++++ |
| A | test5.py | | | 29 | +++++++++++++++++++++++++++++ |
| A | triangle.py | | | 75 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
8 files changed, 1527 insertions(+), 0 deletions(-)
diff --git a/adcustom.py b/adcustom.py
@@ -0,0 +1,649 @@
+# Prime check function
+
+def check_prime(inp) :
+ """
+ Checks the input integers is a Prime number or not.
+
+ Args:
+ inp = The non-negetive integer to check
+
+ Returns:
+ 1 if input integer is Prime, 0 if input integer is not Prime.
+ None if the input is not valid or any error occurs.
+ """
+ #trying to check if the input is valid integer or not
+ try :
+ temp = int(inp)
+ except ValueError :
+ print('Error : Plese enter a valid integer.')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ # handling negetive integers
+ if temp < 0 :
+ print('Error : Please enter a non-negetive integer.')
+ return None
+ #handling integers <= 3
+ if temp < 2 :
+ return 0 # '0' means not prime.
+ if temp <= 3 :
+ return 1 # '1' means prime.
+ if temp % 2 == 0 :
+ return 0 # there is no even number that is prime except '2', this was checked before.
+ #main logic to check prime or not
+ try :
+ for i in range (3, (temp // 2) + 1) :
+ if temp % i == 0 :
+ return 0
+ return 1
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+# factorial function
+
+def factorial(inp) :
+ """
+ Calculates the factorial of given integer
+
+ Args:
+ inp = an non-negetive integer
+
+ Returns:
+ the factorial of the non-negetive integer.
+ None if the input is not valid or any error occurs.
+ """
+ # trying to check if input is a valid integer or not
+ try :
+ temp = int(inp)
+ except ValueError :
+ print('Error : Plese enter a valid integer.')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ # handling negetive integer
+ if temp < 0 :
+ print('Error : Please enter a non-negetive integer.')
+ return None
+ # handling inp '0'
+ if temp == 0 :
+ return 1
+ # main logic for factorial
+ try :
+ result = 1
+ for i in range(2, temp + 1) :
+ result = result * i
+ return result
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+# permutation function
+
+def permutation(total_item,chosen_item) :
+ """
+ Calculates the number of permutations p(n, k).
+
+ Args:
+ total_item = the total number of distinct items in the set
+ chosen_item = the number of items to be arranged or chosen from the set at a time
+
+ Returns:
+ The number of permutations.
+ None if the input is not valid or any error occurs.
+ """
+ # trying to check if the inputs are a valid integer or not.
+ try :
+ n = int(total_item)
+ k = int(chosen_item)
+ except ValueError :
+ print('Error : Please enter a valid integer.')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ # handling negetive integer
+ if n < 0 or k < 0 :
+ print('Error : Please enter non-negetive integer.')
+ return None
+ if k > n :
+ print('Error : Chosen item should be lower than Total item.')
+ return None
+ # main logic for permutation
+ try :
+ fact_n = factorial(n)
+ fact_n_k = factorial(n-k)
+ result = fact_n / fact_n_k
+ return int(result)
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+# combination function
+
+def combination(total_item, chosen_item) :
+ """
+ Calculates the number of combination c(n, k).
+
+ Args:
+ total_item = the total number of distinct items in the set
+ chosen_item = the number of items to be arranged or chosen from the set at a time
+
+ Returns:
+ The number of combinations.
+ None if the input is not valid or any error occurs.
+ """
+ # trying to check if the inputs are a valid integer or not.
+ try :
+ n = int(total_item)
+ k = int(chosen_item)
+ except ValueError :
+ print('Error : Please enter a valid integer.')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ # handling negetive integer
+ if n < 0 or k < 0 :
+ print('Error : Please enter non-negetive integer.')
+ return None
+ if k > n :
+ return 0 # if total item is lower than chosen then their is no possible combinaition.
+ # main logic for combination
+ try :
+ fact_n = factorial(n)
+ fact_k = factorial(k)
+ fact_n_k = factorial(n-k)
+ result = fact_n / (fact_n_k * fact_k)
+ return int(result)
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+# reverse string function
+
+def string_reverse(string) :
+ """
+ Reverse the given string
+
+ Args:
+ string = The given string
+
+ Returns:
+ Reverse string of the given string
+ None if the input is not valid or any error occurs.
+ """
+ # trying to check if the input is a string
+ try :
+ temp = str(string)
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ # handing empty string
+ if temp == '' :
+ print('Error : Input should not be a empty string.')
+ return None
+ # main logic
+ try :
+ result = ''
+ for char in temp :
+ result = char + result
+ return result
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+# matrix checking function
+
+def is_matrix_valid(matrix) :
+ """
+ Helper to validate if an input is a list of lists representing a matrix.
+
+ Args:
+ matrix = A matrix that will be checked.
+
+ Returns:
+ True if the matrix is valid. False if not.
+ """
+ try :
+ #checking if the list is empty or not / trying to check is the input matrix is empty or not
+ row_count = 0
+ for row in matrix :
+ row_count += 1
+
+ if row_count == 0 :
+ print('Error: Matrix must be a non-empty list of lists.')
+ return False
+
+ #trying to check if the list is 'list of lists', trying to check if the matrix have both row and column
+ first_row = matrix[0]
+ col_count_first_row = 0
+ for val in first_row :
+ col_count_first_row += 1
+
+ if col_count_first_row == 0 :
+ print('Error : Matrix should have non-empty lists as rows.')
+ return False
+
+ # checking if All rows in the matrix have the same number of columns
+ for row_index in range(row_count) :
+ current_row = matrix[row_index]
+
+ current_col_count = 0
+ for col in current_row :
+ current_col_count += 1
+
+ if current_col_count != col_count_first_row :
+ print('All rows in the matrix must have the same number of columns')
+ return False
+
+ #checking if columns have a number by attempting a conversion
+ for col_index in range(current_col_count) :
+ element = current_row[col_index]
+
+ try :
+ checker = float(element)
+ except (ValueError, TypeError) :
+ print('Error : Matrix elements should be a number(Integer or Float number).')
+ except Exception as error :
+ print(f'Error : An uncxpected error happened : {error}')
+ return False
+
+ return True # if all check passed
+
+ except Exception as error :
+ print(f'Error : An uncxpected error happened : {error}')
+ return False
+
+# matrix multiplication function
+
+def matrix_addition(matrix1, matrix2) :
+ """
+ Add two input matrix
+
+ Args:
+ matrix1 = first matrix
+ matrix2 = second matrix
+
+ Returns:
+ Matrix after adding two input matrix.
+ None if the input is not valid or any error occurs.
+ """
+ # checking if the matrix are valid or not
+ if not is_matrix_valid(matrix1) :
+ print('Error : First matrix is not valid.')
+ return None
+ if not is_matrix_valid(matrix2) :
+ print('Error : Second matrix is not valid.')
+ return None
+
+ # checking matrix dimension are same or not.
+ row_count_mat1 = len(matrix1)
+ col_count_mat1 = len(matrix1[0])
+
+ row_count_mat2 = len(matrix2)
+ col_count_mat2 = len(matrix2[0])
+
+ if row_count_mat1 != row_count_mat2 or col_count_mat1 != col_count_mat2 :
+ print('Error : Matrix dimension should be same for both matrix to do addition.')
+ return None
+
+ try :
+ result_matrix = []
+ for i in range(row_count_mat1) :
+ result_matrix_row = []
+ for j in range(col_count_mat1) :
+ result_matrix_element = matrix1[i][j] + matrix2[i][j]
+ result_matrix_row.append(result_matrix_element)
+ result_matrix.append(result_matrix_row)
+
+ string_result_matrix = ''
+ for row in result_matrix :
+ for element in row :
+ string_result_matrix = string_result_matrix + str(element) + ' '
+ string_result_matrix = string_result_matrix + '\n'
+ return string_result_matrix
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+# matrix multiplication function
+
+def matrix_multiplication(matrix1, matrix2) :
+ """
+ Multiply one input matrix with another input matrix.
+
+ Args:
+ matrix1 = first matrix
+ matrix2 = second matrix
+
+ Returns:
+ Matrix after multiplying
+ None if the input is not valid or any error occurs.
+ """
+ # checking if the matrix are valid or not
+ if not is_matrix_valid(matrix1) :
+ print('Error : First matrix is not valid.')
+ return None
+ if not is_matrix_valid(matrix2) :
+ print('Error : Second matrix is not valid.')
+ return None
+
+ # checking matrix dimension as the column_count of the first matrix and the row_count of the second matrix should be same
+ row_count_mat1 = len(matrix1)
+ col_count_mat1 = len(matrix1[0])
+
+ row_count_mat2 = len(matrix2)
+ col_count_mat2 = len(matrix2[0])
+
+ if col_count_mat1 != row_count_mat2 :
+ print('Error : Column_count of the first matrix and the Row_count of the second matrix should be same to do multiplication.')
+ return None
+
+ try :
+ result_matrix = []
+ for i in range(row_count_mat1) : # taking the row of the matrix1
+ result_matrix_row = []
+ for j in range(col_count_mat2) : # taking the column of the matrix2
+ result_matrix_element = 0
+ for k in range(col_count_mat1) : # taking the column of the matrix1.
+ """
+ এখন, 'k' এর লুপ একবার সম্পন্ন হলে, 'i' এর জন্য matrix1
+ এর সারি একই থাকবে, 'j' এর জন্য matrix2 এর কলাম একই থাকবে,
+ কিন্তু 'k' এর মান পরিবর্তনের সাহায্যে, matrix1 এর কলাম এবং matrix2
+ এর সারি পরিবর্তন করা যেতে পারে। 'j' পরিবর্তন হলে, matrix2 এর
+ কলাম পরিবর্তন হবে। অর্থাৎ, কাজটি এই প্রবাহে হবে: প্রথমে, matrix1
+ এর সারিটি নেবে এবং matrix2 এর কলাম পরিবর্তন করে এটিকে গুণ
+ করবে। সমস্ত কলাম শেষ হয়ে গেলে, তারপর matrix1 এর পরবর্তী সারিতে যাবে।
+ """
+ result_matrix_element += matrix1[i][k] * matrix2[k][j]
+ result_matrix_row.append(result_matrix_element)
+ result_matrix.append(result_matrix_row)
+
+ string_result_matrix = ''
+ for row in result_matrix :
+ for element in row :
+ string_result_matrix = string_result_matrix + str(element) + ' '
+ string_result_matrix = string_result_matrix + '\n'
+ return string_result_matrix
+ except Exception as error :
+ print(f'An unexpected error happened : {error}')
+ return None
+
+# matrix transpose function
+
+def matrix_transpose(matrix) :
+ """
+ Transpose a matrix(row becomes column, column becomes row)
+
+ Args:
+ matrix = Input matrix given by user
+
+ Returns:
+ Matrix after transposing
+ None if the input is not valid or any error occurs.
+ """
+ # checking if the matrix are valid or not
+ if not is_matrix_valid(matrix) :
+ print('Error : Given matrix is not valid.')
+ return None
+
+ row = len(matrix)
+ column = len(matrix[0])
+
+ try :
+ result_matrix = []
+ for i in range(column) :
+ result_matrix_row = []
+ for j in range(row) :
+ result_matrix_row.append(matrix[j][i])
+ result_matrix.append(result_matrix_row)
+
+ string_result_matrix = ''
+ for row in result_matrix :
+ for element in row :
+ string_result_matrix = string_result_matrix + str(element) + ' '
+ string_result_matrix = string_result_matrix + '\n'
+ return string_result_matrix
+ except Exception as error :
+ print(f'An unexpected error happened : {error}')
+ return None
+
+# determinant_value function
+
+def determinant_value(matrix) :
+ """
+ Calculates the determinant value of given matrix
+
+ Args:
+ matrix = Input matrix given by user
+
+ Returns:
+ Determinant value of given matrix
+ None if the input is not valid or any error occurs.
+ """
+ # checking if the matrix are valid or not
+ if not is_matrix_valid(matrix) :
+ print('Error : Given matrix is not valid.')
+ return None
+
+ row = len(matrix)
+ column = len(matrix[0])
+
+ if row != column :
+ print('Error : Row count and the Column count should be same.')
+ return None
+
+ if row > 3 :
+ print('Error : This function is currently allowing up to 3 x 3 matrix')
+ return None
+
+ if row == 1 :
+ return matrix[0][0]
+
+ if row == 2 :
+ try :
+ for i in range(row) :
+ for j in range(column) :
+ result = ((matrix[i][j] * matrix[i+1][j+1]) - (matrix[i][j+1] * matrix[i+1][j]))
+ return result
+
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+ if row == 3 :
+ try :
+ first_part = (matrix[0][0] * ((matrix[1][1] * matrix[2][2]) - (matrix[1][2] * matrix[2][1])))
+ second_part = (matrix[0][1] * ((matrix[1][0] * matrix[2][2]) - (matrix[1][2] * matrix[2][0])))
+ third_part = (matrix[0][2] * ((matrix[1][0] * matrix[2][1]) - (matrix[1][1] * matrix[2][0])))
+ result = first_part - second_part + third_part
+ return result
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+# mean-median-node fuction
+
+def mean(inp_set) :
+ """
+ Gives the mean value of a set
+
+ Args:
+ set = Input set given by user
+
+ Returns:
+ Mean value of the input set.
+ None if the input is not valid or any error occurs.
+ """
+ temp = [] # this new list will be used to take out all elements as float number.
+ try :
+ set_len = len(inp_set)
+
+ if set_len == 0 :
+ print('Error : Set should not be empty.')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ try :
+ for element in inp_set :
+ checker = float(element)
+ temp.append(checker)
+ except ValueError :
+ print('Error : Please enter a valid number(Integer or Float).')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ try :
+ element_total = 0.0
+ for element in temp :
+ element_total = element_total + element # summation of the set element
+
+ result = element_total / float(set_len)
+ return result
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+def median(inp_set) :
+ """
+ Gives the median value of a set
+
+ Args:
+ set = Input set given by user
+
+ Returns:
+ Median value of the input set.
+ None if the input is not valid or any error occurs.
+ """
+ temp = [] # this new list will be used to take out all elements as float number.
+ try :
+ set_len = len(inp_set)
+
+ if set_len == 0 :
+ print('Error : Set should not be empty.')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+ try :
+ for element in inp_set :
+ checker = float(element)
+ temp.append(checker)
+ except ValueError :
+ print('Error : Please enter a valid number(Integer or Float).')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+ # trying to order the list if not.
+ # here 'bubble sort' is used, maybe i should use sort() function.
+ # actually i dont know how to use sort() function
+ try :
+ for counter in range(1, set_len+1) :
+ for ele_index in range(set_len - counter) :
+ if temp[ele_index] > temp[ele_index + 1] :
+ temp[ele_index], temp[ele_index + 1] = temp[ele_index + 1], temp[ele_index]
+
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+ # if the set have odd element count, like 1, 3, 5, 7, 9 etc
+ if set_len % 2 == 1 :
+ try :
+ middle_index = (set_len // 2) + 1 # for example, if we have a set with 5 element then (set_len // 2) will be 2 and plus one 3
+ return temp[middle_index - 1] # python's 0-based indexing
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+ # if the set have even element count, like 2, 4, 6, 8 etc
+ if set_len % 2 == 0 :
+ try :
+ first_middle_index = set_len // 2
+ second_middle_index = first_middle_index + 1
+
+ middle_avg = (temp[first_middle_index - 1] + temp[second_middle_index - 1]) / 2 # python's 0-based indexing
+ return middle_avg
+
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+def mode(inp_set) :
+ """
+ Gives the mode value of a set
+
+ Args:
+ set = Input set given by user
+
+ Returns:
+ Mode value of the input set.
+ None if the input is not valid or any error occurs.
+ """
+ # mode function can be used for any data type.
+ try :
+ set_len = len(inp_set)
+ if set_len == 0 :
+ print('Error : Set should not be empty.')
+ return None
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+ # trying to get the total number of times a element appeared in the set
+ try :
+ processed_elements_list = []
+ element_details = []
+
+ for i in range(set_len) :
+ current_element = inp_set[i]
+ already_done = False
+
+ for processed_element in processed_elements_list :
+ if current_element == processed_element :
+ already_done = True
+ break
+
+ if not already_done :
+ count = 0
+ for j in range(set_len) :
+ if current_element == inp_set[j] :
+ count += 1
+
+ element_details.append([current_element, count])
+ processed_elements_list.append(current_element)
+
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+ # now sending the mode data
+ try :
+ if not element_details: # Handle case where element_details might be empty (e.g., if inp_set was empty, though handled earlier)
+ return None
+
+ highest_count = 0
+ for i in range(len(element_details)) :
+ if element_details[i][1] > highest_count :
+ highest_count = element_details[i][1]
+
+ highest_count_element = []
+ for i in range(len(element_details)) :
+ if element_details[i][1] == highest_count :
+ highest_count_element.append(element_details[i][0])
+
+ return highest_count_element, highest_count
+
+ except Exception as error :
+ print(f'Error : An unexpected error happened : {error}')
+ return None
+
+
+# the end+
\ No newline at end of file
diff --git a/finance.py b/finance.py
@@ -0,0 +1,116 @@
+# This module contains an interest calculator
+# Formula used for compound interest: A = P * (1 + r / n) ** (n * t)
+
+def interest(prime_amount, time_duration_str, number_of_times_interest_will_compound_per_year, rate_of_interest) :
+ """
+ Calculates the compound interest.
+
+ Args:
+ prime_amount (float or int): The initial principal amount (P).
+ time_duration_str (str): The duration for which the interest is calculated,
+ **must be in specific short-hand formats**:
+ - "XyYm" (e.g., "5y6m", "1y8m" for 1 year 8 months)
+ - "Xm" (e.g., "15m", "6m" for 15 months, 6 months)
+ - "Xy" (e.g., "5y", "1y" for 5 years, 1 year)
+ Where X and Y are whole numbers.
+ number_of_times_interest_will_compound_per_year (float or int):
+ The number of times interest is compounded per year (n).
+ (e.g., 2 for half-yearly, 4 for quarterly, 12 for monthly, 365 for daily).
+ rate_of_interest (float or int): The annual nominal interest rate (as a percentage, e.g., 5 for 5%).
+
+ Returns:
+ float: The compound interest amount earned, rounded to 3 decimal places.
+ None: If the input is not valid or any error occurs.
+ """
+
+ # Convert and validate numeric inputs (P, N, R)
+ try:
+ p = float(prime_amount)
+ n = float(number_of_times_interest_will_compound_per_year)
+ r = float(rate_of_interest)
+ except ValueError:
+ print('Error: Please enter valid numbers (integer or float) for Prime Amount, Compounding Frequency, and Rate of Interest.')
+ return None
+ except Exception as error:
+ print(f'An unexpected error happened during initial input conversion: {error}')
+ return None
+
+ # Parse and validate 'time_duration_str' without 're' module
+ total_time_in_years = 0.0
+ # Normalize input string for consistent parsing
+ time_str_normalized = str(time_duration_str).lower().strip()
+
+ years = 0
+ months = 0
+ is_valid_format = False
+
+ if 'y' in time_str_normalized and 'm' in time_str_normalized:
+ # Potentially XyYm format
+ y_index = time_str_normalized.find('y')
+ m_index = time_str_normalized.find('m')
+
+ if y_index != -1 and m_index != -1 and y_index < m_index:
+ years_part = time_str_normalized[:y_index]
+ months_part = time_str_normalized[y_index + 1 : m_index]
+
+ if years_part.isdigit() and months_part.isdigit():
+ years = int(years_part)
+ months = int(months_part)
+ total_time_in_years = years + (months / 12.0)
+ is_valid_format = True
+
+ if not is_valid_format: # If XyYm wasn't matched or was invalid, try other formats
+ if time_str_normalized.endswith('m') and 'y' not in time_str_normalized:
+ # Format: Xm
+ months_part = time_str_normalized[:-1] # Remove 'm'
+ if months_part.isdigit():
+ months = int(months_part)
+ total_time_in_years = months / 12.0
+ is_valid_format = True
+ elif time_str_normalized.endswith('y') and 'm' not in time_str_normalized:
+ # Format: Xy
+ years_part = time_str_normalized[:-1] # Remove 'y'
+ if years_part.isdigit():
+ years = int(years_part)
+ total_time_in_years = float(years)
+ is_valid_format = True
+
+ if not is_valid_format:
+ print(f"Error: Invalid time duration format: '{time_duration_str}'.")
+ print("Please use formats like '5y6m', '15m', or '5y'.")
+ return None
+
+ # Final validation for parsed time
+ if total_time_in_years <= 0:
+ print('Error: Time duration must be a positive value.')
+ return None
+
+ # Validate other numeric data (after time parsing, before main logic)
+ if p <= 0:
+ print('Error: Prime amount should be greater than Zero.')
+ return None
+ if n <= 0:
+ print('Error: The number of times the interest will compound per year should be greater than Zero.')
+ return None
+ if r <= 0:
+ print('Error: Rate of Interest should be greater than Zero.')
+ return None
+
+ # Main calculation logic
+ try :
+ r_decimal = r / 100.0 # Change percentage to decimal (using 100.0 for float division)
+
+ # Calculate the total amount after compounding with full precision
+ total_amount_precise = p * (1 + r_decimal / n) ** (n * total_time_in_years)
+
+ # Calculate the compound interest with full precision
+ compound_interest_precise = total_amount_precise - p
+
+ # Round the final interest amount to 3 decimal places before returning
+ result = round(compound_interest_precise, 3)
+
+ return result
+
+ except Exception as error :
+ print(f'An unexpected error happened during calculation: {error}')
+ return None
diff --git a/test1.py b/test1.py
@@ -0,0 +1,334 @@
+import adcustom as c
+
+print("--- Comprehensive Test Suite for custom module ---")
+
+# --- Helper function to check test results ---
+def check_test(test_name, result, expected, function_prints_error=False):
+ """
+ Checks the test result against the expected value.
+ 'function_prints_error' is set to True if the tested function is expected
+ to print an error message to console instead of just returning None.
+ """
+ print(f" Test Status: ", end="")
+ if result == expected:
+ print(f"PASS")
+ else:
+ print(f"FAIL - Expected {expected}, Got {result}")
+ if function_prints_error:
+ print(" (Note: The function may have printed an error message above)")
+
+# --- Test Cases for check_prime() ---
+print("\n--- Testing check_prime() function ---")
+result_prime_1 = c.check_prime(7)
+print(f"Test check_prime 1: 7")
+print(f"Expected: 1")
+print(f"Result: {result_prime_1}")
+check_test("check_prime 1", result_prime_1, 1)
+
+result_prime_2 = c.check_prime(10)
+print(f"\nTest check_prime 2: 10")
+print(f"Expected: 0")
+print(f"Result: {result_prime_2}")
+check_test("check_prime 2", result_prime_2, 0)
+
+result_prime_3 = c.check_prime(2)
+print(f"\nTest check_prime 3: 2 (edge case)")
+print(f"Expected: 1")
+print(f"Result: {result_prime_3}")
+check_test("check_prime 3", result_prime_3, 1)
+
+result_prime_4 = c.check_prime(1)
+print(f"\nTest check_prime 4: 1 (not prime)")
+print(f"Expected: 0")
+print(f"Result: {result_prime_4}")
+check_test("check_prime 4", result_prime_4, 0)
+
+result_prime_5 = c.check_prime(-5)
+print(f"\nTest check_prime 5: -5 (negative input)")
+print(f"Expected: None")
+print(f"Result: {result_prime_5}")
+check_test("check_prime 5", result_prime_5, None, function_prints_error=True)
+
+result_prime_6 = c.check_prime("abc")
+print(f"\nTest check_prime 6: 'abc' (invalid input type)")
+print(f"Expected: None")
+print(f"Result: {result_prime_6}")
+check_test("check_prime 6", result_prime_6, None, function_prints_error=True)
+
+# --- Test Cases for factorial() ---
+print("\n--- Testing factorial() function ---")
+result_fact_1 = c.factorial(5)
+print(f"Test factorial 1: 5")
+print(f"Expected: 120")
+print(f"Result: {result_fact_1}")
+check_test("factorial 1", result_fact_1, 120)
+
+result_fact_2 = c.factorial(0)
+print(f"\nTest factorial 2: 0 (edge case)")
+print(f"Expected: 1")
+print(f"Result: {result_fact_2}")
+check_test("factorial 2", result_fact_2, 1)
+
+result_fact_3 = c.factorial(-3)
+print(f"\nTest factorial 3: -3 (negative input)")
+print(f"Expected: None")
+print(f"Result: {result_fact_3}")
+check_test("factorial 3", result_fact_3, None, function_prints_error=True)
+
+# --- Test Cases for permutation() ---
+print("\n--- Testing permutation() function ---")
+result_perm_1 = c.permutation(5, 2)
+print(f"Test permutation 1: P(5, 2)")
+print(f"Expected: 20")
+print(f"Result: {result_perm_1}")
+check_test("permutation 1", result_perm_1, 20)
+
+result_perm_2 = c.permutation(3, 3)
+print(f"\nTest permutation 2: P(3, 3)")
+print(f"Expected: 6")
+print(f"Result: {result_perm_2}")
+check_test("permutation 2", result_perm_2, 6)
+
+result_perm_3 = c.permutation(5, 7)
+print(f"\nTest permutation 3: P(5, 7) (k > n)")
+print(f"Expected: None")
+print(f"Result: {result_perm_3}")
+check_test("permutation 3", result_perm_3, None, function_prints_error=True)
+
+# --- Test Cases for combination() ---
+print("\n--- Testing combination() function ---")
+result_comb_1 = c.combination(5, 2)
+print(f"Test combination 1: C(5, 2)")
+print(f"Expected: 10")
+print(f"Result: {result_comb_1}")
+check_test("combination 1", result_comb_1, 10)
+
+result_comb_2 = c.combination(3, 3)
+print(f"\nTest combination 2: C(3, 3)")
+print(f"Expected: 1")
+print(f"Result: {result_comb_2}")
+check_test("combination 2", result_comb_2, 1)
+
+result_comb_3 = c.combination(5, 7)
+print(f"\nTest combination 3: C(5, 7) (k > n)")
+print(f"Expected: 0") # Your function returns 0 for k > n
+print(f"Result: {result_comb_3}")
+check_test("combination 3", result_comb_3, 0)
+
+# --- Test Cases for string_reverse() ---
+print("\n--- Testing string_reverse() function ---")
+result_str_rev_1 = c.string_reverse("hello")
+print(f"Test string_reverse 1: 'hello'")
+print(f"Expected: 'olleh'")
+print(f"Result: {result_str_rev_1}")
+check_test("string_reverse 1", result_str_rev_1, "olleh")
+
+result_str_rev_2 = c.string_reverse("")
+print(f"\nTest string_reverse 2: '' (empty string)")
+print(f"Expected: None")
+print(f"Result: {result_str_rev_2}")
+check_test("string_reverse 2", result_str_rev_2, None, function_prints_error=True)
+
+# --- Test Cases for matrix_addition() ---
+print("\n--- Testing matrix_addition() function ---")
+mat_add_1 = [[1, 2], [3, 4]]
+mat_add_2 = [[5, 6], [7, 8]]
+expected_add_mat = "6 8 \n10 12 \n"
+result_mat_add_1 = c.matrix_addition(mat_add_1, mat_add_2)
+print(f"Test matrix_addition 1: Adding {mat_add_1} and {mat_add_2}")
+print(f"Expected:\n{expected_add_mat}")
+print(f"Result:\n{result_mat_add_1}")
+check_test("matrix_addition 1", result_mat_add_1, expected_add_mat)
+
+mat_add_incompatible_1 = [[1, 2]]
+mat_add_incompatible_2 = [[1, 2, 3]]
+result_mat_add_2 = c.matrix_addition(mat_add_incompatible_1, mat_add_incompatible_2)
+print(f"\nTest matrix_addition 2: Incompatible dimensions {mat_add_incompatible_1} and {mat_add_incompatible_2}")
+print(f"Expected: None")
+print(f"Result: {result_mat_add_2}")
+check_test("matrix_addition 2", result_mat_add_2, None, function_prints_error=True)
+
+# --- Test Cases for matrix_multiplication() ---
+print("\n--- Testing matrix_multiplication() function ---")
+mat_mult_1 = [[1, 2], [3, 4]]
+mat_mult_2 = [[5, 6], [7, 8]]
+expected_mult_mat = "19 22 \n43 50 \n"
+result_mat_mult_1 = c.matrix_multiplication(mat_mult_1, mat_mult_2)
+print(f"Test matrix_multiplication 1: Multiplying {mat_mult_1} and {mat_mult_2}")
+print(f"Expected:\n{expected_mult_mat}")
+print(f"Result:\n{result_mat_mult_1}")
+check_test("matrix_multiplication 1", result_mat_mult_1, expected_mult_mat)
+
+mat_mult_incompatible_1 = [[1, 2]]
+mat_mult_incompatible_2 = [[1], [2], [3]]
+result_mat_mult_2 = c.matrix_multiplication(mat_mult_incompatible_1, mat_mult_incompatible_2)
+print(f"\nTest matrix_multiplication 2: Incompatible dimensions {mat_mult_incompatible_1} and {mat_mult_incompatible_2}")
+print(f"Expected: None")
+print(f"Result: {result_mat_mult_2}")
+check_test("matrix_multiplication 2", result_mat_mult_2, None, function_prints_error=True)
+
+# --- Test Cases for matrix_transpose() ---
+print("\n--- Testing matrix_transpose() function ---")
+mat_trans_1 = [[1, 2, 3], [4, 5, 6]]
+expected_trans_mat = "1 4 \n2 5 \n3 6 \n"
+result_mat_trans_1 = c.matrix_transpose(mat_trans_1)
+print(f"Test matrix_transpose 1: Transposing {mat_trans_1}")
+print(f"Expected:\n{expected_trans_mat}")
+print(f"Result:\n{result_mat_trans_1}")
+check_test("matrix_transpose 1", result_mat_trans_1, expected_trans_mat)
+
+mat_trans_2 = [[10]]
+expected_trans_mat_2 = "10 \n"
+result_mat_trans_2 = c.matrix_transpose(mat_trans_2)
+print(f"\nTest matrix_transpose 2: Transposing {mat_trans_2}")
+print(f"Expected:\n{expected_trans_mat_2}")
+print(f"Result:\n{result_mat_trans_2}")
+check_test("matrix_transpose 2", result_mat_trans_2, expected_trans_mat_2)
+
+
+# --- Test Cases for determinant_value() ---
+print("\n--- Testing determinant_value() function ---")
+det_1 = [[5]]
+result_det_1 = c.determinant_value(det_1)
+print(f"Test determinant_value 1: 1x1 matrix {det_1}")
+print(f"Expected: 5")
+print(f"Result: {result_det_1}")
+check_test("determinant_value 1", result_det_1, 5)
+
+det_2 = [[1, 2], [3, 4]]
+result_det_2 = c.determinant_value(det_2)
+print(f"\nTest determinant_value 2: 2x2 matrix {det_2}")
+print(f"Expected: -2") # (1*4 - 2*3) = 4 - 6 = -2
+print(f"Result: {result_det_2}")
+check_test("determinant_value 2", result_det_2, -2)
+
+det_3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+result_det_3 = c.determinant_value(det_3)
+print(f"\nTest determinant_value 3: 3x3 matrix {det_3}")
+print(f"Expected: 0")
+print(f"Result: {result_det_3}")
+check_test("determinant_value 3", result_det_3, 0)
+
+det_non_square = [[1, 2], [3, 4], [5, 6]]
+result_det_4 = c.determinant_value(det_non_square)
+print(f"\nTest determinant_value 4: Non-square matrix {det_non_square}")
+print(f"Expected: None")
+print(f"Result: {result_det_4}")
+check_test("determinant_value 4", result_det_4, None, function_prints_error=True)
+
+# --- Test Cases for mean() ---
+print("\n--- Testing mean() function ---")
+test_mean_1 = [1, 2, 3, 4, 5]
+result_mean_1 = c.mean(test_mean_1)
+print(f"Test mean 1: {test_mean_1}")
+print(f"Expected: 3.0")
+print(f"Result: {result_mean_1}")
+check_test("mean 1", result_mean_1, 3.0)
+
+test_mean_2 = [10, 20, 30]
+result_mean_2 = c.mean(test_mean_2)
+print(f"\nTest mean 2: {test_mean_2}")
+print(f"Expected: 20.0")
+print(f"Result: {result_mean_2}")
+check_test("mean 2", result_mean_2, 20.0)
+
+test_mean_3 = []
+result_mean_3 = c.mean(test_mean_3)
+print(f"\nTest mean 3: Empty list {test_mean_3}")
+print(f"Expected: None")
+print(f"Result: {result_mean_3}")
+check_test("mean 3", result_mean_3, None, function_prints_error=True)
+
+# --- Test Cases for median() ---
+print("\n--- Testing median() function ---")
+test_median_odd = [5, 2, 8, 1, 9] # Sorted: [1, 2, 5, 8, 9] -> Median: 5
+result_median_odd = c.median(test_median_odd)
+print(f"Test median 1: Odd length list {test_median_odd}")
+print(f"Expected: 5.0")
+print(f"Result: {result_median_odd}")
+check_test("median 1", result_median_odd, 5.0)
+
+test_median_even = [5, 2, 8, 1, 9, 3] # Sorted: [1, 2, 3, 5, 8, 9] -> Median: (3+5)/2 = 4
+result_median_even = c.median(test_median_even)
+print(f"\nTest median 2: Even length list {test_median_even}")
+print(f"Expected: 4.0")
+print(f"Result: {result_median_even}")
+check_test("median 2", result_median_even, 4.0)
+
+test_median_empty = []
+result_median_empty = c.median(test_median_empty)
+print(f"\nTest median 3: Empty list {test_median_empty}")
+print(f"Expected: None")
+print(f"Result: {result_median_empty}")
+check_test("median 3", result_median_empty, None, function_prints_error=True)
+
+# --- Test Cases for mode() ---
+# Re-using the test cases that were previously confirmed to work with your mode implementation
+print("\n--- Testing mode() function ---")
+
+# Test Case 1: Standard case with a clear mode
+test_list_mode_1 = [1, 2, 3, 2, 1, 5, 1, 1, 2, 6, 5, 54, 52, 5]
+print(f"\nTest mode 1: Standard list: {test_list_mode_1}")
+result_mode_1 = c.mode(test_list_mode_1)
+print(f"Expected: ([1], 4)")
+print(f"Result: {result_mode_1}")
+check_test("mode 1", result_mode_1, ([1], 4))
+
+# Test Case 2: List with multiple modes
+test_list_mode_2 = [10, 20, 30, 20, 10, 40, 50]
+print(f"\nTest mode 2: List with multiple modes: {test_list_mode_2}")
+result_mode_2 = c.mode(test_list_mode_2)
+print(f"Expected: ([10, 20], 2)")
+print(f"Result: {result_mode_2}")
+check_test("mode 2", result_mode_2, ([10, 20], 2))
+
+# Test Case 3: List with no repeating elements
+test_list_mode_3 = [1, 2, 3, 4, 5]
+print(f"\nTest mode 3: List with no repeating elements: {test_list_mode_3}")
+result_mode_3 = c.mode(test_list_mode_3)
+print(f"Expected: ([1, 2, 3, 4, 5], 1)")
+print(f"Result: {result_mode_3}")
+check_test("mode 3", result_mode_3, ([1, 2, 3, 4, 5], 1))
+
+# Test Case 4: List with all same elements
+test_list_mode_4 = [7, 7, 7, 7, 7]
+print(f"\nTest mode 4: List with all same elements: {test_list_mode_4}")
+result_mode_4 = c.mode(test_list_mode_4)
+print(f"Expected: ([7], 5)")
+print(f"Result: {result_mode_4}")
+check_test("mode 4", result_mode_4, ([7], 5))
+
+# Test Case 5: Empty list
+test_list_mode_5 = []
+print(f"\nTest mode 5: Empty list: {test_list_mode_5}")
+result_mode_5 = c.mode(test_list_mode_5)
+print(f"Expected: None")
+print(f"Result: {result_mode_5}")
+check_test("mode 5", result_mode_5, None, function_prints_error=True)
+
+# Test Case 6: List with negative numbers and zeros
+test_list_mode_6 = [-1, 0, -5, 0, -1, 10]
+print(f"\nTest mode 6: List with negative numbers and zeros: {test_list_mode_6}")
+result_mode_6 = c.mode(test_list_mode_6)
+print(f"Expected: ([-1, 0], 2)")
+print(f"Result: {result_mode_6}")
+check_test("mode 6", result_mode_6, ([-1, 0], 2))
+
+# Test Case 7: List with strings (checking versatility for different data types)
+test_list_mode_7 = ["apple", "banana", "apple", "orange", "banana", "apple"]
+print(f"\nTest mode 7: List with strings: {test_list_mode_7}")
+result_mode_7 = c.mode(test_list_mode_7)
+print(f"Expected: (['apple'], 3)")
+print(f"Result: {result_mode_7}")
+check_test("mode 7", result_mode_7, (['apple'], 3))
+
+# Test Case 8: Invalid input (integer) for mode
+test_invalid_input_mode = 123
+print(f"\nTest mode 8: Invalid input (integer): {test_invalid_input_mode}")
+result_invalid_mode = c.mode(test_invalid_input_mode)
+print(f"Expected: None")
+print(f"Result: {result_invalid_mode}")
+check_test("mode 8", result_invalid_mode, None, function_prints_error=True)
+
+
+print("\n--- All tests completed. Review the 'Test Status' lines for results. ---")+
\ No newline at end of file
diff --git a/test2.py b/test2.py
@@ -0,0 +1,190 @@
+import adcustom as c
+
+def get_integer_input(prompt):
+ while True:
+ try:
+ return int(input(prompt))
+ except ValueError:
+ print("Invalid input. Please enter an integer.")
+
+def get_float_input(prompt):
+ while True:
+ try:
+ return float(input(prompt))
+ except ValueError:
+ print("Invalid input. Please enter a number (integer or float).")
+
+def get_list_of_numbers_input(prompt):
+ while True:
+ s = input(prompt)
+ if not s.strip(): # Handle empty input for empty list
+ return []
+ try:
+ # Attempt to convert each part to a float, allowing for integers as well
+ return [float(x.strip()) for x in s.split(',')]
+ except ValueError:
+ print("Invalid input. Please enter comma-separated numbers (e.g., 1, 2.5, 3).")
+
+def get_general_list_input(prompt):
+ while True:
+ s = input(prompt)
+ if not s.strip(): # Handle empty input for empty list
+ return []
+ # For general lists, we'll split by comma and strip spaces.
+ # The function itself handles type conversion/validation.
+ return [x.strip() for x in s.split(',')]
+
+def get_matrix_input(prompt):
+ matrix = []
+ print(prompt + " (Enter rows separated by ';', elements by ',' e.g., '1,2;3,4')")
+ while True:
+ s = input("Enter matrix row(s) (or type 'done' to finish): ").strip()
+ if s.lower() == 'done':
+ break
+ if not s:
+ print("Row cannot be empty. Please enter elements or 'done'.")
+ continue
+ try:
+ rows_str = s.split(';')
+ current_matrix = []
+ for row_str in rows_str:
+ row_elements = [float(x.strip()) for x in row_str.split(',')]
+ current_matrix.append(row_elements)
+
+ # Basic validation for consistency of rows for the first row entered
+ if not matrix and current_matrix: # If this is the first matrix input
+ for r in current_matrix:
+ matrix.append(r)
+ elif matrix and current_matrix: # If subsequent rows, check consistency
+ if len(current_matrix[0]) != len(matrix[0]):
+ print("Error: All rows must have the same number of columns.")
+ matrix = [] # Clear and restart input for this matrix
+ raise ValueError("Inconsistent column count")
+ for r in current_matrix:
+ matrix.append(r)
+ else: # If s was empty or only whitespace, and not 'done'
+ print("Invalid row input. Please enter comma-separated numbers.")
+ continue
+ return matrix
+ except ValueError as e:
+ if "Inconsistent column count" in str(e): # Handled above, restart loop
+ continue
+ print("Invalid matrix input. Ensure elements are numbers and rows are comma-separated.")
+ print("Example: '1,2;3,4' for [[1,2],[3,4]]")
+ matrix = [] # Clear and retry input if invalid format
+ continue
+
+ if not matrix:
+ print("No valid matrix entered.")
+ return None # Return None if no matrix was successfully entered or user exits without input
+ return matrix
+
+
+def run_interactive_test():
+ print("--- Interactive Test for custom.py module ---")
+ while True:
+ print("\nSelect a function to test:")
+ print("1. add(num1, num2)")
+ print("2. check_prime(num)")
+ print("3. factorial(num)")
+ print("4. permutation(total, chosen)")
+ print("5. combination(total, chosen)")
+ print("6. string_reverse(text)")
+ print("7. matrix_addition(mat1, mat2)")
+ print("8. matrix_multiplication(mat1, mat2)")
+ print("9. matrix_transpose(mat)")
+ print("10. determinant_value(mat)")
+ print("11. mean(data_list)")
+ print("12. median(data_list)")
+ print("13. mode(data_list)")
+ print("0. Exit")
+
+ choice = input("Enter your choice (0-13): ")
+
+ if choice == '0':
+ print("Exiting interactive test. Goodbye!")
+ break
+ elif choice == '1':
+ num1 = get_float_input("Enter first number: ")
+ num2 = get_float_input("Enter second number: ")
+ result = c.add(num1, num2)
+ print(f"Result of add({num1}, {num2}): {result}")
+ elif choice == '2':
+ num = get_integer_input("Enter an integer to check if prime: ")
+ result = c.check_prime(num)
+ print(f"Result of check_prime({num}): {result} (1=Prime, 0=Not Prime, None=Error)")
+ elif choice == '3':
+ num = get_integer_input("Enter a non-negative integer for factorial: ")
+ result = c.factorial(num)
+ print(f"Result of factorial({num}): {result}")
+ elif choice == '4':
+ n = get_integer_input("Enter total items (n): ")
+ k = get_integer_input("Enter chosen items (k): ")
+ result = c.permutation(n, k)
+ print(f"Result of permutation({n}, {k}): {result}")
+ elif choice == '5':
+ n = get_integer_input("Enter total items (n): ")
+ k = get_integer_input("Enter chosen items (k): ")
+ result = c.combination(n, k)
+ print(f"Result of combination({n}, {k}): {result}")
+ elif choice == '6':
+ text = input("Enter a string to reverse: ")
+ result = c.string_reverse(text)
+ print(f"Result of string_reverse('{text}'): {result}")
+ elif choice == '7':
+ print("\n--- Input for Matrix 1 ---")
+ mat1 = get_matrix_input("Matrix 1")
+ print("\n--- Input for Matrix 2 ---")
+ mat2 = get_matrix_input("Matrix 2")
+ if mat1 is not None and mat2 is not None:
+ print("\nCalculating Matrix Addition...")
+ result = c.matrix_addition(mat1, mat2)
+ print(f"Result of matrix_addition:\n{result}")
+ else:
+ print("Matrix input was invalid or incomplete. Cannot perform addition.")
+ elif choice == '8':
+ print("\n--- Input for Matrix 1 ---")
+ mat1 = get_matrix_input("Matrix 1")
+ print("\n--- Input for Matrix 2 ---")
+ mat2 = get_matrix_input("Matrix 2")
+ if mat1 is not None and mat2 is not None:
+ print("\nCalculating Matrix Multiplication...")
+ result = c.matrix_multiplication(mat1, mat2)
+ print(f"Result of matrix_multiplication:\n{result}")
+ else:
+ print("Matrix input was invalid or incomplete. Cannot perform multiplication.")
+ elif choice == '9':
+ mat = get_matrix_input("\n--- Input for Matrix to Transpose ---")
+ if mat is not None:
+ print("\nCalculating Matrix Transpose...")
+ result = c.matrix_transpose(mat)
+ print(f"Result of matrix_transpose:\n{result}")
+ else:
+ print("Matrix input was invalid or incomplete. Cannot perform transpose.")
+ elif choice == '10':
+ mat = get_matrix_input("\n--- Input for Matrix to get Determinant Value ---")
+ if mat is not None:
+ print("\nCalculating Determinant Value...")
+ result = c.determinant_value(mat)
+ print(f"Result of determinant_value: {result}")
+ else:
+ print("Matrix input was invalid or incomplete. Cannot calculate determinant.")
+ elif choice == '11':
+ data_list = get_list_of_numbers_input("Enter comma-separated numbers for mean (e.g., 1,2,3.5): ")
+ result = c.mean(data_list)
+ print(f"Result of mean({data_list}): {result}")
+ elif choice == '12':
+ data_list = get_list_of_numbers_input("Enter comma-separated numbers for median (e.g., 1,2,3.5): ")
+ result = c.median(data_list)
+ print(f"Result of median({data_list}): {result}")
+ elif choice == '13':
+ # Mode can take mixed types
+ data_list = get_general_list_input("Enter comma-separated values for mode (e.g., apple,banana,apple,1,2,1): ")
+ result = c.mode(data_list)
+ print(f"Result of mode({data_list}): {result}")
+ else:
+ print("Invalid choice. Please enter a number between 0 and 13.")
+
+# Run the interactive test
+if __name__ == "__main__":
+ run_interactive_test()+
\ No newline at end of file
diff --git a/test3.py b/test3.py
@@ -0,0 +1,105 @@
+# test_triangle_calculator.py
+import unittest
+import math
+from triangle import areaoftriangle
+
+class TestAreaOfTriangle(unittest.TestCase):
+
+ def setUp(self):
+ pass
+
+ # --- Test Cases for Valid Triangles ---
+
+ def test_right_triangle_3_4_5(self):
+ self.assertAlmostEqual(areaoftriangle(3, 4, 5), 6.0, places=9)
+ self.assertAlmostEqual(areaoftriangle(4, 3, 5), 6.0, places=9)
+ self.assertAlmostEqual(areaoftriangle(5, 3, 4), 6.0, places=9)
+
+ def test_equilateral_triangle(self):
+ self.assertAlmostEqual(areaoftriangle(2, 2, 2), math.sqrt(3), places=9)
+ self.assertAlmostEqual(areaoftriangle(10, 10, 10), (math.sqrt(3)/4) * 100, places=9)
+
+ def test_scalene_triangle(self):
+ self.assertAlmostEqual(areaoftriangle(7, 8, 9), math.sqrt(720), places=9) # approx 26.83281573
+ self.assertAlmostEqual(areaoftriangle(6, 8, 10), 24.0, places=9)
+
+ def test_float_inputs(self):
+ self.assertAlmostEqual(areaoftriangle(3.0, 4.0, 5.0), 6.0, places=9)
+ self.assertAlmostEqual(areaoftriangle(7.5, 10.0, 12.5), 37.5, places=9)
+
+ # --- Test Cases for Degenerate Triangles (Area should be 0) ---
+
+ def test_degenerate_triangle_straight_line(self):
+ self.assertAlmostEqual(areaoftriangle(1, 2, 3), 0.0, places=9)
+ self.assertAlmostEqual(areaoftriangle(2.5, 2.5, 5.0), 0.0, places=9)
+ self.assertAlmostEqual(areaoftriangle(10, 20, 30), 0.0, places=9)
+ self.assertAlmostEqual(areaoftriangle(1, 1, 2), 0.0, places=9)
+
+
+ # --- Test Cases for Invalid Inputs (should return None) ---
+
+ def test_invalid_triangle_inequality(self):
+ self.assertIsNone(areaoftriangle(1, 2, 5))
+ self.assertIsNone(areaoftriangle(10, 1, 2))
+ self.assertIsNone(areaoftriangle(1, 10, 2))
+
+ def test_zero_side_length(self):
+ self.assertIsNone(areaoftriangle(0, 4, 5))
+ self.assertIsNone(areaoftriangle(3, 0, 5))
+ self.assertIsNone(areaoftriangle(3, 4, 0))
+ self.assertIsNone(areaoftriangle(0, 0, 0))
+
+ def test_negative_side_length(self):
+ self.assertIsNone(areaoftriangle(-3, 4, 5))
+ self.assertIsNone(areaoftriangle(3, -4, 5))
+ self.assertIsNone(areaoftriangle(3, 4, -5))
+
+ def test_non_numeric_inputs(self):
+ self.assertIsNone(areaoftriangle("a", 4, 5))
+ self.assertIsNone(areaoftriangle(3, "b", 5))
+ self.assertIsNone(areaoftriangle(3, 4, "c"))
+ self.assertIsNone(areaoftriangle(None, 4, 5))
+ self.assertIsNone(areaoftriangle([1,2], 4, 5))
+
+ # --- Test Cases for Unit Parameter ---
+
+ def test_unit_parameter(self):
+ self.assertEqual(areaoftriangle(3, 4, 5, 'sq units'), "6.0 sq units")
+ self.assertEqual(areaoftriangle(7, 8, 9, 'm^2'), f"{math.sqrt(720)} m^2")
+ self.assertEqual(areaoftriangle(10, 10, 10, 'cm²'), f"{ (math.sqrt(3)/4) * 100 } cm²")
+
+ # Corrected syntax here:
+ def test_no_unit_parameter(self):
+ self.assertIsInstance(areaoftriangle(3, 4, 5), float)
+ self.assertAlmostEqual(areaoftriangle(3, 4, 5), 6.0, places=9)
+
+ def test_empty_unit_parameter(self):
+ self.assertIsInstance(areaoftriangle(3, 4, 5, ''), float)
+ self.assertAlmostEqual(areaoftriangle(3, 4, 5, ''), 6.0, places=9)
+
+ # --- Refined Test for precision around degenerate cases ---
+ # This test focuses on cases where the mathematical area is exactly 0,
+ # but floating point arithmetic *might* produce a slightly negative `pre_result`.
+ # Your function's `pre_result > -0.09` tolerance should handle these.
+ def test_degenerate_triangle_zero_area_precision(self):
+ # A perfectly degenerate triangle where s-c is exactly 0.
+ # This is the primary case where floating point might yield pre_result < 0 but near 0.
+ self.assertAlmostEqual(areaoftriangle(1.0, 1.0, 2.0), 0.0, places=9)
+ self.assertAlmostEqual(areaoftriangle(3.0, 4.0, 7.0), 0.0, places=9)
+ # Add cases that might cause tiny negative pre_result for true degeneracy
+ # (These are hard to force consistently without knowing specific float quirks)
+ # For perfectly degenerate: a=1,b=1,c=2 => s=2, s-c=0, pre_result=0.
+ # If the internal calculation for (s-a)*(s-b)*(s-c) is slightly negative,
+ # your function's tolerance should catch it and return 0.0.
+
+ # This test verifies that genuinely invalid triangles (violating inequality) still return None.
+ # This was previously part of 'test_nearly_degenerate_triangle' that caused TypeError.
+ def test_invalid_triangle_exceeding_tolerance(self):
+ # These are clearly invalid and should return None
+ self.assertIsNone(areaoftriangle(1.0, 2.0, 3.0000000001)) # 1+2 < 3.0000000001
+ self.assertIsNone(areaoftriangle(1.0, 1.0, 2.0000000001)) # 1+1 < 2.0000000001
+ self.assertIsNone(areaoftriangle(10, 10, 25)) # Sum of two sides is less than third (pre_result would be very negative)
+
+
+if __name__ == '__main__':
+ unittest.main(argv=['first-arg-is-ignored'], exit=False)+
\ No newline at end of file
diff --git a/test4.py b/test4.py
@@ -0,0 +1,24 @@
+from adpkg.triangle import areaoftriangle
+
+if __name__ == '__main__':
+ print("--- Triangle Area Calculator ---")
+
+ while True:
+ try:
+ side_a = input("Enter the length of side a: ")
+ side_b = input("Enter the length of side b: ")
+ side_c = input("Enter the length of side c: ")
+
+ area = areaoftriangle(side_a, side_b, side_c)
+
+ if area is not None:
+ print(f"The calculated area of the triangle is: {area}")
+
+ except Exception as e:
+ print(f"An error occurred during input: {e}")
+
+ check_again = input("\nDo you want to calculate another area? (yes/no): ").lower()
+ if check_again != 'yes':
+ break
+
+ print("Exiting calculator. Goodbye!")+
\ No newline at end of file
diff --git a/test5.py b/test5.py
@@ -0,0 +1,28 @@
+from adpkg.finance import interest
+
+if __name__ == '__main__':
+ print("--- Compound Interest Calculator ---")
+
+ while True:
+ try:
+ print("\nPlease provide the following details:")
+ prime_amount = input("Principal Amount (P): ")
+ rate_of_interest = input("Annual Interest Rate (%): ")
+ compounding_frequency = input("Times per year interest is compounded (n): ")
+ time_duration_str = input("Time Duration (e.g., '5y6m', '18m', '3y'): ")
+
+ calculated_interest = interest(prime_amount, time_duration_str, compounding_frequency, rate_of_interest)
+
+ if calculated_interest is not None:
+ print(f"\nCompound Interest earned is: {calculated_interest}")
+ else:
+ print("\nCalculation failed due to invalid input.")
+
+ except Exception as e:
+ print(f"\nAn unexpected error occurred: {e}")
+
+ check_again = input("\nDo you want to calculate another interest amount? (yes/no): ").lower()
+ if check_again != 'yes':
+ break
+
+ print("Exiting calculator. Goodbye!")+
\ No newline at end of file
diff --git a/triangle.py b/triangle.py
@@ -0,0 +1,74 @@
+# this module had the function to calculate the area of triangle
+# √[s(s-a)(s-b)(s-c)]
+
+def areaoftriangle(len_a, len_b, len_c, unit = '') :
+ """
+ Calculates the area of triangle using general formula. √[s(s-a)(s-b)(s-c)]
+
+ Args:
+ len_a = A positive number as length of a side of a triangle (Not Zero)
+ len_b = A positive number as length of a side of a triangle (Not Zero)
+ len_c = A positive number as length of a side of a triangle (Not Zero)
+ unit = Unit of the area of the triangle (e.g., "sq cm", "m^2").
+
+ Returns:
+ Area of the triangle
+ None if the input is not valid or any error occurs.
+ """
+ # first checking if the input values are even valid or not.
+ try :
+ a = float(len_a)
+ b = float(len_b)
+ c = float(len_c)
+ except ValueError :
+ print('Please enter a valid number (Integer or Float).')
+ return None
+ except Exception as error :
+ print(f'An unexpected error happened : {error}')
+ return None
+
+ # checking if inputs are above 0, because a side length can't be zero
+ if a <= 0 or b <= 0 or c <= 0 :
+ print('Side length of a triangle can\'t be Zero or negative.')
+ return None
+
+ # checking if the triangle even follows the triangle rule : len_a + len_b > len_c
+ if not (a + b >= c and a + c >= b and b + c >= a) :
+ print('The triangle must satisfy the triangle inequality theorem (the sum of the lengths of any two sides must be greater than or same as the length of the third side).')
+ return None
+
+ # main logic
+ try :
+ # calculating the value of 's' (The semi-perimeter (half the perimeter) of the triangle)
+ s = (a + b + c) / 2
+
+ # now the formula without root
+ pre_result = (s * (s - a) * (s - b) * (s - c))
+
+ if pre_result < 0:
+ # Due to floating point inaccuracies, it might be slightly negative
+ if pre_result > -0.09 : # A small tolerance
+ result = 0.0
+ else:
+ print("Error: Calculation resulted in a negative number under the square root, indicating invalid triangle sides (likely due to precision issues)."
+ f"\nCalculated value before root was : {pre_result}")
+ return None
+
+ else :
+ # now the root
+ result = pre_result ** 0.5
+
+ except Exception as error :
+ print(f'An unexpected error happened : {error}')
+ return None
+
+ # returning the result with the unit if provided
+ try :
+ if len(unit) > 0 :
+ return f'{result:.3f} {unit}'
+ else :
+ result = round(result, 3)
+ return float(result)
+ except Exception as error :
+ print(f'An unexpected error happened : {error}')
+ return None+
\ No newline at end of file