adpkg

A package containing Python mo...
Log | Files | Refs | README | LICENSE

adcustom.py (22692B)


      1 # Prime check function
      2 
      3 def check_prime(inp) : 
      4     """
      5     Checks the input integers is a Prime number or not.
      6 
      7     Args: 
      8         inp = The non-negetive integer to check 
      9 
     10     Returns:
     11         1 if input integer is Prime, 0 if input integer is not Prime.
     12         None if the input is not valid or any error occurs.
     13     """
     14     #trying to check if the input is valid integer or not
     15     try : 
     16         temp = int(inp)
     17     except ValueError : 
     18         print('Error : Plese enter a valid integer.')
     19         return None
     20     except Exception as error : 
     21         print(f'Error : An unexpected error happened : {error}')
     22         return None
     23     # handling negetive integers
     24     if temp < 0 : 
     25         print('Error : Please enter a non-negetive integer.')
     26         return None
     27     #handling integers <= 3
     28     if temp < 2 :
     29         return 0    # '0' means not prime.
     30     if temp <= 3 : 
     31         return 1    # '1' means prime.
     32     if temp % 2 == 0 :
     33         return 0    # there is no even number that is prime except '2', this was checked before.
     34     #main logic to check prime or not
     35     try : 
     36         for i in range (3, (temp // 2) + 1) :
     37             if temp % i == 0 :
     38                 return 0
     39         return 1
     40     except Exception as error : 
     41         print(f'Error : An unexpected error happened : {error}') 
     42         return None
     43     
     44 # factorial function
     45 
     46 def factorial(inp) :
     47     """
     48     Calculates the factorial of given integer
     49 
     50     Args:
     51         inp = an non-negetive integer
     52     
     53     Returns:
     54         the factorial of the non-negetive integer.
     55         None if the input is not valid or any error occurs.
     56     """
     57     # trying to check if input is a valid integer or not
     58     try : 
     59         temp = int(inp)
     60     except ValueError : 
     61         print('Error : Plese enter a valid integer.')
     62         return None
     63     except Exception as error : 
     64         print(f'Error : An unexpected error happened : {error}')
     65         return None
     66     # handling negetive integer 
     67     if temp < 0 :
     68         print('Error : Please enter a non-negetive integer.')
     69         return None
     70     # handling inp '0'
     71     if temp == 0 :
     72         return 1
     73     # main logic for factorial 
     74     try : 
     75         result = 1
     76         for i in range(2, temp + 1) :
     77             result = result * i
     78         return result
     79     except Exception as error :
     80         print(f'Error : An unexpected error happened : {error}')
     81         return None
     82     
     83 # permutation function
     84 
     85 def permutation(total_item,chosen_item) : 
     86     """
     87     Calculates the number of permutations p(n, k).
     88 
     89     Args:
     90         total_item = the total number of distinct items in the set
     91         chosen_item = the number of items to be arranged or chosen from the set at a time
     92     
     93     Returns:
     94         The number of permutations.
     95         None if the input is not valid or any error occurs.
     96     """
     97     # trying to check if the inputs are a valid integer or not.
     98     try : 
     99         n = int(total_item)
    100         k = int(chosen_item)
    101     except ValueError : 
    102         print('Error : Please enter a valid integer.')
    103         return None
    104     except Exception as error : 
    105         print(f'Error : An unexpected error happened : {error}')
    106         return None
    107     # handling negetive integer
    108     if n < 0 or k < 0 :
    109         print('Error : Please enter non-negetive integer.')
    110         return None
    111     if k > n : 
    112         print('Error : Chosen item should be lower than Total item.')
    113         return None
    114     # main logic for permutation
    115     try : 
    116         fact_n = factorial(n)
    117         fact_n_k = factorial(n-k)
    118         result = fact_n / fact_n_k
    119         return int(result)
    120     except Exception as error : 
    121         print(f'Error : An unexpected error happened : {error}')
    122         return None
    123     
    124 # combination function
    125 
    126 def combination(total_item, chosen_item) : 
    127     """
    128     Calculates the number of combination c(n, k).
    129 
    130     Args:
    131         total_item = the total number of distinct items in the set
    132         chosen_item = the number of items to be arranged or chosen from the set at a time
    133     
    134     Returns:
    135         The number of combinations.
    136         None if the input is not valid or any error occurs.
    137     """
    138     # trying to check if the inputs are a valid integer or not.
    139     try : 
    140         n = int(total_item)
    141         k = int(chosen_item)
    142     except ValueError : 
    143         print('Error : Please enter a valid integer.')
    144         return None
    145     except Exception as error : 
    146         print(f'Error : An unexpected error happened : {error}')
    147         return None
    148     # handling negetive integer
    149     if n < 0 or k < 0 :
    150         print('Error : Please enter non-negetive integer.')
    151         return None
    152     if k > n : 
    153         return 0   # if total item is lower than chosen then their is no possible combinaition. 
    154     # main logic for combination
    155     try : 
    156         fact_n = factorial(n)
    157         fact_k = factorial(k)
    158         fact_n_k = factorial(n-k)
    159         result = fact_n / (fact_n_k * fact_k)
    160         return int(result)
    161     except Exception as error : 
    162         print(f'Error : An unexpected error happened : {error}')
    163         return None
    164 
    165 # reverse string function
    166 
    167 def string_reverse(string) : 
    168     """
    169     Reverse the given string
    170 
    171     Args:
    172         string = The given string
    173     
    174     Returns:
    175         Reverse string of the given string
    176         None if the input is not valid or any error occurs.
    177     """
    178     # trying to check if the input is a string
    179     try : 
    180         temp = str(string)
    181     except Exception as error : 
    182         print(f'Error : An unexpected error happened : {error}')
    183         return None
    184     # handing empty string
    185     if temp == '' :
    186         print('Error : Input should not be a empty string.')
    187         return None
    188     # main logic
    189     try : 
    190         result = ''
    191         for char in temp : 
    192             result = char + result
    193         return result
    194     except Exception as error : 
    195         print(f'Error : An unexpected error happened : {error}')
    196         return None
    197 
    198 # matrix checking function
    199 
    200 def is_matrix_valid(matrix) :
    201     """
    202     Helper to validate if an input is a list of lists representing a matrix.
    203 
    204     Args:
    205         matrix = A matrix that will be checked.
    206     
    207     Returns:
    208         True if the matrix is valid. False if not.
    209     """
    210     try : 
    211         #checking if the list is empty or not / trying to check is the input matrix is empty or not
    212         row_count = 0
    213         for row in matrix : 
    214             row_count += 1
    215         
    216         if row_count == 0 :
    217             print('Error: Matrix must be a non-empty list of lists.')
    218             return False
    219         
    220         #trying to check if the list is 'list of lists', trying to check if the matrix have both row and column
    221         first_row = matrix[0]
    222         col_count_first_row = 0
    223         for val in first_row :
    224             col_count_first_row += 1
    225 
    226         if col_count_first_row == 0 :
    227             print('Error : Matrix should have non-empty lists as rows.')
    228             return False
    229         
    230         # checking if All rows in the matrix have the same number of columns
    231         for row_index in range(row_count) :
    232             current_row = matrix[row_index]
    233             
    234             current_col_count = 0
    235             for col in current_row : 
    236                 current_col_count += 1
    237 
    238             if current_col_count != col_count_first_row : 
    239                 print('All rows in the matrix must have the same number of columns')
    240                 return False
    241             
    242             #checking if columns have a number by attempting a conversion
    243             for col_index in range(current_col_count) : 
    244                 element = current_row[col_index]
    245 
    246                 try : 
    247                     checker = float(element)
    248                 except (ValueError, TypeError) :
    249                     print('Error : Matrix elements should be a number(Integer or Float number).')
    250                 except Exception as error :
    251                     print(f'Error : An uncxpected error happened : {error}')
    252                     return False
    253         
    254         return True     # if all check passed 
    255     
    256     except Exception as error : 
    257         print(f'Error : An uncxpected error happened : {error}')
    258         return False
    259 
    260 # matrix multiplication function
    261 
    262 def matrix_addition(matrix1, matrix2) :
    263     """
    264     Add two input matrix
    265 
    266     Args:
    267         matrix1 = first matrix
    268         matrix2 = second matrix
    269     
    270     Returns:
    271         Matrix after adding two input matrix.
    272         None if the input is not valid or any error occurs.
    273     """
    274     # checking if the matrix are valid or not
    275     if not is_matrix_valid(matrix1) : 
    276         print('Error : First matrix is not valid.')
    277         return None
    278     if not is_matrix_valid(matrix2) : 
    279         print('Error : Second matrix is not valid.')
    280         return None
    281 
    282     # checking matrix dimension are same or not.
    283     row_count_mat1 = len(matrix1)
    284     col_count_mat1 = len(matrix1[0])
    285 
    286     row_count_mat2 = len(matrix2)
    287     col_count_mat2 = len(matrix2[0])
    288 
    289     if row_count_mat1 != row_count_mat2 or col_count_mat1 != col_count_mat2 :
    290         print('Error : Matrix dimension should be same for both matrix to do addition.')
    291         return None
    292 
    293     try : 
    294         result_matrix = []
    295         for i in range(row_count_mat1) : 
    296             result_matrix_row = []
    297             for j in range(col_count_mat1) : 
    298                 result_matrix_element = matrix1[i][j] + matrix2[i][j]
    299                 result_matrix_row.append(result_matrix_element)
    300             result_matrix.append(result_matrix_row)
    301             
    302         string_result_matrix = ''
    303         for row in result_matrix :
    304             for element in row :
    305                 string_result_matrix = string_result_matrix + str(element) + ' '
    306             string_result_matrix = string_result_matrix + '\n'
    307         return string_result_matrix
    308     except Exception as error : 
    309         print(f'Error : An unexpected error happened : {error}')
    310         return None
    311 
    312 # matrix multiplication function
    313 
    314 def matrix_multiplication(matrix1, matrix2) : 
    315     """
    316     Multiply one input matrix with another input matrix.
    317 
    318     Args:
    319         matrix1 = first matrix
    320         matrix2 = second matrix
    321     
    322     Returns:
    323         Matrix after multiplying
    324         None if the input is not valid or any error occurs.
    325     """
    326     # checking if the matrix are valid or not
    327     if not is_matrix_valid(matrix1) : 
    328         print('Error : First matrix is not valid.')
    329         return None
    330     if not is_matrix_valid(matrix2) : 
    331         print('Error : Second matrix is not valid.')
    332         return None
    333     
    334     # checking matrix dimension as the column_count of the first matrix and the row_count of the second matrix should be same
    335     row_count_mat1 = len(matrix1)
    336     col_count_mat1 = len(matrix1[0])
    337 
    338     row_count_mat2 = len(matrix2)
    339     col_count_mat2 = len(matrix2[0])
    340 
    341     if col_count_mat1 != row_count_mat2 : 
    342         print('Error : Column_count of the first matrix and the Row_count of the second matrix should be same to do multiplication.')
    343         return None
    344     
    345     try : 
    346         result_matrix = []
    347         for i in range(row_count_mat1) :    # taking the row of the matrix1
    348             result_matrix_row = []
    349             for j in range(col_count_mat2) :    # taking the column of the matrix2
    350                 result_matrix_element = 0
    351                 for k in range(col_count_mat1) :    # taking the column of the matrix1.
    352                     """ 
    353                     এখন, 'k' এর লুপ একবার সম্পন্ন হলে, 'i' এর জন্য matrix1 
    354                     এর সারি একই থাকবে, 'j' এর জন্য matrix2 এর কলাম একই থাকবে,
    355                     কিন্তু 'k' এর মান পরিবর্তনের সাহায্যে, matrix1 এর কলাম এবং matrix2
    356                     এর সারি পরিবর্তন করা যেতে পারে। 'j' পরিবর্তন হলে, matrix2 এর 
    357                     কলাম পরিবর্তন হবে। অর্থাৎ, কাজটি এই প্রবাহে হবে: প্রথমে, matrix1 
    358                     এর সারিটি নেবে এবং matrix2 এর কলাম পরিবর্তন করে এটিকে গুণ 
    359                     করবে। সমস্ত কলাম শেষ হয়ে গেলে, তারপর matrix1 এর পরবর্তী সারিতে যাবে।
    360                     """
    361                     result_matrix_element += matrix1[i][k] * matrix2[k][j]
    362                 result_matrix_row.append(result_matrix_element)
    363             result_matrix.append(result_matrix_row)
    364 
    365         string_result_matrix = ''
    366         for row in result_matrix :
    367             for element in row :
    368                 string_result_matrix = string_result_matrix + str(element) + ' '
    369             string_result_matrix = string_result_matrix + '\n'
    370         return string_result_matrix
    371     except Exception as error : 
    372         print(f'An unexpected error happened : {error}')
    373         return None
    374     
    375 # matrix transpose function
    376 
    377 def matrix_transpose(matrix) : 
    378     """
    379     Transpose a matrix(row becomes column, column becomes row)
    380 
    381     Args:
    382         matrix = Input matrix given by user
    383     
    384     Returns:
    385         Matrix after transposing
    386         None if the input is not valid or any error occurs.
    387     """
    388     # checking if the matrix are valid or not
    389     if not is_matrix_valid(matrix) : 
    390         print('Error : Given matrix is not valid.')
    391         return None
    392     
    393     row = len(matrix)
    394     column = len(matrix[0])
    395 
    396     try : 
    397         result_matrix = []
    398         for i in range(column) : 
    399             result_matrix_row = []
    400             for j in range(row) : 
    401                 result_matrix_row.append(matrix[j][i])
    402             result_matrix.append(result_matrix_row)
    403 
    404         string_result_matrix = ''
    405         for row in result_matrix :
    406             for element in row :
    407                 string_result_matrix = string_result_matrix + str(element) + ' '
    408             string_result_matrix = string_result_matrix + '\n'
    409         return string_result_matrix
    410     except Exception as error : 
    411         print(f'An unexpected error happened : {error}')
    412         return None
    413 
    414 # determinant_value function
    415 
    416 def determinant_value(matrix) : 
    417     """
    418     Calculates the determinant value of given matrix
    419 
    420     Args:
    421         matrix = Input matrix given by user
    422     
    423     Returns:
    424         Determinant value of given matrix
    425         None if the input is not valid or any error occurs.
    426     """
    427     # checking if the matrix are valid or not
    428     if not is_matrix_valid(matrix) : 
    429         print('Error : Given matrix is not valid.')
    430         return None
    431     
    432     row = len(matrix)
    433     column = len(matrix[0])
    434 
    435     if row != column :
    436         print('Error : Row count and the Column count should be same.')
    437         return None
    438     
    439     if row > 3 :
    440         print('Error : This function is currently allowing up to 3 x 3 matrix')
    441         return None
    442     
    443     if row == 1 : 
    444         return matrix[0][0]
    445 
    446     if row == 2 : 
    447         try : 
    448             for i in range(row) : 
    449                 for j in range(column) : 
    450                     result = ((matrix[i][j] * matrix[i+1][j+1]) - (matrix[i][j+1] * matrix[i+1][j]))
    451                     return result
    452                 
    453         except Exception as error : 
    454             print(f'Error : An unexpected error happened : {error}')
    455             return None
    456 
    457     if row == 3 :
    458         try : 
    459             first_part = (matrix[0][0] * ((matrix[1][1] * matrix[2][2]) - (matrix[1][2] * matrix[2][1])))
    460             second_part = (matrix[0][1] * ((matrix[1][0] * matrix[2][2]) - (matrix[1][2] * matrix[2][0])))
    461             third_part = (matrix[0][2] * ((matrix[1][0] * matrix[2][1]) - (matrix[1][1] * matrix[2][0])))
    462             result = first_part - second_part + third_part
    463             return result
    464         except Exception as error : 
    465             print(f'Error : An unexpected error happened : {error}')
    466             return None
    467 
    468 # mean-median-node fuction
    469 
    470 def mean(inp_set) : 
    471     """
    472     Gives the mean value of a set
    473 
    474     Args:
    475         set = Input set given by user
    476     
    477     Returns:
    478         Mean value of the input set.
    479         None if the input is not valid or any error occurs.
    480     """
    481     temp = []   # this new list will be used to take out all elements as float number.
    482     try : 
    483         set_len = len(inp_set)
    484 
    485         if set_len == 0 : 
    486             print('Error : Set should not be empty.')
    487             return None
    488     except Exception as error : 
    489             print(f'Error : An unexpected error happened : {error}')
    490             return None
    491     try : 
    492         for element in inp_set : 
    493             checker = float(element)
    494             temp.append(checker)
    495     except ValueError : 
    496         print('Error : Please enter a valid number(Integer or Float).')
    497         return None
    498     except Exception as error :
    499         print(f'Error : An unexpected error happened : {error}')
    500         return None
    501     try : 
    502         element_total = 0.0
    503         for element in temp : 
    504             element_total = element_total + element    # summation of the set element
    505 
    506         result = element_total / float(set_len)
    507         return result
    508     except Exception as error : 
    509         print(f'Error : An unexpected error happened : {error}')
    510         return None
    511     
    512 def median(inp_set) : 
    513     """
    514     Gives the median value of a set
    515 
    516     Args:
    517         set = Input set given by user
    518     
    519     Returns:
    520         Median value of the input set.
    521         None if the input is not valid or any error occurs.
    522     """
    523     temp = []   # this new list will be used to take out all elements as float number.
    524     try : 
    525         set_len = len(inp_set)
    526 
    527         if set_len == 0 : 
    528             print('Error : Set should not be empty.')
    529             return None
    530     except Exception as error : 
    531             print(f'Error : An unexpected error happened : {error}')
    532             return None
    533     try : 
    534         for element in inp_set : 
    535             checker = float(element)
    536             temp.append(checker)
    537     except ValueError : 
    538         print('Error : Please enter a valid number(Integer or Float).')
    539         return None
    540     except Exception as error :
    541         print(f'Error : An unexpected error happened : {error}')
    542         return None
    543     
    544     # trying to order the list if not. 
    545     # here 'bubble sort' is used, maybe i should use sort() function. 
    546     # actually i dont know how to use sort() function
    547     try : 
    548         for counter in range(1, set_len+1) : 
    549             for ele_index in range(set_len - counter) : 
    550                 if temp[ele_index] > temp[ele_index + 1] :
    551                     temp[ele_index], temp[ele_index + 1] = temp[ele_index + 1], temp[ele_index]
    552 
    553     except Exception as error : 
    554         print(f'Error : An unexpected error happened : {error}')
    555         return None
    556     
    557     # if the set have odd element count, like 1, 3, 5, 7, 9 etc
    558     if set_len % 2 == 1 :       
    559         try : 
    560             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
    561             return temp[middle_index - 1]       # python's 0-based indexing
    562         except Exception as error : 
    563             print(f'Error : An unexpected error happened : {error}')
    564             return None
    565     
    566     # if the set have even element count, like 2, 4, 6, 8 etc
    567     if set_len % 2 == 0 :
    568         try : 
    569             first_middle_index = set_len // 2
    570             second_middle_index = first_middle_index + 1
    571 
    572             middle_avg = (temp[first_middle_index - 1] + temp[second_middle_index - 1]) / 2  # python's 0-based indexing
    573             return middle_avg
    574         
    575         except Exception as error : 
    576             print(f'Error : An unexpected error happened : {error}')
    577             return None
    578 
    579 def mode(inp_set) : 
    580     """
    581     Gives the mode value of a set
    582 
    583     Args:
    584         set = Input set given by user
    585     
    586     Returns:
    587         Mode value of the input set.
    588         None if the input is not valid or any error occurs.
    589     """
    590     # mode function can be used for any data type.
    591     try : 
    592         set_len = len(inp_set)
    593         if set_len == 0 : 
    594             print('Error : Set should not be empty.')
    595             return None
    596     except Exception as error : 
    597             print(f'Error : An unexpected error happened : {error}')
    598             return None
    599     
    600     # trying to get the total number of times a element appeared in the set
    601     try : 
    602         processed_elements_list = []
    603         element_details = []
    604 
    605         for i in range(set_len) : 
    606             current_element = inp_set[i]
    607             already_done = False
    608 
    609             for processed_element in processed_elements_list :
    610                 if current_element == processed_element :
    611                     already_done = True 
    612                     break
    613             
    614             if not already_done : 
    615                 count = 0
    616                 for j in range(set_len) :
    617                     if current_element == inp_set[j] :
    618                         count += 1
    619                 
    620                 element_details.append([current_element, count])
    621                 processed_elements_list.append(current_element)
    622     
    623     except Exception as error :
    624         print(f'Error : An unexpected error happened : {error}')
    625         return None
    626     
    627     # now sending the mode data
    628     try : 
    629         if not element_details: # Handle case where element_details might be empty (e.g., if inp_set was empty, though handled earlier)
    630             return None
    631 
    632         highest_count = 0
    633         for i in range(len(element_details)) :
    634             if element_details[i][1] > highest_count :
    635                 highest_count = element_details[i][1]
    636         
    637         highest_count_element = []
    638         for i in range(len(element_details)) :
    639             if element_details[i][1] == highest_count :
    640                 highest_count_element.append(element_details[i][0])
    641 
    642         return highest_count_element, highest_count
    643     
    644     except Exception as error :
    645         print(f'Error : An unexpected error happened : {error}')
    646         return None
    647 
    648 
    649 # the end
© notamitgamer • Site Built: 2026-07-21 13:58:23 UTC • git-mirror commit: 1037f62 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror