From bae7e157c533848a79ebe6357e7db5aa61fcc5df Mon Sep 17 00:00:00 2001 From: sysu-JohnLiu <2398549260@qq.com> Date: Sat, 12 Jul 2025 03:10:54 +0800 Subject: [PATCH 1/7] Update Cholesky.py --- Algebra/Cholesky.py | 40 ++++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/Algebra/Cholesky.py b/Algebra/Cholesky.py index 436cde6..707bc1d 100644 --- a/Algebra/Cholesky.py +++ b/Algebra/Cholesky.py @@ -1,24 +1,40 @@ import numpy as np from math import sqrt -def cholesky_decomposition(A): +def cholesky_decomposition(A: np.ndarray) -> np.ndarray: """ Perform Cholesky decomposition on a matrix A. A must be a symmetric, positive-definite matrix. Returns the lower triangular matrix L such that A = L * L^T. + + Raises: + ValueError: If the input matrix is not square, not symmetric, + or not positive definite. """ - n = len(A) - L = np.zeros((n, n)) # Initialize L with zeros - + # Validate input matrix + if A.ndim != 2 or A.shape[0] != A.shape[1]: + raise ValueError("Input matrix must be square") + + n = A.shape[0] + L = np.zeros_like(A, dtype=float) # Initialize L with zeros + + # Check matrix symmetry + if not np.allclose(A, A.T, atol=1e-10): + raise ValueError("Input matrix must be symmetric") + for k in range(n): - # Calculate the diagonal element L[k][k] - sum_squares = sum(L[k][j] ** 2 for j in range(k)) - L[k][k] = sqrt(A[k][k] - sum_squares) - - # Calculate the off-diagonal elements L[i][k] + # Calculate diagonal element + diagonal_term = A[k, k] - np.sum(L[k, :k] ** 2) + + # Check positive definiteness + if diagonal_term <= 0: + raise ValueError("Matrix is not positive definite") + + L[k, k] = sqrt(diagonal_term) + + # Calculate off-diagonal elements for row k for i in range(k + 1, n): - sum_products = sum(L[i][j] * L[k][j] for j in range(k)) - L[i][k] = (A[i][k] - sum_products) / L[k][k] - + L[i, k] = (A[i, k] - np.sum(L[i, :k] * L[k, :k])) / L[k, k] + return L From 736c1c8a2ade121277059804c0e46e06aa2bbe48 Mon Sep 17 00:00:00 2001 From: sysu-JohnLiu <2398549260@qq.com> Date: Sat, 12 Jul 2025 03:12:30 +0800 Subject: [PATCH 2/7] Update Gauss.py --- Algebra/Gauss.py | 89 ++++++++++++++++++------------------------------ 1 file changed, 34 insertions(+), 55 deletions(-) diff --git a/Algebra/Gauss.py b/Algebra/Gauss.py index 01a629d..f8aa2ca 100644 --- a/Algebra/Gauss.py +++ b/Algebra/Gauss.py @@ -1,57 +1,36 @@ -from numpy import zeros,array, eye, copy, dot - -def Gauss(A,b): - size = len(A) - A = array(A) - P = eye(size) - for i in range(size-1): - maxRow = i - for j in range(i+1,size): - if abs(A[j][i]) > abs(A[maxRow][i]): - maxRow = j - if maxRow != i: - #### Swap - P[[maxRow,i]] = P[[i, maxRow]] - A[[maxRow,i]] = A[[i, maxRow]] - for k in range(i+1, size): - A[k][i] /= A[i][i] - for j in range(i+1, size): - A[k][j] -= A[k][i]*A[i][j] - - L = eye(size) - for i in range(size): - for j in range(i): - L[i][j] = A[i][j] - - U = zeros((size,size)) - for i in range(size): - for j in range(i,size): - U[i][j] = A[i][j] - - b = array(b) - - y = copy(dot(P,b)) - - # forwards - for i in range(size): - if L[i][i] == 0: #Division by 0 - y[i] = 0 - continue - for j in range(i): - y[i] = (y[i] - L[i][j]*y[j])/L[i][i] +import numpy as np +def gauss_elimination(A, b): + A = np.asarray(A, dtype=float) + b = np.asarray(b, dtype=float) - x = zeros((size,1)) - x[size-1] = y[size-1]/U[size-1][size-1] - - for i in range(size-1,-1,-1): - if U[i][i] == 0: #Division by 0 - x[i] = 0 - continue - xv = y[i] - for j in range(i+1,size): - xv -= U[i][j]*x[j] - xv /= U[i][i] - x[i] = xv - - return x \ No newline at end of file + if A.ndim != 2 or A.shape[0] != A.shape[1]: + raise ValueError("Coefficient matrix A must be square") + + n = A.shape[0] + + if b.ndim != 1 or len(b) != n: + raise ValueError("Right-hand side vector b must have same length as rows of A") + + augmented = np.column_stack((A, b)) + + for i in range(n): + max_row = np.argmax(np.abs(augmented[i:, i])) + i + if max_row != i: + augmented[[i, max_row]] = augmented[[max_row, i]] + + pivot = augmented[i, i] + if np.abs(pivot) < 1e-10: + raise ValueError("Matrix is nearly singular, cannot solve using Gaussian elimination") + + augmented[i, i:] /= pivot + + for j in range(i+1, n): + factor = augmented[j, i] + augmented[j, i:] -= factor * augmented[i, i:] + + x = np.zeros(n) + for i in range(n-1, -1, -1): + x[i] = augmented[i, -1] - np.sum(augmented[i, i+1:-1] * x[i+1:]) + + return x From a7bc03ab8251cdfd02cf31b48f8f0c659365fbc4 Mon Sep 17 00:00:00 2001 From: sysu-JohnLiu <2398549260@qq.com> Date: Sat, 12 Jul 2025 03:38:45 +0800 Subject: [PATCH 3/7] Update function_to_graph.py --- Algebra/function_to_graph.py | 93 ++++++++++++++++++++++-------------- 1 file changed, 56 insertions(+), 37 deletions(-) diff --git a/Algebra/function_to_graph.py b/Algebra/function_to_graph.py index 6464621..9e6670c 100644 --- a/Algebra/function_to_graph.py +++ b/Algebra/function_to_graph.py @@ -1,41 +1,60 @@ import matplotlib.pyplot as plt import numpy as np - -xmin = -100 -xmax = 100 -ymin = -100 -ymax = 100 -points = xmax - xmin -x = np.linspace(xmin, xmax, points) - - -while True: - eq = input("Enter the equation for y in terms of x: ") - - # Use eval() to evaluate the user's input as a mathematical expression +def get_valid_expression(prompt: str) -> str: + while True: + expr = input(prompt).strip() + if is_safe_expression(expr): + return expr + print("Invalid or unsafe expression. Please try again.") + +def is_safe_expression(expr: str) -> bool: + allowed_names = {'sin': np.sin, 'cos': np.cos, 'tan': np.tan, + 'exp': np.exp, 'log': np.log, 'sqrt': np.sqrt, + 'pi': np.pi, 'e': np.e} + code = compile(expr, '', 'eval') + for name in code.co_names: + if name not in allowed_names: + return False + return True + +def main(): + xmin, xmax = -100, 100 + ymin, ymax = -100, 100 + points = 1000 + + x = np.linspace(xmin, xmax, points) + + eq = get_valid_expression("Enter the equation for y in terms of x: ") + + allowed_names = {'sin': np.sin, 'cos': np.cos, 'tan': np.tan, + 'exp': np.exp, 'log': np.log, 'sqrt': np.sqrt, + 'pi': np.pi, 'e': np.e, 'x': x} try: - y = eval(eq) # Evaluate the expression with x as a variable - break - except: - print("Invalid input equation.") - - -fig, ax = plt.subplots() -plt.axis([xmin, xmax, ymin, ymax]) -plt.plot([xmin, xmax], [0, 0], "b") -plt.plot([0, 0], [ymin, ymax], "b") - -ax.set_xlabel("x values") -ax.set_ylabel("y values") -ax.set_title("Equation Graph") -ax.grid(True) - -ax.set_xticks(np.arange(xmin, xmax, 20)) -ax.set_yticks(np.arange(ymin, ymax, 20)) - - -plt.plot(x, y, label=f"y= {eq}") - -plt.legend() -plt.show() + y = eval(eq, {"__builtins__": None}, allowed_names) + except Exception as e: + print(f"Error evaluating expression: {e}") + return + + fig, ax = plt.subplots(figsize=(10, 8)) + plt.axis([xmin, xmax, ymin, ymax]) + + plt.axhline(y=0, color='blue', linestyle='-', alpha=0.5) + plt.axvline(x=0, color='blue', linestyle='-', alpha=0.5) + + ax.set_xlabel("x values", fontsize=12) + ax.set_ylabel("y values", fontsize=12) + ax.set_title("Equation Graph", fontsize=14) + ax.grid(True, linestyle='--', alpha=0.7) + + ax.set_xticks(np.arange(xmin, xmax+1, 20)) + ax.set_yticks(np.arange(ymin, ymax+1, 20)) + + plt.plot(x, y, label=f"y = {eq}", linewidth=2) + + plt.legend(fontsize=12) + plt.tight_layout() + plt.show() + +if __name__ == "__main__": + main() From c103c2ad85368e2988b822d2adacf665c9ef57f3 Mon Sep 17 00:00:00 2001 From: sysu-JohnLiu <2398549260@qq.com> Date: Sat, 12 Jul 2025 03:39:51 +0800 Subject: [PATCH 4/7] Update graphing_calculator.py --- Algebra/graphing_calculator.py | 265 +++++++++++++++++---------------- 1 file changed, 136 insertions(+), 129 deletions(-) diff --git a/Algebra/graphing_calculator.py b/Algebra/graphing_calculator.py index c3122d6..6c6deb0 100644 --- a/Algebra/graphing_calculator.py +++ b/Algebra/graphing_calculator.py @@ -1,157 +1,164 @@ import numpy as np import matplotlib.pyplot as plt -from sympy import * +from sympy import symbols, linsolve, simplify -def main(): +def get_valid_input(prompt, validation_func=None): while True: - print("\nMenu:") - print("1. Display the graph and table of values for an equation") - print("2. Solve a system of two equations without graphing") - print("3. Graph two equations and plot the point of intersection") - print("4. Plot the roots and vertex of a quadratic equation") - print("5. Exit") - - choice = input("Enter your choice: ") - - if choice == '1': - display_graph_and_table() - elif choice == '2': - solve_system_of_equations() - elif choice == '3': - graph_and_find_intersection() - elif choice == '4': - plot_quadratic_roots_and_vertex() - elif choice == '5': - break - else: - print("Invalid choice. Please try again.") + user_input = input(prompt).strip() + if validation_func is None or validation_func(user_input): + return user_input + print("Invalid input. Please try again.") + +def is_number(s): + try: + float(s) + return True + except ValueError: + return False + +def is_valid_expression(expr, symbols): + try: + sympy_expr = simplify(expr) + allowed_symbols = {str(s) for s in symbols} + return all(str(s) in allowed_symbols for s in sympy_expr.free_symbols) + except: + return False def display_graph_and_table(): - equation = input("Enter the equation in terms of 'x': y = ") - x = np.linspace(-10, 10, 400) # Adjust the range as needed - y = eval(equation) - plt.plot(x, y) + x = symbols('x') + equation = get_valid_input("Enter the equation in terms of 'x': y = ", + lambda e: is_valid_expression(e, [x])) + x_vals = np.linspace(-10, 10, 400) + y_vals = np.array([simplify(equation).subs(x, val) for val in x_vals], dtype=float) + + plt.figure(figsize=(10, 5)) + plt.subplot(1, 2, 1) + plt.plot(x_vals, y_vals) plt.xlabel('x') plt.ylabel('y') - plt.title(f'Graph of {equation}') + plt.title(f'Graph of y = {equation}') plt.grid(True) - plt.show() - display_table(equation) - -def display_table(equation): - ax = plt.subplot() - ax.set_axis_off() - title = f"y = {equation}" - cols = ('x', 'y') - rows = [[0, 0]] - for x in range(1, 10): - rows.append([x, eval(equation)]) - - ax.set_title(title) - plt.table(cellText=rows, colLabels=cols, cellLoc='center', loc='upper left') + + plt.subplot(1, 2, 2) + plt.axis('off') + rows = [[x_val, simplify(equation).subs(x, x_val)] for x_val in range(-5, 6)] + plt.table(cellText=rows, colLabels=['x', 'y'], cellLoc='center', loc='center') + plt.title("Values Table") + + plt.tight_layout() plt.show() def solve_system_of_equations(): x, y = symbols('x y') - print("Remember to use Python syntax with x and y as variables") - print("Notice how each equation is already set equal to zero") - first = input("Enter the first equation: 0 = ") - second = input("Enter the second equation: 0 = ") - solution = linsolve([first, second], (x, y)) - x_solution = solution.args[0][0] - y_solution = solution.args[0][1] - - print("x = ", x_solution) - print("y = ", y_solution) + print("Use Python syntax with x and y as variables (e.g., 2*x + 3*y - 6)") + first = get_valid_input("Enter the first equation: 0 = ", + lambda e: is_valid_expression(e, [x, y])) + second = get_valid_input("Enter the second equation: 0 = ", + lambda e: is_valid_expression(e, [x, y])) + + try: + solution = linsolve([first, second], (x, y)) + if not solution: + print("No solution exists.") + else: + x_sol, y_sol = solution.args[0] + print(f"Solution: x = {x_sol}, y = {y_sol}") + except Exception as e: + print(f"Error solving system: {e}") def graph_and_find_intersection(): - print("First equation: y = mx + b") - mb_1 = input("Enter m and b, separated by a comma: ") - mb_in1 = mb_1.split(",") - m1 = float(mb_in1[0]) - b1 = float(mb_in1[1]) - - print("Second equation: y = mx + b") - mb_2 = input("Enter m and b, separated by a comma: ") - mb_in2 = mb_2.split(",") - m2 = float(mb_in2[0]) - b2 = float(mb_in2[1]) - - # Solve the system of equations + m1, b1 = map(float, get_valid_input( + "Enter m and b for first equation (y=mx+b), separated by comma: ", + lambda s: len(s.split(',')) == 2 and all(is_number(p) for p in s.split(',')) + ).split(',')) + + m2, b2 = map(float, get_valid_input( + "Enter m and b for second equation (y=mx+b), separated by comma: ", + lambda s: len(s.split(',')) == 2 and all(is_number(p) for p in s.split(',')) + ).split(',')) + x, y = symbols('x y') - first = m1 * x + b1 - y - second = m2 * x + b2 - y - solution = linsolve([first, second], (x, y)) - x_solution = round(float(solution.args[0][0]), 3) - y_solution = round(float(solution.args[0][1]), 3) - - # Make sure the window includes the solution - xmin = int(x_solution) - 20 - xmax = int(x_solution) + 20 - ymin = int(y_solution) - 20 - ymax = int(y_solution) + 20 - points = 2 * (xmax - xmin) - - # Define the x values once for the graph - graph_x = np.linspace(xmin, xmax, points) - - # Define the y values for the graph - y1 = m1 * graph_x + b1 - y2 = m2 * graph_x + b2 - - fig, ax = plt.subplots() - plt.axis([xmin, xmax, ymin, ymax]) # window size - plt.plot([xmin, xmax], [0, 0], 'b') # blue x-axis - plt.plot([0, 0], [ymin, ymax], 'b') # blue y-axis - - # line 1 - plt.plot(graph_x, y1) - - # line 2 - plt.plot(graph_x, y2) - - # point - plt.plot([x_solution], [y_solution], 'ro') - - plt.show() - print(" ") - print("Solution: (", x_solution, ",", y_solution, ")") - -def plot_quadratic_roots_and_vertex(): - print("y = ax² + bx + c") - a = float(input("Enter the coefficient 'a' of the quadratic equation: ")) - b = float(input("Enter the coefficient 'b' of the quadratic equation: ")) - c = float(input("Enter the coefficient 'c' of the quadratic equation: ")) - xmin = -10 - xmax = 10 - ymin = -10 - ymax = 10 - points = 2 * (xmax - xmin) - x = np.linspace(xmin, xmax, points) - y = a * x**2 + b * x + c - plt.plot(x, y, label=f'y = {a}x^2 + {b}x + {c}') + try: + solution = linsolve([m1*x + b1 - y, m2*x + b2 - y], (x, y)) + x_sol, y_sol = map(float, solution.args[0]) + except: + print("Lines are parallel or coincident.") + return + + xmin, xmax = int(x_sol)-10, int(x_sol)+10 + ymin, ymax = int(y_sol)-10, int(y_sol)+10 + x_vals = np.linspace(xmin, xmax, 200) + + plt.figure(figsize=(8, 6)) + plt.plot(x_vals, m1*x_vals + b1, label=f'y = {m1}x + {b1}') + plt.plot(x_vals, m2*x_vals + b2, label=f'y = {m2}x + {b2}') + plt.plot(x_sol, y_sol, 'ro', label=f'Intersection ({x_sol:.2f}, {y_sol:.2f})') + + plt.axhline(y=0, color='k', alpha=0.5) + plt.axvline(x=0, color='k', alpha=0.5) plt.xlabel('x') plt.ylabel('y') - plt.title('Quadratic Equation') + plt.title('Intersection of Two Lines') plt.grid(True) + plt.legend() + plt.axis([xmin, xmax, ymin, ymax]) + plt.show() - # Calculate the roots using the quadratic formula - discriminant = b**2 - 4 * a * c +def plot_quadratic_roots_and_vertex(): + a = float(get_valid_input("Enter coefficient 'a': ", is_number)) + b = float(get_valid_input("Enter coefficient 'b': ", is_number)) + c = float(get_valid_input("Enter coefficient 'c': ", is_number)) + + x_vals = np.linspace(-10, 10, 400) + y_vals = a * x_vals**2 + b * x_vals + c + + plt.figure(figsize=(8, 6)) + plt.plot(x_vals, y_vals, label=f'y = {a}x² + {b}x + {c}') + + discriminant = b**2 - 4*a*c if discriminant > 0: - root1 = (-b + np.sqrt(discriminant)) / (2 * a) - root2 = (-b - np.sqrt(discriminant)) / (2 * a) - plt.scatter([root1, root2], [0, 0], color='green', label=f'Roots: x1={root1}, x2={root2}') + root1 = (-b + np.sqrt(discriminant)) / (2*a) + root2 = (-b - np.sqrt(discriminant)) / (2*a) + plt.scatter([root1, root2], [0, 0], color='red', s=50, label=f'Roots: {root1:.2f}, {root2:.2f}') elif discriminant == 0: - root = -b / (2 * a) - plt.scatter(root, 0, color='green', label=f'Root: x={root}') - - # Calculate the vertex - vertex_x = -b / (2 * a) + root = -b / (2*a) + plt.scatter([root], [0], color='red', s=50, label=f'Root: {root:.2f}') + + vertex_x = -b / (2*a) vertex_y = a * vertex_x**2 + b * vertex_x + c - plt.scatter(vertex_x, vertex_y, color='blue', label=f'Vertex ({vertex_x}, {vertex_y})') - + plt.scatter([vertex_x], [vertex_y], color='blue', s=50, label=f'Vertex: ({vertex_x:.2f}, {vertex_y:.2f})') + + plt.axhline(y=0, color='k', alpha=0.5) + plt.axvline(x=0, color='k', alpha=0.5) + plt.xlabel('x') + plt.ylabel('y') + plt.title('Quadratic Equation') + plt.grid(True) plt.legend() + plt.axis([-10, 10, -10, 10]) plt.show() +def main(): + while True: + print("\nMenu:") + print("1. Display graph and table of values") + print("2. Solve system of two equations") + print("3. Graph two equations and intersection") + print("4. Plot quadratic roots and vertex") + print("5. Exit") + + choice = get_valid_input("Enter your choice: ", lambda c: c in {'1', '2', '3', '4', '5'}) + + if choice == '1': + display_graph_and_table() + elif choice == '2': + solve_system_of_equations() + elif choice == '3': + graph_and_find_intersection() + elif choice == '4': + plot_quadratic_roots_and_vertex() + else: + break + if __name__ == '__main__': main() From 2874eea81d4e1dc0665cc0712dcc82bc70daa992 Mon Sep 17 00:00:00 2001 From: sysu-JohnLiu <2398549260@qq.com> Date: Sat, 12 Jul 2025 03:44:14 +0800 Subject: [PATCH 5/7] Update simple_calculator.py --- Algebra/simple_calculator.py | 287 +++++++++++++++++------------------ 1 file changed, 142 insertions(+), 145 deletions(-) diff --git a/Algebra/simple_calculator.py b/Algebra/simple_calculator.py index 3f18edd..3ef0cbc 100644 --- a/Algebra/simple_calculator.py +++ b/Algebra/simple_calculator.py @@ -4,182 +4,179 @@ import sys def main(): - - while True: - - main_menu() - choice = input("Enter your choice (1-12): ") - - if choice == '1': - perform_operation(add) - elif choice == '2': - perform_operation(subtract) - elif choice == '3': - perform_operation(multiply) - elif choice == '4': - perform_operation(divide) - elif choice == '5': - perform_operation(prime_number) - elif choice == '6': - perform_operation(prime_factor) - elif choice == '7': - perform_operation(square_root) - elif choice == '8': - perform_operation(solve) - elif choice == '9': - perform_operation(convert_decimals_to) - elif choice == '10': - perform_operation(convert_fractions_to) - elif choice == '11': - perform_operation(convert_percents_to) - elif choice == '12': - print("Goodbye!") - break - else: - print("Invalid choice. Please choose a valid option (1-12).") - - - - - + while True: + main_menu() + choice = input("Enter your choice (1-12): ") + + if choice == '1': + perform_operation(add) + elif choice == '2': + perform_operation(subtract) + elif choice == '3': + perform_operation(multiply) + elif choice == '4': + perform_operation(divide) + elif choice == '5': + perform_operation(check_prime) + elif choice == '6': + perform_operation(prime_factors) + elif choice == '7': + perform_operation(factor_square_root) + elif choice == '8': + perform_operation(solve_equation) + elif choice == '9': + perform_operation(decimal_to_other) + elif choice == '10': + perform_operation(fraction_to_other) + elif choice == '11': + perform_operation(percent_to_other) + elif choice == '12': + print("Goodbye!") + break + else: + print("Invalid choice. Please choose a valid option (1-12).") + +def get_integer_input(prompt): + while True: + try: + return int(input(prompt)) + except ValueError: + print("Invalid input. Please enter an integer.") + +def get_positive_integer(prompt): + while True: + num = get_integer_input(prompt) + if num > 0: + return num + print("Please enter a positive integer.") def add(): - try: - a = int(input('Enter an integer: ')) - b = int(input('Enter an integer: ')) - print(f"a+b = {a+b}") - except ValueError: - print("Invalid input. Please enter integers only.") + a = get_integer_input("Enter first integer: ") + b = get_integer_input("Enter second integer: ") + print(f"{a} + {b} = {a + b}") def subtract(): - try: - a = int(input('Enter an integer: ')) - b = int(input('Enter an integer: ')) - print(f"a-b = {a-b}") - except ValueError: - print("Invalid input. Please enter integers only.") + a = get_integer_input("Enter first integer: ") + b = get_integer_input("Enter second integer: ") + print(f"{a} - {b} = {a - b}") def multiply(): - try: - a = int(input('Enter an integer: ')) - b = int(input('Enter an integer: ')) - print(f"a*b = {a*b}") - except ValueError: - print("Invalid input. Please enter integers only.") + a = get_integer_input("Enter first integer: ") + b = get_integer_input("Enter second integer: ") + print(f"{a} * {b} = {a * b}") def divide(): - try: - a = int(input('Enter an integer: ')) - b = int(input('Enter an integer: ')) + a = get_integer_input("Enter dividend: ") + b = get_integer_input("Enter divisor: ") if b == 0: - print("Cannot divide by zero!") + print("Cannot divide by zero.") else: - print(f"a/b = {a/b}") - except ValueError: - print("Invalid input. Please enter integers only.") -def prime_number(): - try: - number = int(input("Enter a positive integer: ")) - if number <= 0: - print("Invalid input. Please enter a positive integer.") - return - is_prime = all(number % i != 0 for i in range(2, number)) - print("prime" if is_prime else "composite") - except ValueError: - print("Invalid input. Please enter a positive integer.") - -def prime_factor(): - try: - number = int(input('Enter an integer: ')) - if number <= 0: - print("Invalid input. Please enter a positive integer.") - return - factors = [i for i in range(1, number + 1) if number % i == 0] - print(factors) - except ValueError: - print("Invalid input. Please enter a positive integer.") - -def square_root(): - try: - n = int(input('Without the radical, enter a square root to factor: ')) - if n <= 0: - print("Invalid input. Please enter a positive integer.") + print(f"{a} / {b} = {a / b}") + +def check_prime(): + number = get_positive_integer("Enter a positive integer: ") + if number == 1: + print("1 is neither prime nor composite.") return - max_factor = max(i**2 for i in range(1, math.isqrt(n) + 1) if n % (i**2) == 0) - other_factor = n // max_factor - square_root = int(math.sqrt(max_factor)) - output = square_root * sqrt(other_factor) - print(output) - except ValueError: - print("Invalid input. Please enter a positive integer.") - -def solve(): - try: + is_prime = all(number % i != 0 for i in range(2, int(math.isqrt(number)) + 1)) + print(f"{number} is prime." if is_prime else f"{number} is composite.") + +def prime_factors(): + number = get_positive_integer("Enter a positive integer: ") + factors = [] + divisor = 2 + while divisor * divisor <= number: + while number % divisor == 0: + factors.append(divisor) + number //= divisor + divisor += 1 + if number > 1: + factors.append(number) + print(f"Prime factors: {factors}") + +def factor_square_root(): + n = get_positive_integer("Enter number to factor its square root: ") + max_square = max(i**2 for i in range(1, int(math.isqrt(n)) + 1) if n % (i**2) == 0) + other = n // max_square + root = int(math.sqrt(max_square)) + print(f"√{n} = {root}√{other}") + +def solve_equation(): x = symbols('x') - eq = input('Enter an equation to solve for x: 0 = ') - solutions = solve(eq, x) - print(f"x = {solutions[0]}" if solutions else "No solutions found.") - except (ValueError, TypeError, IndexError): - print("Invalid equation or no solutions found.") - -def convert_decimals_to(): - try: - decimal = float(input("Enter a decimal number to convert: ")) + eq = input("Enter equation to solve for x (0 = ...): ") + try: + solutions = solve(eq, x) + if solutions: + print(f"Solutions: x = {', '.join(map(str, solutions))}") + else: + print("No solutions found.") + except: + print("Invalid equation format.") + +def decimal_to_other(): + while True: + try: + decimal = float(input("Enter a decimal number: ")) + break + except ValueError: + print("Invalid input. Please enter a valid decimal.") fraction = Fraction(decimal).limit_denominator() percent = decimal * 100 - print(f"The decimal is {decimal}") - print(f"The fraction is {fraction}") - print(f"The percent is {percent}%") - except ValueError: - print("Invalid input. Please enter a valid decimal number.") - -def convert_fractions_to(): - try: - fraction = input("Enter a fraction (numerator/denominator): ") - numerator, denominator = map(int, fraction.split("/")) + print(f"Decimal: {decimal}") + print(f"Fraction: {fraction}") + print(f"Percent: {percent}%") + +def fraction_to_other(): + while True: + try: + fraction = input("Enter a fraction (numerator/denominator): ").strip() + numerator, denominator = map(int, fraction.split('/')) + if denominator == 0: + print("Denominator cannot be zero.") + continue + break + except (ValueError, TypeError): + print("Invalid format. Use numerator/denominator.") decimal = numerator / denominator percent = decimal * 100 - print(f"The decimal is {decimal}") - print(f"The percent is {percent}%") - except (ValueError, ZeroDivisionError): - print("Invalid input. Please enter a valid fraction.") - -def convert_percents_to(): - try: - percent = float(input("Enter a percent: ").strip("%")) + print(f"Decimal: {decimal}") + print(f"Percent: {percent}%") + +def percent_to_other(): + while True: + try: + percent = float(input("Enter a percent: ").strip('%')) + break + except ValueError: + print("Invalid input. Please enter a valid percent.") decimal = percent / 100 fraction = Fraction(decimal).limit_denominator() - print(f"The decimal is {decimal}") - print(f"The fraction is {fraction}") - except ValueError: - print("Invalid input. Please enter a valid percent.") + print(f"Decimal: {decimal}") + print(f"Fraction: {fraction}") -# Write your code here - -def perform_operation(operation_func): - operation_func() +def perform_operation(operation): + operation() if not continue_calculations(): sys.exit("Goodbye") def continue_calculations(): - check = input("Do you want to continue calculations? (Y/N): ").upper() - return check != "N" + response = input("Continue calculations? (Y/N): ").strip().upper() + return response != "N" def main_menu(): - print("Menu:") + print("\nMenu:") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") - print("5. Check if a Number is Prime") + print("5. Check Prime Number") print("6. Find Prime Factors") - print("7. Square Root Factorization") + print("7. Factor Square Root") print("8. Solve Equation for x") - print("9. Convert decimals to fractions and percents") - print("10. Convert fractions to decimals and percents") - print("11. Convert percents to decimals and fractions") + print("9. Convert Decimal to Fraction/Percent") + print("10. Convert Fraction to Decimal/Percent") + print("11. Convert Percent to Decimal/Fraction") print("12. Exit") - -if __name__=='__main__': +if __name__ == '__main__': main() From eda9cafabcea0a139f8e7a83a8c1ae5407742115 Mon Sep 17 00:00:00 2001 From: sysu-JohnLiu <2398549260@qq.com> Date: Sat, 12 Jul 2025 03:53:56 +0800 Subject: [PATCH 6/7] Update slope_intecept.py --- Algebra/slope_intecept.py | 79 ++++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/Algebra/slope_intecept.py b/Algebra/slope_intecept.py index df1c899..7cf32c6 100644 --- a/Algebra/slope_intecept.py +++ b/Algebra/slope_intecept.py @@ -1,37 +1,46 @@ import matplotlib.pyplot as plt -x1 = int(input("Please type x1 value :")) -y1 = int(input("Please type y1 value :")) -x2 = int(input("Please type x2 value :")) -y2 = int(input("Please type y2 value :")) - -# Develop the equation y = mx + b -m = (y2 - y1) / (x2 - x1) -b = y1 - m*x1 -equation = f'y = {m}x + {b}' - -# For the graph -xmin = -10 -xmax = 10 -ymin = -10 -ymax = 10 - -# For the line on the graph -y3 = m*xmin + b -y4 = m*xmax + b - -# Basic setup for the graph -fig, ax = plt.subplots() -plt.axis([xmin,xmax,ymin,ymax]) # window size -plt.plot([xmin,xmax],[0,0],'b') # blue x axis -plt.plot([0,0],[ymin,ymax], 'b') # blue y axis - - -# Plot the linear function as a red line -plt.plot([xmin,xmax],[y3,y4],'r',label=equation) -plt.scatter([x1, x2], [y1, y2], color='green', marker='o', label=f'Points ({x1}, {y1}), ({x2}, {y2})') - - - -plt.legend() -plt.show() \ No newline at end of file +def get_coordinate(prompt): + while True: + try: + return int(input(prompt)) + except ValueError: + print("Invalid input. Please enter an integer.") + +def calculate_line_parameters(x1, y1, x2, y2): + if x1 == x2: + return None, x1 # Vertical line x = x1 + m = (y2 - y1) / (x2 - x1) + b = y1 - m * x1 + return m, b + +def plot_line_and_points(x1, y1, x2, y2, m, b): + xmin, xmax = -10, 10 + ymin, ymax = -10, 10 + + fig, ax = plt.subplots() + plt.axis([xmin, xmax, ymin, ymax]) + plt.plot([xmin, xmax], [0, 0], 'b') + plt.plot([0, 0], [ymin, ymax], 'b') + + if m is None: + equation = f'x = {b}' + plt.axvline(x=b, color='r', label=equation) + else: + equation = f'y = {m}x + {b}' + y3 = m * xmin + b + y4 = m * xmax + b + plt.plot([xmin, xmax], [y3, y4], 'r', label=equation) + + plt.scatter([x1, x2], [y1, y2], color='green', marker='o', + label=f'Points ({x1}, {y1}), ({x2}, {y2})') + plt.legend() + plt.show() + +x1 = get_coordinate("Please enter x1 value: ") +y1 = get_coordinate("Please enter y1 value: ") +x2 = get_coordinate("Please enter x2 value: ") +y2 = get_coordinate("Please enter y2 value: ") + +m, b = calculate_line_parameters(x1, y1, x2, y2) +plot_line_and_points(x1, y1, x2, y2, m, b) From dc906bd62324905e7e7749cd5e8c23090e34dcfd Mon Sep 17 00:00:00 2001 From: sysu-JohnLiu <2398549260@qq.com> Date: Sat, 12 Jul 2025 03:56:45 +0800 Subject: [PATCH 7/7] Update temperature_prediction.py --- Neuronal-Red/temperature_prediction.py | 109 ++++++++++++++++++------- 1 file changed, 78 insertions(+), 31 deletions(-) diff --git a/Neuronal-Red/temperature_prediction.py b/Neuronal-Red/temperature_prediction.py index 08bff20..c2b2861 100644 --- a/Neuronal-Red/temperature_prediction.py +++ b/Neuronal-Red/temperature_prediction.py @@ -1,35 +1,82 @@ import tensorflow as tf import numpy as np +import matplotlib.pyplot as plt -# Input data -celsius = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=np.float16) -fahrenheit = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=np.float16) - -# Model definition -hidden1 = tf.keras.layers.Dense(units=3, input_shape=[1]) -hidden2 = tf.keras.layers.Dense(units=3) -output = tf.keras.layers.Dense(units=1) -model = tf.keras.Sequential([hidden1, hidden2, output]) - -# Model compilation -model.compile( - optimizer=tf.keras.optimizers.Adam(0.1), - loss='mean_squared_error' -) - -# Model training -print("Starting training...") -history = model.fit(celsius, fahrenheit, epochs=1000, verbose=False) -print("Model trained!") - -# Making a prediction -print("Let's make a prediction!") -result = model.predict([89.0]) -print("The result is " + str(result) + " fahrenheit") - -# Viewing the internal variables of the model -print("Internal model variables") -print(hidden1.get_weights()) -print(hidden2.get_weights()) -print(output.get_weights()) +# Configuration parameters +LEARNING_RATE = 0.1 +EPOCHS = 1000 +HIDDEN_UNITS = [3, 3] +def prepare_data(): + """Prepare and validate temperature conversion data""" + celsius = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=np.float16) + fahrenheit = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=np.float16) + + if len(celsius) != len(fahrenheit): + raise ValueError("Input arrays must have the same length") + + return celsius, fahrenheit + +def build_model(input_shape=[1]): + """Construct the neural network model""" + layers = [tf.keras.layers.Dense(units=units, input_shape=input_shape) + for units in HIDDEN_UNITS[:1]] + + layers.extend([tf.keras.layers.Dense(units=units) + for units in HIDDEN_UNITS[1:]]) + + layers.append(tf.keras.layers.Dense(units=1)) + + return tf.keras.Sequential(layers) + +def train_model(model, x, y): + """Train the model with specified parameters""" + model.compile( + optimizer=tf.keras.optimizers.Adam(LEARNING_RATE), + loss='mean_squared_error' + ) + + return model.fit(x, y, epochs=EPOCHS, verbose=False) + +def plot_training_loss(history): + """Plot training loss over epochs""" + plt.figure(figsize=(10, 6)) + plt.plot(history.history['loss']) + plt.title('Model Training Loss') + plt.ylabel('Loss') + plt.xlabel('Epoch') + plt.show() + +def predict_temperature(model, celsius_value): + """Predict fahrenheit from celsius using trained model""" + prediction = model.predict([celsius_value], verbose=False) + return float(prediction[0][0]) + +def main(): + # Data preparation + celsius, fahrenheit = prepare_data() + + # Model construction + model = build_model() + + # Model training + print("Starting training...") + history = train_model(model, celsius, fahrenheit) + print("Model trained!") + + # Visualize training process + plot_training_loss(history) + + # Make prediction + test_value = 89.0 + result = predict_temperature(model, test_value) + print(f"Prediction: {test_value}°C = {result:.2f}°F") + + # Display model weights + print("\nInternal model weights:") + for i, layer in enumerate(model.layers): + print(f"\nLayer {i+1} weights:") + print(layer.get_weights()) + +if __name__ == "__main__": + main()