adpkg

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

test2.py (8716B)


      1 import adcustom as c
      2 
      3 def get_integer_input(prompt):
      4     while True:
      5         try:
      6             return int(input(prompt))
      7         except ValueError:
      8             print("Invalid input. Please enter an integer.")
      9 
     10 def get_float_input(prompt):
     11     while True:
     12         try:
     13             return float(input(prompt))
     14         except ValueError:
     15             print("Invalid input. Please enter a number (integer or float).")
     16 
     17 def get_list_of_numbers_input(prompt):
     18     while True:
     19         s = input(prompt)
     20         if not s.strip(): # Handle empty input for empty list
     21             return []
     22         try:
     23             # Attempt to convert each part to a float, allowing for integers as well
     24             return [float(x.strip()) for x in s.split(',')]
     25         except ValueError:
     26             print("Invalid input. Please enter comma-separated numbers (e.g., 1, 2.5, 3).")
     27 
     28 def get_general_list_input(prompt):
     29     while True:
     30         s = input(prompt)
     31         if not s.strip(): # Handle empty input for empty list
     32             return []
     33         # For general lists, we'll split by comma and strip spaces.
     34         # The function itself handles type conversion/validation.
     35         return [x.strip() for x in s.split(',')]
     36 
     37 def get_matrix_input(prompt):
     38     matrix = []
     39     print(prompt + " (Enter rows separated by ';', elements by ',' e.g., '1,2;3,4')")
     40     while True:
     41         s = input("Enter matrix row(s) (or type 'done' to finish): ").strip()
     42         if s.lower() == 'done':
     43             break
     44         if not s:
     45             print("Row cannot be empty. Please enter elements or 'done'.")
     46             continue
     47         try:
     48             rows_str = s.split(';')
     49             current_matrix = []
     50             for row_str in rows_str:
     51                 row_elements = [float(x.strip()) for x in row_str.split(',')]
     52                 current_matrix.append(row_elements)
     53 
     54             # Basic validation for consistency of rows for the first row entered
     55             if not matrix and current_matrix: # If this is the first matrix input
     56                 for r in current_matrix:
     57                     matrix.append(r)
     58             elif matrix and current_matrix: # If subsequent rows, check consistency
     59                 if len(current_matrix[0]) != len(matrix[0]):
     60                     print("Error: All rows must have the same number of columns.")
     61                     matrix = [] # Clear and restart input for this matrix
     62                     raise ValueError("Inconsistent column count")
     63                 for r in current_matrix:
     64                     matrix.append(r)
     65             else: # If s was empty or only whitespace, and not 'done'
     66                 print("Invalid row input. Please enter comma-separated numbers.")
     67                 continue
     68             return matrix
     69         except ValueError as e:
     70             if "Inconsistent column count" in str(e): # Handled above, restart loop
     71                 continue
     72             print("Invalid matrix input. Ensure elements are numbers and rows are comma-separated.")
     73             print("Example: '1,2;3,4' for [[1,2],[3,4]]")
     74             matrix = [] # Clear and retry input if invalid format
     75             continue
     76 
     77     if not matrix:
     78         print("No valid matrix entered.")
     79         return None # Return None if no matrix was successfully entered or user exits without input
     80     return matrix
     81 
     82 
     83 def run_interactive_test():
     84     print("--- Interactive Test for custom.py module ---")
     85     while True:
     86         print("\nSelect a function to test:")
     87         print("1. add(num1, num2)")
     88         print("2. check_prime(num)")
     89         print("3. factorial(num)")
     90         print("4. permutation(total, chosen)")
     91         print("5. combination(total, chosen)")
     92         print("6. string_reverse(text)")
     93         print("7. matrix_addition(mat1, mat2)")
     94         print("8. matrix_multiplication(mat1, mat2)")
     95         print("9. matrix_transpose(mat)")
     96         print("10. determinant_value(mat)")
     97         print("11. mean(data_list)")
     98         print("12. median(data_list)")
     99         print("13. mode(data_list)")
    100         print("0. Exit")
    101 
    102         choice = input("Enter your choice (0-13): ")
    103 
    104         if choice == '0':
    105             print("Exiting interactive test. Goodbye!")
    106             break
    107         elif choice == '1':
    108             num1 = get_float_input("Enter first number: ")
    109             num2 = get_float_input("Enter second number: ")
    110             result = c.add(num1, num2)
    111             print(f"Result of add({num1}, {num2}): {result}")
    112         elif choice == '2':
    113             num = get_integer_input("Enter an integer to check if prime: ")
    114             result = c.check_prime(num)
    115             print(f"Result of check_prime({num}): {result} (1=Prime, 0=Not Prime, None=Error)")
    116         elif choice == '3':
    117             num = get_integer_input("Enter a non-negative integer for factorial: ")
    118             result = c.factorial(num)
    119             print(f"Result of factorial({num}): {result}")
    120         elif choice == '4':
    121             n = get_integer_input("Enter total items (n): ")
    122             k = get_integer_input("Enter chosen items (k): ")
    123             result = c.permutation(n, k)
    124             print(f"Result of permutation({n}, {k}): {result}")
    125         elif choice == '5':
    126             n = get_integer_input("Enter total items (n): ")
    127             k = get_integer_input("Enter chosen items (k): ")
    128             result = c.combination(n, k)
    129             print(f"Result of combination({n}, {k}): {result}")
    130         elif choice == '6':
    131             text = input("Enter a string to reverse: ")
    132             result = c.string_reverse(text)
    133             print(f"Result of string_reverse('{text}'): {result}")
    134         elif choice == '7':
    135             print("\n--- Input for Matrix 1 ---")
    136             mat1 = get_matrix_input("Matrix 1")
    137             print("\n--- Input for Matrix 2 ---")
    138             mat2 = get_matrix_input("Matrix 2")
    139             if mat1 is not None and mat2 is not None:
    140                 print("\nCalculating Matrix Addition...")
    141                 result = c.matrix_addition(mat1, mat2)
    142                 print(f"Result of matrix_addition:\n{result}")
    143             else:
    144                 print("Matrix input was invalid or incomplete. Cannot perform addition.")
    145         elif choice == '8':
    146             print("\n--- Input for Matrix 1 ---")
    147             mat1 = get_matrix_input("Matrix 1")
    148             print("\n--- Input for Matrix 2 ---")
    149             mat2 = get_matrix_input("Matrix 2")
    150             if mat1 is not None and mat2 is not None:
    151                 print("\nCalculating Matrix Multiplication...")
    152                 result = c.matrix_multiplication(mat1, mat2)
    153                 print(f"Result of matrix_multiplication:\n{result}")
    154             else:
    155                 print("Matrix input was invalid or incomplete. Cannot perform multiplication.")
    156         elif choice == '9':
    157             mat = get_matrix_input("\n--- Input for Matrix to Transpose ---")
    158             if mat is not None:
    159                 print("\nCalculating Matrix Transpose...")
    160                 result = c.matrix_transpose(mat)
    161                 print(f"Result of matrix_transpose:\n{result}")
    162             else:
    163                 print("Matrix input was invalid or incomplete. Cannot perform transpose.")
    164         elif choice == '10':
    165             mat = get_matrix_input("\n--- Input for Matrix to get Determinant Value ---")
    166             if mat is not None:
    167                 print("\nCalculating Determinant Value...")
    168                 result = c.determinant_value(mat)
    169                 print(f"Result of determinant_value: {result}")
    170             else:
    171                 print("Matrix input was invalid or incomplete. Cannot calculate determinant.")
    172         elif choice == '11':
    173             data_list = get_list_of_numbers_input("Enter comma-separated numbers for mean (e.g., 1,2,3.5): ")
    174             result = c.mean(data_list)
    175             print(f"Result of mean({data_list}): {result}")
    176         elif choice == '12':
    177             data_list = get_list_of_numbers_input("Enter comma-separated numbers for median (e.g., 1,2,3.5): ")
    178             result = c.median(data_list)
    179             print(f"Result of median({data_list}): {result}")
    180         elif choice == '13':
    181             # Mode can take mixed types
    182             data_list = get_general_list_input("Enter comma-separated values for mode (e.g., apple,banana,apple,1,2,1): ")
    183             result = c.mode(data_list)
    184             print(f"Result of mode({data_list}): {result}")
    185         else:
    186             print("Invalid choice. Please enter a number between 0 and 13.")
    187 
    188 # Run the interactive test
    189 if __name__ == "__main__":
    190     run_interactive_test()
© 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