Python Built-in Functions & Basics Common Built-in Functions abs() : Returns the absolute value of a number. round() : Rounds a number to a specified number of decimal places. len() : Returns the length (number of items) of an object. sum() : Sums the items of an iterable. max() : Returns the largest item in an iterable or between two or more arguments. min() : Returns the smallest item in an iterable or between two or more arguments. print() : Prints objects to the text stream. input() : Reads a line from input, converts to a string. type() : Returns the type of an object. range() : Returns a sequence of numbers. Basic Operations & Predictions abs(-15) $\rightarrow 15$ round(3.14159, 2) $\rightarrow 3.14$ 9 // 2 (Floor division) $\rightarrow 4$ 2 ** 5 (Exponentiation) $\rightarrow 32$ is_even(n) Function def is_even(n): return n % 2 == 0 Sum of Squares (First 20 positive integers) sum_of_squares = 0 for i in range(1, 21): sum_of_squares += i**2 print(sum_of_squares) # Output: 2870 Python Sequence Types List Ordered, mutable sequence of items. Can contain items of different data types. Defined using square brackets: my_list = [1, 'hello', 3.14] Set Unordered collection of unique items. Mutable, but elements must be immutable. Defined using curly braces or set() : my_set = {1, 2, 3} , another_set = set([3, 4, 5]) Dictionary Unordered collection of key-value pairs. Keys must be unique and immutable; values can be of any type. Defined using curly braces with colons: my_dict = {'name': 'Alice', 'age': 30} Numerical Methods & Approximations Euler's Constant Approximation Series: $e = \sum_{n=0}^{\infty} \frac{1}{n!}$ import math e_approx = 0 factorial = 1 for n in range(10): # First 10 terms (n=0 to n=9) e_approx += 1 / factorial factorial *= (n + 1) print(f"Approximation of e: {e_approx}") print(f"math.e: {math.e}") print(f"Difference: {abs(e_approx - math.e)}") Basel Problem Approximation Problem: $\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}$ import math basel_sum = 0 for n in range(1, 1001): # First 1000 terms basel_sum += 1 / (n**2) pi_squared_over_6 = (math.pi**2) / 6 print(f"Basel sum (1000 terms): {basel_sum}") print(f"pi^2 / 6: {pi_squared_over_6}") print(f"Difference: {abs(basel_sum - pi_squared_over_6)}") approx_zeta(s, N) Function Approximates $\zeta(s, N) = \sum_{n=1}^{N} \frac{1}{n^s}$ def approx_zeta(s, N): zeta_sum = 0 for n in range(1, N + 1): zeta_sum += 1 / (n**s) return zeta_sum # Test for s = 3, N = 1000 result_zeta = approx_zeta(3, 1000) print(f"approx_zeta(3, 1000): {result_zeta}") Trapezoidal Rule for Integration Formula: $\int_a^b f(x) dx \approx \frac{h}{2} [f(a) + f(b) + 2\sum_{i=1}^{N-1} f(x_i)]$ where $h = \frac{b-a}{N}$ import math def trapezoid(f, a, b, N): h = (b - a) / N integral = (f(a) + f(b)) / 2 for i in range(1, N): integral += f(a + i * h) return integral * h # Test with f(x) = sin(x), a = 0, b = pi, N = 100 def sin_func(x): return math.sin(x) a = 0 b = math.pi N = 100 approx_integral = trapezoid(sin_func, a, b, N) print(f"Trapezoidal approximation of integral: {approx_integral}") # Analytical result of integral(sin(x) dx from 0 to pi) = [-cos(x)] from 0 to pi = -cos(pi) - (-cos(0)) = 1 - (-1) = 2 analytical_result = 2 print(f"Analytical result: {analytical_result}") print(f"Difference: {abs(approx_integral - analytical_result)}") Functions and Algorithms Geometric Mean Formula: $GM(X) = \sqrt[n]{x_1 \cdot x_2 \cdot \ldots \cdot x_n}$ def geometric_mean(X): if not X: return 0 product = 1 for x in X: if x Euler's Method for ODEs Method: $y_{n+1} = y_n + h \cdot f(y_n, t_n)$ def rk_euler(f, y0, t_range): """ f: function f(y, t) from y' = f(y, t) y0: initial condition y(t[0]) = y0 t_range: list or array of t values [t0, t1, ..., tn] """ y_values = [y0] for i in range(len(t_range) - 1): h = t_range[i+1] - t_range[i] y_next = y_values[-1] + h * f(y_values[-1], t_range[i]) y_values.append(y_next) return y_values # Apply to y' = y + t, y(0) = 1, t = 0 to 1, step 0.1 import numpy as np def f_ode(y, t): return y + t y0_ode = 1 t_start = 0 t_end = 1 step_size = 0.1 t_values = np.arange(t_start, t_end + step_size, step_size) solution_euler = rk_euler(f_ode, y0_ode, t_values) print(f"Euler's method solution for y' = y + t: {solution_euler}") Triangle Area (Heron's Formula) For sides $a, b, c$ and semi-perimeter $s = (a+b+c)/2$, Area $= \sqrt{s(s-a)(s-b)(s-c)}$ import math def triangle_area(vertices): ((x1, y1), (x2, y2), (x3, y3)) = vertices # Calculate side lengths a = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) b = math.sqrt((x3 - x2)**2 + (y3 - y2)**2) c = math.sqrt((x1 - x3)**2 + (y1 - y3)**2) # Calculate semi-perimeter s = (a + b + c) / 2 # Heron's formula # Check for valid triangle (prevents math domain error for s Arithmetic Mean def mean(X): if not X: return 0 return sum(X) / len(X) # Example: # print(mean([1, 2, 3, 4, 5])) # Output: 3.0 NumPy Row Operations import numpy as np def add_row(A, i, j, k): """ Adds k times row i to row j in a 2D NumPy array A. Modifies A in-place. """ if not isinstance(A, np.ndarray) or A.ndim != 2: raise ValueError("Input A must be a 2D NumPy array.") if not (0 Collatz Sequence Rule: If $n$ is even, $n \rightarrow n/2$. If $n$ is odd, $n \rightarrow 3n+1$. def collatz_steps(a): if a Polynomial Operations Polynomial: $p(x) = c_n x^n + c_{n-1} x^{n-1} + \ldots + c_1 x + c_0$ Coefficients: coeffs = [c_n, c_{n-1}, ..., c_1, c_0] Polynomial Derivative If $p(x) = 2x^3 - 3x^2 + 4x - 7$, then $p'(x) = 6x^2 - 6x + 4$. def poly_derivative(coeffs): if len(coeffs) Second Derivative of a Polynomial def second_derivative(coeffs): first_deriv_coeffs = poly_derivative(coeffs) second_deriv_coeffs = poly_derivative(first_deriv_coeffs) return second_deriv_coeffs # Example for p(x) = 2x^3 - 3x^2 + 4x - 7 # coeffs = [2, -3, 4, -7] # second_deriv = second_derivative(coeffs) # Expected: [12, -6] (for 12x - 6) # print(f"Second derivative coefficients: {second_deriv}") Evaluate Polynomial at a Point def evaluate_poly(coeffs, x): result = 0 degree = len(coeffs) - 1 for i, coeff in enumerate(coeffs): result += coeff * (x**(degree - i)) return result # Example: # print(evaluate_poly([12, -6], 1)) # For 12x - 6 at x=1, gives 6 is_concave_up(coeffs, a) Function Checks if $p''(a) > 0$. def is_concave_up(coeffs, a): second_deriv_coeffs = second_derivative(coeffs) if not second_deriv_coeffs or second_deriv_coeffs == [0]: return False # Not enough degree for concavity or is a line/constant # Evaluate the second derivative at point 'a' p_double_prime_at_a = evaluate_poly(second_deriv_coeffs, a) return p_double_prime_at_a > 0 # Example for p(x) = 2x^3 - 3x^2 + 4x - 7 # coeffs_poly = [2, -3, 4, -7] # print(f"Is concave up at x=1? {is_concave_up(coeffs_poly, 1)}") # p''(1) = 12(1) - 6 = 6 > 0 (True) # print(f"Is concave up at x=0? {is_concave_up(coeffs_poly, 0)}") # p''(0) = 12(0) - 6 = -6 Secant Method for Root Finding Formula: $x_{n+1} = x_n - f(x_n) \frac{x_n - x_{n-1}}{f(x_n) - f(x_{n-1})}$ def secant_root(f, a, b, N): """ f: the function for which to find the root a, b: initial guesses for the root N: number of iterations """ x_prev = a x_curr = b for _ in range(N): f_prev = f(x_prev) f_curr = f(x_curr) if f_curr - f_prev == 0: # Avoid division by zero print("Secant method failed: Division by zero (f(x_curr) == f(x_prev))") return x_curr x_next = x_curr - f_curr * (x_curr - x_prev) / (f_curr - f_prev) x_prev = x_curr x_curr = x_next return x_curr # Apply to f(x) = x^2 - 2 with a = 1, b = 2, N = 10 def f_secant(x): return x**2 - 2 a_secant = 1 b_secant = 2 N_secant = 10 approx_root = secant_root(f_secant, a_secant, b_secant, N_secant) print(f"Approximated root of x^2 - 2: {approx_root}") print(f"Check f({approx_root}): {f_secant(approx_root)}")