instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate descriptive docstrings automatically
import numpy as np # List of input, output pairs train_data = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) test_data = (((515, 22, 13), 555), ((61, 35, 49), 150)) parameter_vector = [2, 4, 1, 5] m = len(train_data) LEARNING_RATE = 0.009 def _error(example_no, data_set="train"): return calculate_hypothesis_value(example_no, data_set) - output( example_no, data_set ) def _hypothesis_value(data_input_tuple): hyp_val = 0 for i in range(len(parameter_vector) - 1): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def output(example_no, data_set): if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def calculate_hypothesis_value(example_no, data_set): if data_set == "train": return _hypothesis_value(train_data[example_no][0]) elif data_set == "test": return _hypothesis_value(test_data[example_no][0]) return None def summation_of_cost_derivative(index, end=m): summation_value = 0 for i in range(end): if index == -1: summation_value += _error(i) else: summation_value += _error(i) * train_data[i][0][index] return summation_value def get_cost_derivative(index): cost_derivative_value = summation_of_cost_derivative(index, m) / m return cost_derivative_value def run_gradient_descent(): global parameter_vector # Tune these values to set a tolerance value for predicted output absolute_error_limit = 0.000002 relative_error_limit = 0 j = 0 while True: j += 1 temp_parameter_vector = [0, 0, 0, 0] for i in range(len(parameter_vector)): cost_derivative = get_cost_derivative(i - 1) temp_parameter_vector[i] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if np.allclose( parameter_vector, temp_parameter_vector, atol=absolute_error_limit, rtol=relative_error_limit, ): break parameter_vector = temp_parameter_vector print(("Number of iterations:", j)) def test_gradient_descent(): for i in range(len(test_data)): print(("Actual output value:", output(i, "test"))) print(("Hypothesis output:", calculate_hypothesis_value(i, "test"))) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
--- +++ @@ -1,3 +1,7 @@+""" +Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis +function. +""" import numpy as np @@ -16,12 +20,25 @@ def _error(example_no, data_set="train"): + """ + :param data_set: train data or test data + :param example_no: example number whose error has to be checked + :return: error in example pointed by example number. + """ return calculate_hypothesis_value(example_no, data_set) - output( example_no, data_set ) def _hypothesis_value(data_input_tuple): + """ + Calculates hypothesis function value for a given input + :param data_input_tuple: Input tuple of a particular example + :return: Value of hypothesis function at that point. + Note that there is an 'biased input' whose value is fixed as 1. + It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. + So, we have to take care of it separately. Line 36 takes care of it. + """ hyp_val = 0 for i in range(len(parameter_vector) - 1): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] @@ -30,6 +47,11 @@ def output(example_no, data_set): + """ + :param data_set: test data or train data + :param example_no: example whose output is to be fetched + :return: output for that example + """ if data_set == "train": return train_data[example_no][1] elif data_set == "test": @@ -38,6 +60,12 @@ def calculate_hypothesis_value(example_no, data_set): + """ + Calculates hypothesis value for a given example + :param data_set: test data or train_data + :param example_no: example whose hypothesis value is to be calculated + :return: hypothesis value for that example + """ if data_set == "train": return _hypothesis_value(train_data[example_no][0]) elif data_set == "test": @@ -46,6 +74,14 @@ def summation_of_cost_derivative(index, end=m): + """ + Calculates the sum of cost function derivative + :param index: index wrt derivative is being calculated + :param end: value where summation ends, default is m, number of examples + :return: Returns the summation of cost derivative + Note: If index is -1, this means we are calculating summation wrt to biased + parameter. + """ summation_value = 0 for i in range(end): if index == -1: @@ -56,6 +92,12 @@ def get_cost_derivative(index): + """ + :param index: index of the parameter vector wrt to derivative is to be calculated + :return: derivative wrt to that index + Note: If index is -1, this means we are calculating summation wrt to biased + parameter. + """ cost_derivative_value = summation_of_cost_derivative(index, m) / m return cost_derivative_value @@ -94,4 +136,4 @@ if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") - test_gradient_descent()+ test_gradient_descent()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/gradient_descent.py
Write docstrings for backend logic
import matplotlib.pyplot as plt import numpy as np def weight_matrix(point: np.ndarray, x_train: np.ndarray, tau: float) -> np.ndarray: m = len(x_train) # Number of training samples weights = np.eye(m) # Initialize weights as identity matrix for j in range(m): diff = point - x_train[j] weights[j, j] = np.exp(diff @ diff.T / (-2.0 * tau**2)) return weights def local_weight( point: np.ndarray, x_train: np.ndarray, y_train: np.ndarray, tau: float ) -> np.ndarray: weight_mat = weight_matrix(point, x_train, tau) weight = np.linalg.inv(x_train.T @ weight_mat @ x_train) @ ( x_train.T @ weight_mat @ y_train.T ) return weight def local_weight_regression( x_train: np.ndarray, y_train: np.ndarray, tau: float ) -> np.ndarray: y_pred = np.zeros(len(x_train)) # Initialize array of predictions for i, item in enumerate(x_train): y_pred[i] = np.dot(item, local_weight(item, x_train, y_train, tau)).item() return y_pred def load_data( dataset_name: str, x_name: str, y_name: str ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: import seaborn as sns data = sns.load_dataset(dataset_name) x_data = np.array(data[x_name]) y_data = np.array(data[y_name]) one = np.ones(len(y_data)) # pairing elements of one and x_data x_train = np.column_stack((one, x_data)) return x_train, x_data, y_data def plot_preds( x_train: np.ndarray, preds: np.ndarray, x_data: np.ndarray, y_data: np.ndarray, x_name: str, y_name: str, ) -> None: x_train_sorted = np.sort(x_train, axis=0) plt.scatter(x_data, y_data, color="blue") plt.plot( x_train_sorted[:, 1], preds[x_train[:, 1].argsort(0)], color="yellow", linewidth=5, ) plt.title("Local Weighted Regression") plt.xlabel(x_name) plt.ylabel(y_name) plt.show() if __name__ == "__main__": import doctest doctest.testmod() # Demo with a dataset from the seaborn module training_data_x, total_bill, tip = load_data("tips", "total_bill", "tip") predictions = local_weight_regression(training_data_x, tip, 5) plot_preds(training_data_x, predictions, total_bill, tip, "total_bill", "tip")
--- +++ @@ -1,9 +1,63 @@+""" +Locally weighted linear regression, also called local regression, is a type of +non-parametric linear regression that prioritizes data closest to a given +prediction point. The algorithm estimates the vector of model coefficients β +using weighted least squares regression: + +β = (XᵀWX)⁻¹(XᵀWy), + +where X is the design matrix, y is the response vector, and W is the diagonal +weight matrix. + +This implementation calculates wᵢ, the weight of the ith training sample, using +the Gaussian weight: + +wᵢ = exp(-‖xᵢ - x‖²/(2τ²)), + +where xᵢ is the ith training sample, x is the prediction point, τ is the +"bandwidth", and ‖x‖ is the Euclidean norm (also called the 2-norm or the L² +norm). The bandwidth τ controls how quickly the weight of a training sample +decreases as its distance from the prediction point increases. One can think of +the Gaussian weight as a bell curve centered around the prediction point: a +training sample is weighted lower if it's farther from the center, and τ +controls the spread of the bell curve. + +Other types of locally weighted regression such as locally estimated scatterplot +smoothing (LOESS) typically use different weight functions. + +References: + - https://en.wikipedia.org/wiki/Local_regression + - https://en.wikipedia.org/wiki/Weighted_least_squares + - https://cs229.stanford.edu/notes2022fall/main_notes.pdf +""" import matplotlib.pyplot as plt import numpy as np def weight_matrix(point: np.ndarray, x_train: np.ndarray, tau: float) -> np.ndarray: + """ + Calculate the weight of every point in the training data around a given + prediction point + + Args: + point: x-value at which the prediction is being made + x_train: ndarray of x-values for training + tau: bandwidth value, controls how quickly the weight of training values + decreases as the distance from the prediction point increases + + Returns: + m x m weight matrix around the prediction point, where m is the size of + the training set + >>> weight_matrix( + ... np.array([1., 1.]), + ... np.array([[16.99, 10.34], [21.01,23.68], [24.59,25.69]]), + ... 0.6 + ... ) + array([[1.43807972e-207, 0.00000000e+000, 0.00000000e+000], + [0.00000000e+000, 0.00000000e+000, 0.00000000e+000], + [0.00000000e+000, 0.00000000e+000, 0.00000000e+000]]) + """ m = len(x_train) # Number of training samples weights = np.eye(m) # Initialize weights as identity matrix for j in range(m): @@ -16,6 +70,27 @@ def local_weight( point: np.ndarray, x_train: np.ndarray, y_train: np.ndarray, tau: float ) -> np.ndarray: + """ + Calculate the local weights at a given prediction point using the weight + matrix for that point + + Args: + point: x-value at which the prediction is being made + x_train: ndarray of x-values for training + y_train: ndarray of y-values for training + tau: bandwidth value, controls how quickly the weight of training values + decreases as the distance from the prediction point increases + Returns: + ndarray of local weights + >>> local_weight( + ... np.array([1., 1.]), + ... np.array([[16.99, 10.34], [21.01,23.68], [24.59,25.69]]), + ... np.array([[1.01, 1.66, 3.5]]), + ... 0.6 + ... ) + array([[0.00873174], + [0.08272556]]) + """ weight_mat = weight_matrix(point, x_train, tau) weight = np.linalg.inv(x_train.T @ weight_mat @ x_train) @ ( x_train.T @ weight_mat @ y_train.T @@ -27,6 +102,24 @@ def local_weight_regression( x_train: np.ndarray, y_train: np.ndarray, tau: float ) -> np.ndarray: + """ + Calculate predictions for each point in the training data + + Args: + x_train: ndarray of x-values for training + y_train: ndarray of y-values for training + tau: bandwidth value, controls how quickly the weight of training values + decreases as the distance from the prediction point increases + + Returns: + ndarray of predictions + >>> local_weight_regression( + ... np.array([[16.99, 10.34], [21.01, 23.68], [24.59, 25.69]]), + ... np.array([[1.01, 1.66, 3.5]]), + ... 0.6 + ... ) + array([1.07173261, 1.65970737, 3.50160179]) + """ y_pred = np.zeros(len(x_train)) # Initialize array of predictions for i, item in enumerate(x_train): y_pred[i] = np.dot(item, local_weight(item, x_train, y_train, tau)).item() @@ -37,6 +130,10 @@ def load_data( dataset_name: str, x_name: str, y_name: str ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Load data from seaborn and split it into x and y points + >>> pass # No doctests, function is for demo purposes only + """ import seaborn as sns data = sns.load_dataset(dataset_name) @@ -59,6 +156,10 @@ x_name: str, y_name: str, ) -> None: + """ + Plot predictions and display the graph + >>> pass # No doctests, function is for demo purposes only + """ x_train_sorted = np.sort(x_train, axis=0) plt.scatter(x_data, y_data, color="blue") plt.plot( @@ -81,4 +182,4 @@ # Demo with a dataset from the seaborn module training_data_x, total_bill, tip = load_data("tips", "total_bill", "tip") predictions = local_weight_regression(training_data_x, tip, 5) - plot_preds(training_data_x, predictions, total_bill, tip, "total_bill", "tip")+ plot_preds(training_data_x, predictions, total_bill, tip, "total_bill", "tip")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/local_weighted_learning/local_weighted_learning.py
Add detailed docstrings explaining each function
import os import sys import urllib.request import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.datasets import make_blobs, make_circles from sklearn.preprocessing import StandardScaler CANCER_DATASET_URL = ( "https://archive.ics.uci.edu/ml/machine-learning-databases/" "breast-cancer-wisconsin/wdbc.data" ) class SmoSVM: def __init__( self, train, kernel_func, alpha_list=None, cost=0.4, b=0.0, tolerance=0.001, auto_norm=True, ): self._init = True self._auto_norm = auto_norm self._c = np.float64(cost) self._b = np.float64(b) self._tol = np.float64(tolerance) if tolerance > 0.0001 else np.float64(0.001) self.tags = train[:, 0] self.samples = self._norm(train[:, 1:]) if self._auto_norm else train[:, 1:] self.alphas = alpha_list if alpha_list is not None else np.zeros(train.shape[0]) self.Kernel = kernel_func self._eps = 0.001 self._all_samples = list(range(self.length)) self._K_matrix = self._calculate_k_matrix() self._error = np.zeros(self.length) self._unbound = [] self.choose_alpha = self._choose_alphas() # Calculate alphas using SMO algorithm def fit(self): k = self._k state = None while True: # 1: Find alpha1, alpha2 try: i1, i2 = self.choose_alpha.send(state) state = None except StopIteration: print("Optimization done!\nEvery sample satisfy the KKT condition!") break # 2: calculate new alpha2 and new alpha1 y1, y2 = self.tags[i1], self.tags[i2] a1, a2 = self.alphas[i1].copy(), self.alphas[i2].copy() e1, e2 = self._e(i1), self._e(i2) args = (i1, i2, a1, a2, e1, e2, y1, y2) a1_new, a2_new = self._get_new_alpha(*args) if not a1_new and not a2_new: state = False continue self.alphas[i1], self.alphas[i2] = a1_new, a2_new # 3: update threshold(b) b1_new = np.float64( -e1 - y1 * k(i1, i1) * (a1_new - a1) - y2 * k(i2, i1) * (a2_new - a2) + self._b ) b2_new = np.float64( -e2 - y2 * k(i2, i2) * (a2_new - a2) - y1 * k(i1, i2) * (a1_new - a1) + self._b ) if 0.0 < a1_new < self._c: b = b1_new if 0.0 < a2_new < self._c: b = b2_new if not (np.float64(0) < a2_new < self._c) and not ( np.float64(0) < a1_new < self._c ): b = (b1_new + b2_new) / 2.0 b_old = self._b self._b = b # 4: update error, here we only calculate the error for non-bound samples self._unbound = [i for i in self._all_samples if self._is_unbound(i)] for s in self.unbound: if s in (i1, i2): continue self._error[s] += ( y1 * (a1_new - a1) * k(i1, s) + y2 * (a2_new - a2) * k(i2, s) + (self._b - b_old) ) # if i1 or i2 is non-bound, update their error value to zero if self._is_unbound(i1): self._error[i1] = 0 if self._is_unbound(i2): self._error[i2] = 0 # Predict test samples def predict(self, test_samples, classify=True): if test_samples.shape[1] > self.samples.shape[1]: raise ValueError( "Test samples' feature length does not equal to that of train samples" ) if self._auto_norm: test_samples = self._norm(test_samples) results = [] for test_sample in test_samples: result = self._predict(test_sample) if classify: results.append(1 if result > 0 else -1) else: results.append(result) return np.array(results) # Check if alpha violates the KKT condition def _check_obey_kkt(self, index): alphas = self.alphas tol = self._tol r = self._e(index) * self.tags[index] c = self._c return (r < -tol and alphas[index] < c) or (r > tol and alphas[index] > 0.0) # Get value calculated from kernel function def _k(self, i1, i2): # for test samples, use kernel function if isinstance(i2, np.ndarray): return self.Kernel(self.samples[i1], i2) # for training samples, kernel values have been saved in matrix else: return self._K_matrix[i1, i2] # Get error for sample def _e(self, index): # get from error data if self._is_unbound(index): return self._error[index] # get by g(xi) - yi else: gx = np.dot(self.alphas * self.tags, self._K_matrix[:, index]) + self._b yi = self.tags[index] return gx - yi # Calculate kernel matrix of all possible i1, i2, saving time def _calculate_k_matrix(self): k_matrix = np.zeros([self.length, self.length]) for i in self._all_samples: for j in self._all_samples: k_matrix[i, j] = np.float64( self.Kernel(self.samples[i, :], self.samples[j, :]) ) return k_matrix # Predict tag for test sample def _predict(self, sample): k = self._k predicted_value = ( np.sum( [ self.alphas[i1] * self.tags[i1] * k(i1, sample) for i1 in self._all_samples ] ) + self._b ) return predicted_value # Choose alpha1 and alpha2 def _choose_alphas(self): loci = yield from self._choose_a1() if not loci: return None return loci def _choose_a1(self): while True: all_not_obey = True # all sample print("Scanning all samples!") for i1 in [i for i in self._all_samples if self._check_obey_kkt(i)]: all_not_obey = False yield from self._choose_a2(i1) # non-bound sample print("Scanning non-bound samples!") while True: not_obey = True for i1 in [ i for i in self._all_samples if self._check_obey_kkt(i) and self._is_unbound(i) ]: not_obey = False yield from self._choose_a2(i1) if not_obey: print("All non-bound samples satisfy the KKT condition!") break if all_not_obey: print("All samples satisfy the KKT condition!") break return False def _choose_a2(self, i1): self._unbound = [i for i in self._all_samples if self._is_unbound(i)] if len(self.unbound) > 0: tmp_error = self._error.copy().tolist() tmp_error_dict = { index: value for index, value in enumerate(tmp_error) if self._is_unbound(index) } if self._e(i1) >= 0: i2 = min(tmp_error_dict, key=lambda index: tmp_error_dict[index]) else: i2 = max(tmp_error_dict, key=lambda index: tmp_error_dict[index]) cmd = yield i1, i2 if cmd is None: return rng = np.random.default_rng() for i2 in np.roll(self.unbound, rng.choice(self.length)): cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self._all_samples, rng.choice(self.length)): cmd = yield i1, i2 if cmd is None: return # Get the new alpha2 and new alpha1 def _get_new_alpha(self, i1, i2, a1, a2, e1, e2, y1, y2): k = self._k if i1 == i2: return None, None # calculate L and H which bound the new alpha2 s = y1 * y2 if s == -1: l, h = max(0.0, a2 - a1), min(self._c, self._c + a2 - a1) # noqa: E741 else: l, h = max(0.0, a2 + a1 - self._c), min(self._c, a2 + a1) # noqa: E741 if l == h: return None, None # calculate eta k11 = k(i1, i1) k22 = k(i2, i2) k12 = k(i1, i2) # select the new alpha2 which could achieve the minimal objectives if (eta := k11 + k22 - 2.0 * k12) > 0.0: a2_new_unc = a2 + (y2 * (e1 - e2)) / eta # a2_new has a boundary if a2_new_unc >= h: a2_new = h elif a2_new_unc <= l: a2_new = l else: a2_new = a2_new_unc else: b = self._b l1 = a1 + s * (a2 - l) h1 = a1 + s * (a2 - h) # Method 1 f1 = y1 * (e1 + b) - a1 * k(i1, i1) - s * a2 * k(i1, i2) f2 = y2 * (e2 + b) - a2 * k(i2, i2) - s * a1 * k(i1, i2) ol = ( l1 * f1 + l * f2 + 1 / 2 * l1**2 * k(i1, i1) + 1 / 2 * l**2 * k(i2, i2) + s * l * l1 * k(i1, i2) ) oh = ( h1 * f1 + h * f2 + 1 / 2 * h1**2 * k(i1, i1) + 1 / 2 * h**2 * k(i2, i2) + s * h * h1 * k(i1, i2) ) """ Method 2: Use objective function to check which alpha2_new could achieve the minimal objectives """ if ol < (oh - self._eps): a2_new = l elif ol > oh + self._eps: a2_new = h else: a2_new = a2 # a1_new has a boundary too a1_new = a1 + s * (a2 - a2_new) if a1_new < 0: a2_new += s * a1_new a1_new = 0 if a1_new > self._c: a2_new += s * (a1_new - self._c) a1_new = self._c return a1_new, a2_new # Normalize data using min-max method def _norm(self, data): if self._init: self._min = np.min(data, axis=0) self._max = np.max(data, axis=0) self._init = False return (data - self._min) / (self._max - self._min) else: return (data - self._min) / (self._max - self._min) def _is_unbound(self, index): return bool(0.0 < self.alphas[index] < self._c) def _is_support(self, index): return bool(self.alphas[index] > 0) @property def unbound(self): return self._unbound @property def support(self): return [i for i in range(self.length) if self._is_support(i)] @property def length(self): return self.samples.shape[0] class Kernel: def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0): self.degree = np.float64(degree) self.coef0 = np.float64(coef0) self.gamma = np.float64(gamma) self._kernel_name = kernel self._kernel = self._get_kernel(kernel_name=kernel) self._check() def _polynomial(self, v1, v2): return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree def _linear(self, v1, v2): return np.inner(v1, v2) + self.coef0 def _rbf(self, v1, v2): return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2)) def _check(self): if self._kernel == self._rbf and self.gamma < 0: raise ValueError("gamma value must be non-negative") def _get_kernel(self, kernel_name): maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf} return maps[kernel_name] def __call__(self, v1, v2): return self._kernel(v1, v2) def __repr__(self): return self._kernel_name def count_time(func): def call_func(*args, **kwargs): import time start_time = time.time() func(*args, **kwargs) end_time = time.time() print(f"SMO algorithm cost {end_time - start_time} seconds") return call_func @count_time def test_cancer_data(): print("Hello!\nStart test SVM using the SMO algorithm!") # 0: download dataset and load into pandas' dataframe if not os.path.exists(r"cancer_data.csv"): request = urllib.request.Request( # noqa: S310 CANCER_DATASET_URL, headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}, ) response = urllib.request.urlopen(request) # noqa: S310 content = response.read().decode("utf-8") with open(r"cancer_data.csv", "w") as f: f.write(content) data = pd.read_csv( "cancer_data.csv", header=None, dtype={0: str}, # Assuming the first column contains string data ) # 1: pre-processing data del data[data.columns.tolist()[0]] data = data.dropna(axis=0) data = data.replace({"M": np.float64(1), "B": np.float64(-1)}) samples = np.array(data)[:, :] # 2: dividing data into train_data data and test_data data train_data, test_data = samples[:328, :], samples[328:, :] test_tags, test_samples = test_data[:, 0], test_data[:, 1:] # 3: choose kernel function, and set initial alphas to zero (optional) my_kernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) al = np.zeros(train_data.shape[0]) # 4: calculating best alphas using SMO algorithm and predict test_data samples mysvm = SmoSVM( train=train_data, kernel_func=my_kernel, alpha_list=al, cost=0.4, b=0.0, tolerance=0.001, ) mysvm.fit() predict = mysvm.predict(test_samples) # 5: check accuracy score = 0 test_num = test_tags.shape[0] for i in range(test_tags.shape[0]): if test_tags[i] == predict[i]: score += 1 print(f"\nAll: {test_num}\nCorrect: {score}\nIncorrect: {test_num - score}") print(f"Rough Accuracy: {score / test_tags.shape[0]}") def test_demonstration(): # change stdout print("\nStarting plot, please wait!") sys.stdout = open(os.devnull, "w") ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) ax4 = plt.subplot2grid((2, 2), (1, 1)) ax1.set_title("Linear SVM, cost = 0.1") test_linear_kernel(ax1, cost=0.1) ax2.set_title("Linear SVM, cost = 500") test_linear_kernel(ax2, cost=500) ax3.set_title("RBF kernel SVM, cost = 0.1") test_rbf_kernel(ax3, cost=0.1) ax4.set_title("RBF kernel SVM, cost = 500") test_rbf_kernel(ax4, cost=500) sys.stdout = sys.__stdout__ print("Plot done!") def test_linear_kernel(ax, cost): train_x, train_y = make_blobs( n_samples=500, centers=2, n_features=2, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) my_kernel = Kernel(kernel="linear", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=my_kernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def test_rbf_kernel(ax, cost): train_x, train_y = make_circles( n_samples=500, noise=0.1, factor=0.1, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) my_kernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=my_kernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def plot_partition_boundary( model, train_data, ax, resolution=100, colors=("b", "k", "r") ): train_data_x = train_data[:, 1] train_data_y = train_data[:, 2] train_data_tags = train_data[:, 0] xrange = np.linspace(train_data_x.min(), train_data_x.max(), resolution) yrange = np.linspace(train_data_y.min(), train_data_y.max(), resolution) test_samples = np.array([(x, y) for x in xrange for y in yrange]).reshape( resolution * resolution, 2 ) test_tags = model.predict(test_samples, classify=False) grid = test_tags.reshape((len(xrange), len(yrange))) # Plot contour map which represents the partition boundary ax.contour( xrange, yrange, np.asmatrix(grid).T, levels=(-1, 0, 1), linestyles=("--", "-", "--"), linewidths=(1, 1, 1), colors=colors, ) # Plot all train samples ax.scatter( train_data_x, train_data_y, c=train_data_tags, cmap=plt.cm.Dark2, lw=0, alpha=0.5, ) # Plot support vectors support = model.support ax.scatter( train_data_x[support], train_data_y[support], c=train_data_tags[support], cmap=plt.cm.Dark2, ) if __name__ == "__main__": test_cancer_data() test_demonstration() plt.show()
--- +++ @@ -1,3 +1,32 @@+""" +Sequential minimal optimization (SMO) for support vector machines (SVM) + +Sequential minimal optimization (SMO) is an algorithm for solving the quadratic +programming (QP) problem that arises during the training of SVMs. It was invented by +John Platt in 1998. + +Input: + 0: type: numpy.ndarray. + 1: first column of ndarray must be tags of samples, must be 1 or -1. + 2: rows of ndarray represent samples. + +Usage: + Command: + python3 sequential_minimum_optimization.py + Code: + from sequential_minimum_optimization import SmoSVM, Kernel + + kernel = Kernel(kernel='poly', degree=3., coef0=1., gamma=0.5) + init_alphas = np.zeros(train.shape[0]) + SVM = SmoSVM(train=train, alpha_list=init_alphas, kernel_func=kernel, cost=0.4, + b=0.0, tolerance=0.001) + SVM.fit() + predict = SVM.predict(test_samples) + +Reference: + https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/smo-book.pdf + https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-98-14.pdf +""" import os import sys @@ -149,6 +178,11 @@ # Get error for sample def _e(self, index): + """ + Two cases: + 1: Sample[index] is non-bound, fetch error from list: _error + 2: sample[index] is bound, use predicted value minus true value: g(xi) - yi + """ # get from error data if self._is_unbound(index): return self._error[index] @@ -190,6 +224,15 @@ return loci def _choose_a1(self): + """ + Choose first alpha + Steps: + 1: First loop over all samples + 2: Second loop over all non-bound samples until no non-bound samples violate + the KKT condition. + 3: Repeat these two processes until no samples violate the KKT condition + after the first loop. + """ while True: all_not_obey = True # all sample @@ -218,6 +261,15 @@ return False def _choose_a2(self, i1): + """ + Choose the second alpha using a heuristic algorithm + Steps: + 1: Choose alpha2 that maximizes the step size (|E1 - E2|). + 2: Start in a random point, loop over all non-bound samples till alpha1 and + alpha2 are optimized. + 3: Start in a random point, loop over all samples till alpha1 and alpha2 are + optimized. + """ self._unbound = [i for i in self._all_samples if self._is_unbound(i)] if len(self.unbound) > 0: @@ -515,6 +567,13 @@ def plot_partition_boundary( model, train_data, ax, resolution=100, colors=("b", "k", "r") ): + """ + We cannot get the optimal w of our kernel SVM model, which is different from a + linear SVM. For this reason, we generate randomly distributed points with high + density, and predicted values of these points are calculated using our trained + model. Then we could use this predicted values to draw contour map, and this contour + map represents the SVM's partition boundary. + """ train_data_x = train_data[:, 1] train_data_y = train_data[:, 2] train_data_tags = train_data[:, 0] @@ -560,4 +619,4 @@ if __name__ == "__main__": test_cancer_data() test_demonstration() - plt.show()+ plt.show()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/sequential_minimum_optimization.py
Improve my code by adding docstrings
def binary_multiply(a: int, b: int) -> int: res = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def binary_mod_multiply(a: int, b: int, modulus: int) -> int: res = 0 while b > 0: if b & 1: res = ((res % modulus) + (a % modulus)) % modulus a += a b >>= 1 return res if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,52 @@+""" +Binary Multiplication +This is a method to find a*b in a time complexity of O(log b) +This is one of the most commonly used methods of finding result of multiplication. +Also useful in cases where solution to (a*b)%c is required, +where a,b,c can be numbers over the computers calculation limits. +Done using iteration, can also be done using recursion + +Let's say you need to calculate a * b +RULE 1 : a * b = (a+a) * (b/2) ---- example : 4 * 4 = (4+4) * (4/2) = 8 * 2 +RULE 2 : IF b is odd, then ---- a * b = a + (a * (b - 1)), where (b - 1) is even. +Once b is even, repeat the process to get a * b +Repeat the process until b = 1 or b = 0, because a*1 = a and a*0 = 0 + +As far as the modulo is concerned, +the fact : (a+b) % c = ((a%c) + (b%c)) % c +Now apply RULE 1 or 2, whichever is required. + +@author chinmoy159 +""" def binary_multiply(a: int, b: int) -> int: + """ + Multiply 'a' and 'b' using bitwise multiplication. + + Parameters: + a (int): The first number. + b (int): The second number. + + Returns: + int: a * b + + Examples: + >>> binary_multiply(2, 3) + 6 + >>> binary_multiply(5, 0) + 0 + >>> binary_multiply(3, 4) + 12 + >>> binary_multiply(10, 5) + 50 + >>> binary_multiply(0, 5) + 0 + >>> binary_multiply(2, 1) + 2 + >>> binary_multiply(1, 10) + 10 + """ res = 0 while b > 0: if b & 1: @@ -13,6 +59,31 @@ def binary_mod_multiply(a: int, b: int, modulus: int) -> int: + """ + Calculate (a * b) % c using binary multiplication and modular arithmetic. + + Parameters: + a (int): The first number. + b (int): The second number. + modulus (int): The modulus. + + Returns: + int: (a * b) % modulus. + + Examples: + >>> binary_mod_multiply(2, 3, 5) + 1 + >>> binary_mod_multiply(5, 0, 7) + 0 + >>> binary_mod_multiply(3, 4, 6) + 0 + >>> binary_mod_multiply(10, 5, 13) + 11 + >>> binary_mod_multiply(2, 1, 5) + 2 + >>> binary_mod_multiply(1, 10, 3) + 1 + """ res = 0 while b > 0: if b & 1: @@ -27,4 +98,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/binary_multiplication.py
Turn comments into proper docstrings
import numpy as np def binary_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") y_pred = np.clip(y_pred, epsilon, 1 - epsilon) # Clip predictions to avoid log(0) bce_loss = -(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred)) return np.mean(bce_loss) def binary_focal_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, gamma: float = 2.0, alpha: float = 0.25, epsilon: float = 1e-15, ) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") # Clip predicted probabilities to avoid log(0) y_pred = np.clip(y_pred, epsilon, 1 - epsilon) bcfe_loss = -( alpha * (1 - y_pred) ** gamma * y_true * np.log(y_pred) + (1 - alpha) * y_pred**gamma * (1 - y_true) * np.log(1 - y_pred) ) return np.mean(bcfe_loss) def categorical_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: if y_true.shape != y_pred.shape: raise ValueError("Input arrays must have the same shape.") if np.any((y_true != 0) & (y_true != 1)) or np.any(y_true.sum(axis=1) != 1): raise ValueError("y_true must be one-hot encoded.") if not np.all(np.isclose(np.sum(y_pred, axis=1), 1, rtol=epsilon, atol=epsilon)): raise ValueError("Predicted probabilities must sum to approximately 1.") y_pred = np.clip(y_pred, epsilon, 1) # Clip predictions to avoid log(0) return -np.sum(y_true * np.log(y_pred)) def categorical_focal_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, alpha: np.ndarray = None, gamma: float = 2.0, epsilon: float = 1e-15, ) -> float: if y_true.shape != y_pred.shape: raise ValueError("Shape of y_true and y_pred must be the same.") if alpha is None: alpha = np.ones(y_true.shape[1]) if np.any((y_true != 0) & (y_true != 1)) or np.any(y_true.sum(axis=1) != 1): raise ValueError("y_true must be one-hot encoded.") if len(alpha) != y_true.shape[1]: raise ValueError("Length of alpha must match the number of classes.") if not np.all(np.isclose(np.sum(y_pred, axis=1), 1, rtol=epsilon, atol=epsilon)): raise ValueError("Predicted probabilities must sum to approximately 1.") # Clip predicted probabilities to avoid log(0) y_pred = np.clip(y_pred, epsilon, 1 - epsilon) # Calculate loss for each class and sum across classes cfce_loss = -np.sum( alpha * np.power(1 - y_pred, gamma) * y_true * np.log(y_pred), axis=1 ) return np.mean(cfce_loss) def hinge_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float: if len(y_true) != len(y_pred): raise ValueError("Length of predicted and actual array must be same.") if np.any((y_true != -1) & (y_true != 1)): raise ValueError("y_true can have values -1 or 1 only.") hinge_losses = np.maximum(0, 1.0 - (y_true * y_pred)) return np.mean(hinge_losses) def huber_loss(y_true: np.ndarray, y_pred: np.ndarray, delta: float) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") huber_mse = 0.5 * (y_true - y_pred) ** 2 huber_mae = delta * (np.abs(y_true - y_pred) - 0.5 * delta) return np.where(np.abs(y_true - y_pred) <= delta, huber_mse, huber_mae).mean() def mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") squared_errors = (y_true - y_pred) ** 2 return np.mean(squared_errors) def mean_absolute_error(y_true: np.ndarray, y_pred: np.ndarray) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") return np.mean(abs(y_true - y_pred)) def mean_squared_logarithmic_error(y_true: np.ndarray, y_pred: np.ndarray) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") squared_logarithmic_errors = (np.log1p(y_true) - np.log1p(y_pred)) ** 2 return np.mean(squared_logarithmic_errors) def mean_absolute_percentage_error( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: if len(y_true) != len(y_pred): raise ValueError("The length of the two arrays should be the same.") y_true = np.where(y_true == 0, epsilon, y_true) absolute_percentage_diff = np.abs((y_true - y_pred) / y_true) return np.mean(absolute_percentage_diff) def perplexity_loss( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-7 ) -> float: vocab_size = y_pred.shape[2] if y_true.shape[0] != y_pred.shape[0]: raise ValueError("Batch size of y_true and y_pred must be equal.") if y_true.shape[1] != y_pred.shape[1]: raise ValueError("Sentence length of y_true and y_pred must be equal.") if np.max(y_true) > vocab_size: raise ValueError("Label value must not be greater than vocabulary size.") # Matrix to select prediction value only for true class filter_matrix = np.array( [[list(np.eye(vocab_size)[word]) for word in sentence] for sentence in y_true] ) # Getting the matrix containing prediction for only true class true_class_pred = np.sum(y_pred * filter_matrix, axis=2).clip(epsilon, 1) # Calculating perplexity for each sentence perp_losses = np.exp(np.negative(np.mean(np.log(true_class_pred), axis=1))) return np.mean(perp_losses) def smooth_l1_loss(y_true: np.ndarray, y_pred: np.ndarray, beta: float = 1.0) -> float: if len(y_true) != len(y_pred): raise ValueError("The length of the two arrays should be the same.") diff = np.abs(y_true - y_pred) loss = np.where(diff < beta, 0.5 * diff**2 / beta, diff - 0.5 * beta) return np.mean(loss) def kullback_leibler_divergence(y_true: np.ndarray, y_pred: np.ndarray) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") kl_loss = y_true * np.log(y_true / y_pred) return np.sum(kl_loss) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -4,6 +4,33 @@ def binary_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: + """ + Calculate the mean binary cross-entropy (BCE) loss between true labels and predicted + probabilities. + + BCE loss quantifies dissimilarity between true labels (0 or 1) and predicted + probabilities. It's widely used in binary classification tasks. + + BCE = -Σ(y_true * ln(y_pred) + (1 - y_true) * ln(1 - y_pred)) + + Reference: https://en.wikipedia.org/wiki/Cross_entropy + + Parameters: + - y_true: True binary labels (0 or 1) + - y_pred: Predicted probabilities for class 1 + - epsilon: Small constant to avoid numerical instability + + >>> true_labels = np.array([0, 1, 1, 0, 1]) + >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8]) + >>> float(binary_cross_entropy(true_labels, predicted_probs)) + 0.2529995012327421 + >>> true_labels = np.array([0, 1, 1, 0, 1]) + >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2]) + >>> binary_cross_entropy(true_labels, predicted_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same length. + """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") @@ -19,6 +46,37 @@ alpha: float = 0.25, epsilon: float = 1e-15, ) -> float: + """ + Calculate the mean binary focal cross-entropy (BFCE) loss between true labels + and predicted probabilities. + + BFCE loss quantifies dissimilarity between true labels (0 or 1) and predicted + probabilities. It's a variation of binary cross-entropy that addresses class + imbalance by focusing on hard examples. + + BCFE = -Σ(alpha * (1 - y_pred)**gamma * y_true * log(y_pred) + + (1 - alpha) * y_pred**gamma * (1 - y_true) * log(1 - y_pred)) + + Reference: [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf) + + Parameters: + - y_true: True binary labels (0 or 1). + - y_pred: Predicted probabilities for class 1. + - gamma: Focusing parameter for modulating the loss (default: 2.0). + - alpha: Weighting factor for class 1 (default: 0.25). + - epsilon: Small constant to avoid numerical instability. + + >>> true_labels = np.array([0, 1, 1, 0, 1]) + >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8]) + >>> float(binary_focal_cross_entropy(true_labels, predicted_probs)) + 0.008257977659239775 + >>> true_labels = np.array([0, 1, 1, 0, 1]) + >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2]) + >>> binary_focal_cross_entropy(true_labels, predicted_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same length. + """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") # Clip predicted probabilities to avoid log(0) @@ -35,6 +93,48 @@ def categorical_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: + """ + Calculate categorical cross-entropy (CCE) loss between true class labels and + predicted class probabilities. + + CCE = -Σ(y_true * ln(y_pred)) + + Reference: https://en.wikipedia.org/wiki/Cross_entropy + + Parameters: + - y_true: True class labels (one-hot encoded) + - y_pred: Predicted class probabilities + - epsilon: Small constant to avoid numerical instability + + >>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]]) + >>> float(categorical_cross_entropy(true_labels, pred_probs)) + 0.567395975254385 + >>> true_labels = np.array([[1, 0], [0, 1]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) + >>> categorical_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same shape. + >>> true_labels = np.array([[2, 0, 1], [1, 0, 0]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) + >>> categorical_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: y_true must be one-hot encoded. + >>> true_labels = np.array([[1, 0, 1], [1, 0, 0]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) + >>> categorical_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: y_true must be one-hot encoded. + >>> true_labels = np.array([[1, 0, 0], [0, 1, 0]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.1], [0.2, 0.7, 0.1]]) + >>> categorical_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: Predicted probabilities must sum to approximately 1. + """ if y_true.shape != y_pred.shape: raise ValueError("Input arrays must have the same shape.") @@ -55,6 +155,75 @@ gamma: float = 2.0, epsilon: float = 1e-15, ) -> float: + """ + Calculate the mean categorical focal cross-entropy (CFCE) loss between true + labels and predicted probabilities for multi-class classification. + + CFCE loss is a generalization of binary focal cross-entropy for multi-class + classification. It addresses class imbalance by focusing on hard examples. + + CFCE = -Σ alpha * (1 - y_pred)**gamma * y_true * log(y_pred) + + Reference: [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf) + + Parameters: + - y_true: True labels in one-hot encoded form. + - y_pred: Predicted probabilities for each class. + - alpha: Array of weighting factors for each class. + - gamma: Focusing parameter for modulating the loss (default: 2.0). + - epsilon: Small constant to avoid numerical instability. + + Returns: + - The mean categorical focal cross-entropy loss. + + >>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]]) + >>> alpha = np.array([0.6, 0.2, 0.7]) + >>> float(categorical_focal_cross_entropy(true_labels, pred_probs, alpha)) + 0.0025966118981496423 + + >>> true_labels = np.array([[0, 1, 0], [0, 0, 1]]) + >>> pred_probs = np.array([[0.05, 0.95, 0], [0.1, 0.8, 0.1]]) + >>> alpha = np.array([0.25, 0.25, 0.25]) + >>> float(categorical_focal_cross_entropy(true_labels, pred_probs, alpha)) + 0.23315276982014324 + + >>> true_labels = np.array([[1, 0], [0, 1]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) + >>> categorical_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same shape. + + >>> true_labels = np.array([[2, 0, 1], [1, 0, 0]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) + >>> categorical_focal_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: y_true must be one-hot encoded. + + >>> true_labels = np.array([[1, 0, 1], [1, 0, 0]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) + >>> categorical_focal_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: y_true must be one-hot encoded. + + >>> true_labels = np.array([[1, 0, 0], [0, 1, 0]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.1], [0.2, 0.7, 0.1]]) + >>> categorical_focal_cross_entropy(true_labels, pred_probs) + Traceback (most recent call last): + ... + ValueError: Predicted probabilities must sum to approximately 1. + + >>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]]) + >>> alpha = np.array([0.6, 0.2]) + >>> categorical_focal_cross_entropy(true_labels, pred_probs, alpha) + Traceback (most recent call last): + ... + ValueError: Length of alpha must match the number of classes. + """ if y_true.shape != y_pred.shape: raise ValueError("Shape of y_true and y_pred must be the same.") @@ -82,6 +251,35 @@ def hinge_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """ + Calculate the mean hinge loss for between true labels and predicted probabilities + for training support vector machines (SVMs). + + Hinge loss = max(0, 1 - true * pred) + + Reference: https://en.wikipedia.org/wiki/Hinge_loss + + Args: + - y_true: actual values (ground truth) encoded as -1 or 1 + - y_pred: predicted values + + >>> true_labels = np.array([-1, 1, 1, -1, 1]) + >>> pred = np.array([-4, -0.3, 0.7, 5, 10]) + >>> float(hinge_loss(true_labels, pred)) + 1.52 + >>> true_labels = np.array([-1, 1, 1, -1, 1, 1]) + >>> pred = np.array([-4, -0.3, 0.7, 5, 10]) + >>> hinge_loss(true_labels, pred) + Traceback (most recent call last): + ... + ValueError: Length of predicted and actual array must be same. + >>> true_labels = np.array([-1, 1, 10, -1, 1]) + >>> pred = np.array([-4, -0.3, 0.7, 5, 10]) + >>> hinge_loss(true_labels, pred) + Traceback (most recent call last): + ... + ValueError: y_true can have values -1 or 1 only. + """ if len(y_true) != len(y_pred): raise ValueError("Length of predicted and actual array must be same.") @@ -93,6 +291,37 @@ def huber_loss(y_true: np.ndarray, y_pred: np.ndarray, delta: float) -> float: + """ + Calculate the mean Huber loss between the given ground truth and predicted values. + + The Huber loss describes the penalty incurred by an estimation procedure, and it + serves as a measure of accuracy for regression models. + + Huber loss = + 0.5 * (y_true - y_pred)^2 if |y_true - y_pred| <= delta + delta * |y_true - y_pred| - 0.5 * delta^2 otherwise + + Reference: https://en.wikipedia.org/wiki/Huber_loss + + Parameters: + - y_true: The true values (ground truth) + - y_pred: The predicted values + + >>> true_values = np.array([0.9, 10.0, 2.0, 1.0, 5.2]) + >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2]) + >>> bool(np.isclose(huber_loss(true_values, predicted_values, 1.0), 2.102)) + True + >>> true_labels = np.array([11.0, 21.0, 3.32, 4.0, 5.0]) + >>> predicted_probs = np.array([8.3, 20.8, 2.9, 11.2, 5.0]) + >>> bool(np.isclose(huber_loss(true_labels, predicted_probs, 1.0), 1.80164)) + True + >>> true_labels = np.array([11.0, 21.0, 3.32, 4.0]) + >>> predicted_probs = np.array([8.3, 20.8, 2.9, 11.2, 5.0]) + >>> huber_loss(true_labels, predicted_probs, 1.0) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same length. + """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") @@ -102,6 +331,31 @@ def mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """ + Calculate the mean squared error (MSE) between ground truth and predicted values. + + MSE measures the squared difference between true values and predicted values, and it + serves as a measure of accuracy for regression models. + + MSE = (1/n) * Σ(y_true - y_pred)^2 + + Reference: https://en.wikipedia.org/wiki/Mean_squared_error + + Parameters: + - y_true: The true values (ground truth) + - y_pred: The predicted values + + >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2]) + >>> bool(np.isclose(mean_squared_error(true_values, predicted_values), 0.028)) + True + >>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2]) + >>> mean_squared_error(true_labels, predicted_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same length. + """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") @@ -110,6 +364,36 @@ def mean_absolute_error(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """ + Calculates the Mean Absolute Error (MAE) between ground truth (observed) + and predicted values. + + MAE measures the absolute difference between true values and predicted values. + + Equation: + MAE = (1/n) * Σ(abs(y_true - y_pred)) + + Reference: https://en.wikipedia.org/wiki/Mean_absolute_error + + Parameters: + - y_true: The true values (ground truth) + - y_pred: The predicted values + + >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2]) + >>> bool(np.isclose(mean_absolute_error(true_values, predicted_values), 0.16)) + True + >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2]) + >>> bool(np.isclose(mean_absolute_error(true_values, predicted_values), 2.16)) + False + >>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + >>> predicted_probs = np.array([0.3, 0.8, 0.9, 5.2]) + >>> mean_absolute_error(true_labels, predicted_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same length. + """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") @@ -117,6 +401,34 @@ def mean_squared_logarithmic_error(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """ + Calculate the mean squared logarithmic error (MSLE) between ground truth and + predicted values. + + MSLE measures the squared logarithmic difference between true values and predicted + values for regression models. It's particularly useful for dealing with skewed or + large-value data, and it's often used when the relative differences between + predicted and true values are more important than absolute differences. + + MSLE = (1/n) * Σ(log(1 + y_true) - log(1 + y_pred))^2 + + Reference: https://insideaiml.com/blog/MeanSquared-Logarithmic-Error-Loss-1035 + + Parameters: + - y_true: The true values (ground truth) + - y_pred: The predicted values + + >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2]) + >>> float(mean_squared_logarithmic_error(true_values, predicted_values)) + 0.0030860877925181344 + >>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2]) + >>> mean_squared_logarithmic_error(true_labels, predicted_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same length. + """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") @@ -127,6 +439,39 @@ def mean_absolute_percentage_error( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: + """ + Calculate the Mean Absolute Percentage Error between y_true and y_pred. + + Mean Absolute Percentage Error calculates the average of the absolute + percentage differences between the predicted and true values. + + Formula = (Σ|y_true[i]-Y_pred[i]/y_true[i]|)/n + + Source: https://stephenallwright.com/good-mape-score/ + + Parameters: + y_true (np.ndarray): Numpy array containing true/target values. + y_pred (np.ndarray): Numpy array containing predicted values. + + Returns: + float: The Mean Absolute Percentage error between y_true and y_pred. + + Examples: + >>> y_true = np.array([10, 20, 30, 40]) + >>> y_pred = np.array([12, 18, 33, 45]) + >>> float(mean_absolute_percentage_error(y_true, y_pred)) + 0.13125 + + >>> y_true = np.array([1, 2, 3, 4]) + >>> y_pred = np.array([2, 3, 4, 5]) + >>> float(mean_absolute_percentage_error(y_true, y_pred)) + 0.5208333333333333 + + >>> y_true = np.array([34, 37, 44, 47, 48, 48, 46, 43, 32, 27, 26, 24]) + >>> y_pred = np.array([37, 40, 46, 44, 46, 50, 45, 44, 34, 30, 22, 23]) + >>> float(mean_absolute_percentage_error(y_true, y_pred)) + 0.064671076436071 + """ if len(y_true) != len(y_pred): raise ValueError("The length of the two arrays should be the same.") @@ -139,6 +484,71 @@ def perplexity_loss( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-7 ) -> float: + """ + Calculate the perplexity for the y_true and y_pred. + + Compute the Perplexity which useful in predicting language model + accuracy in Natural Language Processing (NLP.) + Perplexity is measure of how certain the model in its predictions. + + Perplexity Loss = exp(-1/N (Σ ln(p(x))) + + Reference: + https://en.wikipedia.org/wiki/Perplexity + + Args: + y_true: Actual label encoded sentences of shape (batch_size, sentence_length) + y_pred: Predicted sentences of shape (batch_size, sentence_length, vocab_size) + epsilon: Small floating point number to avoid getting inf for log(0) + + Returns: + Perplexity loss between y_true and y_pred. + + >>> y_true = np.array([[1, 4], [2, 3]]) + >>> y_pred = np.array( + ... [[[0.28, 0.19, 0.21 , 0.15, 0.15], + ... [0.24, 0.19, 0.09, 0.18, 0.27]], + ... [[0.03, 0.26, 0.21, 0.18, 0.30], + ... [0.28, 0.10, 0.33, 0.15, 0.12]]] + ... ) + >>> float(perplexity_loss(y_true, y_pred)) + 5.0247347775367945 + >>> y_true = np.array([[1, 4], [2, 3]]) + >>> y_pred = np.array( + ... [[[0.28, 0.19, 0.21 , 0.15, 0.15], + ... [0.24, 0.19, 0.09, 0.18, 0.27], + ... [0.30, 0.10, 0.20, 0.15, 0.25]], + ... [[0.03, 0.26, 0.21, 0.18, 0.30], + ... [0.28, 0.10, 0.33, 0.15, 0.12], + ... [0.30, 0.10, 0.20, 0.15, 0.25]],] + ... ) + >>> perplexity_loss(y_true, y_pred) + Traceback (most recent call last): + ... + ValueError: Sentence length of y_true and y_pred must be equal. + >>> y_true = np.array([[1, 4], [2, 11]]) + >>> y_pred = np.array( + ... [[[0.28, 0.19, 0.21 , 0.15, 0.15], + ... [0.24, 0.19, 0.09, 0.18, 0.27]], + ... [[0.03, 0.26, 0.21, 0.18, 0.30], + ... [0.28, 0.10, 0.33, 0.15, 0.12]]] + ... ) + >>> perplexity_loss(y_true, y_pred) + Traceback (most recent call last): + ... + ValueError: Label value must not be greater than vocabulary size. + >>> y_true = np.array([[1, 4]]) + >>> y_pred = np.array( + ... [[[0.28, 0.19, 0.21 , 0.15, 0.15], + ... [0.24, 0.19, 0.09, 0.18, 0.27]], + ... [[0.03, 0.26, 0.21, 0.18, 0.30], + ... [0.28, 0.10, 0.33, 0.15, 0.12]]] + ... ) + >>> perplexity_loss(y_true, y_pred) + Traceback (most recent call last): + ... + ValueError: Batch size of y_true and y_pred must be equal. + """ vocab_size = y_pred.shape[2] @@ -164,6 +574,52 @@ def smooth_l1_loss(y_true: np.ndarray, y_pred: np.ndarray, beta: float = 1.0) -> float: + """ + Calculate the Smooth L1 Loss between y_true and y_pred. + + The Smooth L1 Loss is less sensitive to outliers than the L2 Loss and is often used + in regression problems, such as object detection. + + Smooth L1 Loss = + 0.5 * (x - y)^2 / beta, if |x - y| < beta + |x - y| - 0.5 * beta, otherwise + + Reference: + https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html + + Args: + y_true: Array of true values. + y_pred: Array of predicted values. + beta: Specifies the threshold at which to change between L1 and L2 loss. + + Returns: + The calculated Smooth L1 Loss between y_true and y_pred. + + Raises: + ValueError: If the length of the two arrays is not the same. + + >>> y_true = np.array([3, 5, 2, 7]) + >>> y_pred = np.array([2.9, 4.8, 2.1, 7.2]) + >>> float(smooth_l1_loss(y_true, y_pred, 1.0)) + 0.012500000000000022 + + >>> y_true = np.array([2, 4, 6]) + >>> y_pred = np.array([1, 5, 7]) + >>> float(smooth_l1_loss(y_true, y_pred, 1.0)) + 0.5 + + >>> y_true = np.array([1, 3, 5, 7]) + >>> y_pred = np.array([1, 3, 5, 7]) + >>> float(smooth_l1_loss(y_true, y_pred, 1.0)) + 0.0 + + >>> y_true = np.array([1, 3, 5]) + >>> y_pred = np.array([1, 3, 5, 7]) + >>> smooth_l1_loss(y_true, y_pred, 1.0) + Traceback (most recent call last): + ... + ValueError: The length of the two arrays should be the same. + """ if len(y_true) != len(y_pred): raise ValueError("The length of the two arrays should be the same.") @@ -174,6 +630,32 @@ def kullback_leibler_divergence(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """ + Calculate the Kullback-Leibler divergence (KL divergence) loss between true labels + and predicted probabilities. + + KL divergence loss quantifies dissimilarity between true labels and predicted + probabilities. It's often used in training generative models. + + KL = Σ(y_true * ln(y_true / y_pred)) + + Reference: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence + + Parameters: + - y_true: True class probabilities + - y_pred: Predicted class probabilities + + >>> true_labels = np.array([0.2, 0.3, 0.5]) + >>> predicted_probs = np.array([0.3, 0.3, 0.4]) + >>> float(kullback_leibler_divergence(true_labels, predicted_probs)) + 0.030478754035472025 + >>> true_labels = np.array([0.2, 0.3, 0.5]) + >>> predicted_probs = np.array([0.3, 0.3, 0.4, 0.5]) + >>> kullback_leibler_divergence(true_labels, predicted_probs) + Traceback (most recent call last): + ... + ValueError: Input arrays must have the same length. + """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") @@ -184,4 +666,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/loss_functions.py
Add docstrings to clarify complex logic
from __future__ import annotations from collections.abc import Generator def collatz_sequence(n: int) -> Generator[int]: if not isinstance(n, int) or n < 1: raise Exception("Sequence only defined for positive integers") yield n while n != 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 yield n def main(): n = int(input("Your number: ")) sequence = tuple(collatz_sequence(n)) print(sequence) print(f"Collatz sequence from {n} took {len(sequence)} steps.") if __name__ == "__main__": main()
--- +++ @@ -1,3 +1,16 @@+""" +The Collatz conjecture is a famous unsolved problem in mathematics. Given a starting +positive integer, define the following sequence: +- If the current term n is even, then the next term is n/2. +- If the current term n is odd, then the next term is 3n + 1. +The conjecture claims that this sequence will always reach 1 for any starting number. + +Other names for this problem include the 3n + 1 problem, the Ulam conjecture, Kakutani's +problem, the Thwaites conjecture, Hasse's algorithm, the Syracuse problem, and the +hailstone sequence. + +Reference: https://en.wikipedia.org/wiki/Collatz_conjecture +""" from __future__ import annotations @@ -5,6 +18,32 @@ def collatz_sequence(n: int) -> Generator[int]: + """ + Generate the Collatz sequence starting at n. + >>> tuple(collatz_sequence(2.1)) + Traceback (most recent call last): + ... + Exception: Sequence only defined for positive integers + >>> tuple(collatz_sequence(0)) + Traceback (most recent call last): + ... + Exception: Sequence only defined for positive integers + >>> tuple(collatz_sequence(4)) + (4, 2, 1) + >>> tuple(collatz_sequence(11)) + (11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1) + >>> tuple(collatz_sequence(31)) # doctest: +NORMALIZE_WHITESPACE + (31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, + 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, + 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, + 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, + 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, + 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, + 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1) + >>> tuple(collatz_sequence(43)) # doctest: +NORMALIZE_WHITESPACE + (43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26, + 13, 40, 20, 10, 5, 16, 8, 4, 2, 1) + """ if not isinstance(n, int) or n < 1: raise Exception("Sequence only defined for positive integers") @@ -25,4 +64,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/collatz_sequence.py
Add docstrings to existing functions
def rank_of_matrix(matrix: list[list[int | float]]) -> int: rows = len(matrix) columns = len(matrix[0]) rank = min(rows, columns) for row in range(rank): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1, rows): multiplier = matrix[col][row] / matrix[row][row] for i in range(row, columns): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows reduce = True for i in range(row + 1, rows): if matrix[i][row] != 0: matrix[row], matrix[i] = matrix[i], matrix[row] reduce = False break if reduce: rank -= 1 for i in range(rows): matrix[i][row] = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,60 @@+""" +Calculate the rank of a matrix. + +See: https://en.wikipedia.org/wiki/Rank_(linear_algebra) +""" def rank_of_matrix(matrix: list[list[int | float]]) -> int: + """ + Finds the rank of a matrix. + + Args: + `matrix`: The matrix as a list of lists. + + Returns: + The rank of the matrix. + + Example: + + >>> matrix1 = [[1, 2, 3], + ... [4, 5, 6], + ... [7, 8, 9]] + >>> rank_of_matrix(matrix1) + 2 + >>> matrix2 = [[1, 0, 0], + ... [0, 1, 0], + ... [0, 0, 0]] + >>> rank_of_matrix(matrix2) + 2 + >>> matrix3 = [[1, 2, 3, 4], + ... [5, 6, 7, 8], + ... [9, 10, 11, 12]] + >>> rank_of_matrix(matrix3) + 2 + >>> rank_of_matrix([[2,3,-1,-1], + ... [1,-1,-2,4], + ... [3,1,3,-2], + ... [6,3,0,-7]]) + 4 + >>> rank_of_matrix([[2,1,-3,-6], + ... [3,-3,1,2], + ... [1,1,1,2]]) + 3 + >>> rank_of_matrix([[2,-1,0], + ... [1,3,4], + ... [4,1,-3]]) + 3 + >>> rank_of_matrix([[3,2,1], + ... [-6,-4,-2]]) + 1 + >>> rank_of_matrix([[],[]]) + 0 + >>> rank_of_matrix([[1]]) + 1 + >>> rank_of_matrix([[]]) + 0 + """ rows = len(matrix) columns = len(matrix[0]) @@ -36,4 +90,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/src/rank_of_matrix.py
Create docstrings for each class method
import string from math import log10 """ tf-idf Wikipedia: https://en.wikipedia.org/wiki/Tf%E2%80%93idf tf-idf and other word frequency algorithms are often used as a weighting factor in information retrieval and text mining. 83% of text-based recommender systems use tf-idf for term weighting. In Layman's terms, tf-idf is a statistic intended to reflect how important a word is to a document in a corpus (a collection of documents) Here I've implemented several word frequency algorithms that are commonly used in information retrieval: Term Frequency, Document Frequency, and TF-IDF (Term-Frequency*Inverse-Document-Frequency) are included. Term Frequency is a statistical function that returns a number representing how frequently an expression occurs in a document. This indicates how significant a particular term is in a given document. Document Frequency is a statistical function that returns an integer representing the number of documents in a corpus that a term occurs in (where the max number returned would be the number of documents in the corpus). Inverse Document Frequency is mathematically written as log10(N/df), where N is the number of documents in your corpus and df is the Document Frequency. If df is 0, a ZeroDivisionError will be thrown. Term-Frequency*Inverse-Document-Frequency is a measure of the originality of a term. It is mathematically written as tf*log10(N/df). It compares the number of times a term appears in a document with the number of documents the term appears in. If df is 0, a ZeroDivisionError will be thrown. """ def term_frequency(term: str, document: str) -> int: # strip all punctuation and newlines and replace it with '' document_without_punctuation = document.translate( str.maketrans("", "", string.punctuation) ).replace("\n", "") tokenize_document = document_without_punctuation.split(" ") # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()]) def document_frequency(term: str, corpus: str) -> tuple[int, int]: corpus_without_punctuation = corpus.lower().translate( str.maketrans("", "", string.punctuation) ) # strip all punctuation and replace it with '' docs = corpus_without_punctuation.split("\n") term = term.lower() return (len([doc for doc in docs if term in doc]), len(docs)) def inverse_document_frequency(df: int, n: int, smoothing=False) -> float: if smoothing: if n == 0: raise ValueError("log10(0) is undefined.") return round(1 + log10(n / (1 + df)), 3) if df == 0: raise ZeroDivisionError("df must be > 0") elif n == 0: raise ValueError("log10(0) is undefined.") return round(log10(n / df), 3) def tf_idf(tf: int, idf: int) -> float: return round(tf * idf, 3)
--- +++ @@ -41,6 +41,18 @@ def term_frequency(term: str, document: str) -> int: + """ + Return the number of times a term occurs within + a given document. + @params: term, the term to search a document for, and document, + the document to search within + @returns: an integer representing the number of times a term is + found within the document + + @examples: + >>> term_frequency("to", "To be, or not to be") + 2 + """ # strip all punctuation and newlines and replace it with '' document_without_punctuation = document.translate( str.maketrans("", "", string.punctuation) @@ -50,6 +62,19 @@ def document_frequency(term: str, corpus: str) -> tuple[int, int]: + """ + Calculate the number of documents in a corpus that contain a + given term + @params : term, the term to search each document for, and corpus, a collection of + documents. Each document should be separated by a newline. + @returns : the number of documents in the corpus that contain the term you are + searching for and the number of documents in the corpus + @examples : + >>> document_frequency("first", "This is the first document in the corpus.\\nThIs\ +is the second document in the corpus.\\nTHIS is \ +the third document in the corpus.") + (1, 3) + """ corpus_without_punctuation = corpus.lower().translate( str.maketrans("", "", string.punctuation) ) # strip all punctuation and replace it with '' @@ -59,6 +84,30 @@ def inverse_document_frequency(df: int, n: int, smoothing=False) -> float: + """ + Return an integer denoting the importance + of a word. This measure of importance is + calculated by log10(N/df), where N is the + number of documents and df is + the Document Frequency. + @params : df, the Document Frequency, N, + the number of documents in the corpus and + smoothing, if True return the idf-smooth + @returns : log10(N/df) or 1+log10(N/1+df) + @examples : + >>> inverse_document_frequency(3, 0) + Traceback (most recent call last): + ... + ValueError: log10(0) is undefined. + >>> inverse_document_frequency(1, 3) + 0.477 + >>> inverse_document_frequency(0, 3) + Traceback (most recent call last): + ... + ZeroDivisionError: df must be > 0 + >>> inverse_document_frequency(0, 3,True) + 1.477 + """ if smoothing: if n == 0: raise ValueError("log10(0) is undefined.") @@ -72,4 +121,17 @@ def tf_idf(tf: int, idf: int) -> float: - return round(tf * idf, 3)+ """ + Combine the term frequency + and inverse document frequency functions to + calculate the originality of a term. This + 'originality' is calculated by multiplying + the term frequency and the inverse document + frequency : tf-idf = TF * IDF + @params : tf, the term frequency, and idf, the inverse document + frequency + @examples : + >>> tf_idf(2, 0.477) + 0.954 + """ + return round(tf * idf, 3)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/word_frequency_functions.py
Write beginner-friendly docstrings
def abs_val(num: float) -> float: return -num if num < 0 else num def abs_min(x: list[int]) -> int: if len(x) == 0: raise ValueError("abs_min() arg is an empty sequence") j = x[0] for i in x: if abs_val(i) < abs_val(j): j = i return j def abs_max(x: list[int]) -> int: if len(x) == 0: raise ValueError("abs_max() arg is an empty sequence") j = x[0] for i in x: if abs(i) > abs(j): j = i return j def abs_max_sort(x: list[int]) -> int: if len(x) == 0: raise ValueError("abs_max_sort() arg is an empty sequence") return sorted(x, key=abs)[-1] def test_abs_val(): assert abs_val(0) == 0 assert abs_val(34) == 34 assert abs_val(-100000000000) == 100000000000 a = [-3, -1, 2, -11] assert abs_max(a) == -11 assert abs_max_sort(a) == -11 assert abs_min(a) == -1 if __name__ == "__main__": import doctest doctest.testmod() test_abs_val() print(abs_val(-34)) # --> 34
--- +++ @@ -1,10 +1,31 @@+"""Absolute Value.""" def abs_val(num: float) -> float: + """ + Find the absolute value of a number. + + >>> abs_val(-5.1) + 5.1 + >>> abs_val(-5) == abs_val(5) + True + >>> abs_val(0) + 0 + """ return -num if num < 0 else num def abs_min(x: list[int]) -> int: + """ + >>> abs_min([0,5,1,11]) + 0 + >>> abs_min([3,-10,-2]) + -2 + >>> abs_min([]) + Traceback (most recent call last): + ... + ValueError: abs_min() arg is an empty sequence + """ if len(x) == 0: raise ValueError("abs_min() arg is an empty sequence") j = x[0] @@ -15,6 +36,16 @@ def abs_max(x: list[int]) -> int: + """ + >>> abs_max([0,5,1,11]) + 11 + >>> abs_max([3,-10,-2]) + -10 + >>> abs_max([]) + Traceback (most recent call last): + ... + ValueError: abs_max() arg is an empty sequence + """ if len(x) == 0: raise ValueError("abs_max() arg is an empty sequence") j = x[0] @@ -25,12 +56,25 @@ def abs_max_sort(x: list[int]) -> int: + """ + >>> abs_max_sort([0,5,1,11]) + 11 + >>> abs_max_sort([3,-10,-2]) + -10 + >>> abs_max_sort([]) + Traceback (most recent call last): + ... + ValueError: abs_max_sort() arg is an empty sequence + """ if len(x) == 0: raise ValueError("abs_max_sort() arg is an empty sequence") return sorted(x, key=abs)[-1] def test_abs_val(): + """ + >>> test_abs_val() + """ assert abs_val(0) == 0 assert abs_val(34) == 34 assert abs_val(-100000000000) == 100000000000 @@ -47,4 +91,4 @@ doctest.testmod() test_abs_val() - print(abs_val(-34)) # --> 34+ print(abs_val(-34)) # --> 34
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/abs.py
Add standardized docstrings across the file
# XGBoost Classifier Example import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def data_handling(data: dict) -> tuple: # Split dataset into features and target # data is features return (data["data"], data["target"]) def xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier: classifier = XGBClassifier() classifier.fit(features, target) return classifier def main() -> None: # Load Iris dataset iris = load_iris() features, targets = data_handling(iris) x_train, x_test, y_train, y_test = train_test_split( features, targets, test_size=0.25 ) names = iris["target_names"] # Create an XGBoost Classifier from the training data xgboost_classifier = xgboost(x_train, y_train) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( xgboost_classifier, x_test, y_test, display_labels=names, cmap="Blues", normalize="true", ) plt.title("Normalized Confusion Matrix - IRIS Dataset") plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
--- +++ @@ -10,16 +10,42 @@ def data_handling(data: dict) -> tuple: # Split dataset into features and target # data is features + """ + >>> data_handling(({'data':'[5.1, 3.5, 1.4, 0.2]','target':([0])})) + ('[5.1, 3.5, 1.4, 0.2]', [0]) + >>> data_handling( + ... {'data': '[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', 'target': ([0, 0])} + ... ) + ('[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', [0, 0]) + """ return (data["data"], data["target"]) def xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier: + """ + # THIS TEST IS BROKEN!! >>> xgboost(np.array([[5.1, 3.6, 1.4, 0.2]]), np.array([0])) + XGBClassifier(base_score=0.5, booster='gbtree', callbacks=None, + colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, + early_stopping_rounds=None, enable_categorical=False, + eval_metric=None, gamma=0, gpu_id=-1, grow_policy='depthwise', + importance_type=None, interaction_constraints='', + learning_rate=0.300000012, max_bin=256, max_cat_to_onehot=4, + max_delta_step=0, max_depth=6, max_leaves=0, min_child_weight=1, + missing=nan, monotone_constraints='()', n_estimators=100, + n_jobs=0, num_parallel_tree=1, predictor='auto', random_state=0, + reg_alpha=0, reg_lambda=1, ...) + """ classifier = XGBClassifier() classifier.fit(features, target) return classifier def main() -> None: + """ + Url for the algorithm: + https://xgboost.readthedocs.io/en/stable/ + Iris type dataset is used to demonstrate algorithm. + """ # Load Iris dataset iris = load_iris() @@ -50,4 +76,4 @@ import doctest doctest.testmod(verbose=True) - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/xgboost_classifier.py
Write proper docstrings for these functions
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) -> list[list[list[float] | float]]: if dataset.ndim != value_array.ndim: msg = ( "Wrong input data's dimensions... " f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(msg) try: if dataset.shape[1] != value_array.shape[1]: msg = ( "Wrong input data's shape... " f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(msg) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: msg = ( "Input data have different datatype... " f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(msg) answer = [] for value in value_array: dist = euclidean(value, dataset[0]) vector = dataset[0].tolist() for dataset_value in dataset[1:]: temp_dist = euclidean(value, dataset_value) if dist > temp_dist: dist = temp_dist vector = dataset_value.tolist() answer.append([vector, dist]) return answer def cosine_similarity(input_a: np.ndarray, input_b: np.ndarray) -> float: return float(np.dot(input_a, input_b) / (norm(input_a) * norm(input_b))) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,12 @@+""" +Similarity Search : https://en.wikipedia.org/wiki/Similarity_search +Similarity search is a search algorithm for finding the nearest vector from +vectors, used in natural language processing. +In this algorithm, it calculates distance with euclidean distance and +returns a list containing two data for each vector: + 1. the nearest vector + 2. distance between the vector and the nearest vector (float) +""" from __future__ import annotations @@ -8,12 +17,85 @@ def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: + """ + Calculates euclidean distance between two data. + :param input_a: ndarray of first vector. + :param input_b: ndarray of second vector. + :return: Euclidean distance of input_a and input_b. By using math.sqrt(), + result will be float. + + >>> euclidean(np.array([0]), np.array([1])) + 1.0 + >>> euclidean(np.array([0, 1]), np.array([1, 1])) + 1.0 + >>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1])) + 1.0 + """ return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) -> list[list[list[float] | float]]: + """ + :param dataset: Set containing the vectors. Should be ndarray. + :param value_array: vector/vectors we want to know the nearest vector from dataset. + :return: Result will be a list containing + 1. the nearest vector + 2. distance from the vector + + >>> dataset = np.array([[0], [1], [2]]) + >>> value_array = np.array([[0]]) + >>> similarity_search(dataset, value_array) + [[[0], 0.0]] + + >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) + >>> value_array = np.array([[0, 1]]) + >>> similarity_search(dataset, value_array) + [[[0, 0], 1.0]] + + >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) + >>> value_array = np.array([[0, 0, 1]]) + >>> similarity_search(dataset, value_array) + [[[0, 0, 0], 1.0]] + + >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) + >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) + >>> similarity_search(dataset, value_array) + [[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]] + + These are the errors that might occur: + + 1. If dimensions are different. + For example, dataset has 2d array and value_array has 1d array: + >>> dataset = np.array([[1]]) + >>> value_array = np.array([1]) + >>> similarity_search(dataset, value_array) + Traceback (most recent call last): + ... + ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1 + + 2. If data's shapes are different. + For example, dataset has shape of (3, 2) and value_array has (2, 3). + We are expecting same shapes of two arrays, so it is wrong. + >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) + >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) + >>> similarity_search(dataset, value_array) + Traceback (most recent call last): + ... + ValueError: Wrong input data's shape... dataset : 2, value_array : 3 + + 3. If data types are different. + When trying to compare, we are expecting same types so they should be same. + If not, it'll come up with errors. + >>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32) + >>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32) + >>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + TypeError: Input data have different datatype... + dataset : float32, value_array : int32 + """ if dataset.ndim != value_array.ndim: msg = ( @@ -59,10 +141,22 @@ def cosine_similarity(input_a: np.ndarray, input_b: np.ndarray) -> float: + """ + Calculates cosine similarity between two data. + :param input_a: ndarray of first vector. + :param input_b: ndarray of second vector. + :return: Cosine similarity of input_a and input_b. By using math.sqrt(), + result will be float. + + >>> cosine_similarity(np.array([1]), np.array([1])) + 1.0 + >>> cosine_similarity(np.array([1, 2]), np.array([6, 32])) + 0.9615239476408232 + """ return float(np.dot(input_a, input_b) / (norm(input_a) * norm(input_b))) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/similarity_search.py
Write docstrings for utility functions
from math import pi, sqrt, tan def surface_area_cube(side_length: float) -> float: if side_length < 0: raise ValueError("surface_area_cube() only accepts non-negative values") return 6 * side_length**2 def surface_area_cuboid(length: float, breadth: float, height: float) -> float: if length < 0 or breadth < 0 or height < 0: raise ValueError("surface_area_cuboid() only accepts non-negative values") return 2 * ((length * breadth) + (breadth * height) + (length * height)) def surface_area_sphere(radius: float) -> float: if radius < 0: raise ValueError("surface_area_sphere() only accepts non-negative values") return 4 * pi * radius**2 def surface_area_hemisphere(radius: float) -> float: if radius < 0: raise ValueError("surface_area_hemisphere() only accepts non-negative values") return 3 * pi * radius**2 def surface_area_cone(radius: float, height: float) -> float: if radius < 0 or height < 0: raise ValueError("surface_area_cone() only accepts non-negative values") return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def surface_area_conical_frustum( radius_1: float, radius_2: float, height: float ) -> float: if radius_1 < 0 or radius_2 < 0 or height < 0: raise ValueError( "surface_area_conical_frustum() only accepts non-negative values" ) slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5 return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2) def surface_area_cylinder(radius: float, height: float) -> float: if radius < 0 or height < 0: raise ValueError("surface_area_cylinder() only accepts non-negative values") return 2 * pi * radius * (height + radius) def surface_area_torus(torus_radius: float, tube_radius: float) -> float: if torus_radius < 0 or tube_radius < 0: raise ValueError("surface_area_torus() only accepts non-negative values") if torus_radius < tube_radius: raise ValueError( "surface_area_torus() does not support spindle or self intersecting tori" ) return 4 * pow(pi, 2) * torus_radius * tube_radius def area_rectangle(length: float, width: float) -> float: if length < 0 or width < 0: raise ValueError("area_rectangle() only accepts non-negative values") return length * width def area_square(side_length: float) -> float: if side_length < 0: raise ValueError("area_square() only accepts non-negative values") return side_length**2 def area_triangle(base: float, height: float) -> float: if base < 0 or height < 0: raise ValueError("area_triangle() only accepts non-negative values") return (base * height) / 2 def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float: if side1 < 0 or side2 < 0 or side3 < 0: raise ValueError("area_triangle_three_sides() only accepts non-negative values") elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1: raise ValueError("Given three sides do not form a triangle") semi_perimeter = (side1 + side2 + side3) / 2 area = sqrt( semi_perimeter * (semi_perimeter - side1) * (semi_perimeter - side2) * (semi_perimeter - side3) ) return area def area_parallelogram(base: float, height: float) -> float: if base < 0 or height < 0: raise ValueError("area_parallelogram() only accepts non-negative values") return base * height def area_trapezium(base1: float, base2: float, height: float) -> float: if base1 < 0 or base2 < 0 or height < 0: raise ValueError("area_trapezium() only accepts non-negative values") return 1 / 2 * (base1 + base2) * height def area_circle(radius: float) -> float: if radius < 0: raise ValueError("area_circle() only accepts non-negative values") return pi * radius**2 def area_ellipse(radius_x: float, radius_y: float) -> float: if radius_x < 0 or radius_y < 0: raise ValueError("area_ellipse() only accepts non-negative values") return pi * radius_x * radius_y def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: if diagonal_1 < 0 or diagonal_2 < 0: raise ValueError("area_rhombus() only accepts non-negative values") return 1 / 2 * diagonal_1 * diagonal_2 def area_reg_polygon(sides: int, length: float) -> float: if not isinstance(sides, int) or sides < 3: raise ValueError( "area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides" ) elif length < 0: raise ValueError( "area_reg_polygon() only accepts non-negative values as \ length of a side" ) return (sides * length**2) / (4 * tan(pi / sides)) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print("[DEMO] Areas of various geometric shapes: \n") print(f"Rectangle: {area_rectangle(10, 20) = }") print(f"Square: {area_square(10) = }") print(f"Triangle: {area_triangle(10, 10) = }") print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(f"Parallelogram: {area_parallelogram(10, 20) = }") print(f"Rhombus: {area_rhombus(10, 20) = }") print(f"Trapezium: {area_trapezium(10, 20, 30) = }") print(f"Circle: {area_circle(20) = }") print(f"Ellipse: {area_ellipse(10, 20) = }") print("\nSurface Areas of various geometric shapes: \n") print(f"Cube: {surface_area_cube(20) = }") print(f"Cuboid: {surface_area_cuboid(10, 20, 30) = }") print(f"Sphere: {surface_area_sphere(20) = }") print(f"Hemisphere: {surface_area_hemisphere(20) = }") print(f"Cone: {surface_area_cone(10, 20) = }") print(f"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") print(f"Cylinder: {surface_area_cylinder(10, 20) = }") print(f"Torus: {surface_area_torus(20, 10) = }") print(f"Equilateral Triangle: {area_reg_polygon(3, 10) = }") print(f"Square: {area_reg_polygon(4, 10) = }") print(f"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
--- +++ @@ -1,165 +1,583 @@- -from math import pi, sqrt, tan - - -def surface_area_cube(side_length: float) -> float: - if side_length < 0: - raise ValueError("surface_area_cube() only accepts non-negative values") - return 6 * side_length**2 - - -def surface_area_cuboid(length: float, breadth: float, height: float) -> float: - if length < 0 or breadth < 0 or height < 0: - raise ValueError("surface_area_cuboid() only accepts non-negative values") - return 2 * ((length * breadth) + (breadth * height) + (length * height)) - - -def surface_area_sphere(radius: float) -> float: - if radius < 0: - raise ValueError("surface_area_sphere() only accepts non-negative values") - return 4 * pi * radius**2 - - -def surface_area_hemisphere(radius: float) -> float: - if radius < 0: - raise ValueError("surface_area_hemisphere() only accepts non-negative values") - return 3 * pi * radius**2 - - -def surface_area_cone(radius: float, height: float) -> float: - if radius < 0 or height < 0: - raise ValueError("surface_area_cone() only accepts non-negative values") - return pi * radius * (radius + (height**2 + radius**2) ** 0.5) - - -def surface_area_conical_frustum( - radius_1: float, radius_2: float, height: float -) -> float: - if radius_1 < 0 or radius_2 < 0 or height < 0: - raise ValueError( - "surface_area_conical_frustum() only accepts non-negative values" - ) - slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5 - return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2) - - -def surface_area_cylinder(radius: float, height: float) -> float: - if radius < 0 or height < 0: - raise ValueError("surface_area_cylinder() only accepts non-negative values") - return 2 * pi * radius * (height + radius) - - -def surface_area_torus(torus_radius: float, tube_radius: float) -> float: - if torus_radius < 0 or tube_radius < 0: - raise ValueError("surface_area_torus() only accepts non-negative values") - if torus_radius < tube_radius: - raise ValueError( - "surface_area_torus() does not support spindle or self intersecting tori" - ) - return 4 * pow(pi, 2) * torus_radius * tube_radius - - -def area_rectangle(length: float, width: float) -> float: - if length < 0 or width < 0: - raise ValueError("area_rectangle() only accepts non-negative values") - return length * width - - -def area_square(side_length: float) -> float: - if side_length < 0: - raise ValueError("area_square() only accepts non-negative values") - return side_length**2 - - -def area_triangle(base: float, height: float) -> float: - if base < 0 or height < 0: - raise ValueError("area_triangle() only accepts non-negative values") - return (base * height) / 2 - - -def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float: - if side1 < 0 or side2 < 0 or side3 < 0: - raise ValueError("area_triangle_three_sides() only accepts non-negative values") - elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1: - raise ValueError("Given three sides do not form a triangle") - semi_perimeter = (side1 + side2 + side3) / 2 - area = sqrt( - semi_perimeter - * (semi_perimeter - side1) - * (semi_perimeter - side2) - * (semi_perimeter - side3) - ) - return area - - -def area_parallelogram(base: float, height: float) -> float: - if base < 0 or height < 0: - raise ValueError("area_parallelogram() only accepts non-negative values") - return base * height - - -def area_trapezium(base1: float, base2: float, height: float) -> float: - if base1 < 0 or base2 < 0 or height < 0: - raise ValueError("area_trapezium() only accepts non-negative values") - return 1 / 2 * (base1 + base2) * height - - -def area_circle(radius: float) -> float: - if radius < 0: - raise ValueError("area_circle() only accepts non-negative values") - return pi * radius**2 - - -def area_ellipse(radius_x: float, radius_y: float) -> float: - if radius_x < 0 or radius_y < 0: - raise ValueError("area_ellipse() only accepts non-negative values") - return pi * radius_x * radius_y - - -def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: - if diagonal_1 < 0 or diagonal_2 < 0: - raise ValueError("area_rhombus() only accepts non-negative values") - return 1 / 2 * diagonal_1 * diagonal_2 - - -def area_reg_polygon(sides: int, length: float) -> float: - if not isinstance(sides, int) or sides < 3: - raise ValueError( - "area_reg_polygon() only accepts integers greater than or \ -equal to three as number of sides" - ) - elif length < 0: - raise ValueError( - "area_reg_polygon() only accepts non-negative values as \ -length of a side" - ) - return (sides * length**2) / (4 * tan(pi / sides)) - - -if __name__ == "__main__": - import doctest - - doctest.testmod(verbose=True) # verbose so we can see methods missing tests - - print("[DEMO] Areas of various geometric shapes: \n") - print(f"Rectangle: {area_rectangle(10, 20) = }") - print(f"Square: {area_square(10) = }") - print(f"Triangle: {area_triangle(10, 10) = }") - print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }") - print(f"Parallelogram: {area_parallelogram(10, 20) = }") - print(f"Rhombus: {area_rhombus(10, 20) = }") - print(f"Trapezium: {area_trapezium(10, 20, 30) = }") - print(f"Circle: {area_circle(20) = }") - print(f"Ellipse: {area_ellipse(10, 20) = }") - print("\nSurface Areas of various geometric shapes: \n") - print(f"Cube: {surface_area_cube(20) = }") - print(f"Cuboid: {surface_area_cuboid(10, 20, 30) = }") - print(f"Sphere: {surface_area_sphere(20) = }") - print(f"Hemisphere: {surface_area_hemisphere(20) = }") - print(f"Cone: {surface_area_cone(10, 20) = }") - print(f"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") - print(f"Cylinder: {surface_area_cylinder(10, 20) = }") - print(f"Torus: {surface_area_torus(20, 10) = }") - print(f"Equilateral Triangle: {area_reg_polygon(3, 10) = }") - print(f"Square: {area_reg_polygon(4, 10) = }") - print(f"Reqular Pentagon: {area_reg_polygon(5, 10) = }")+""" +Find the area of various geometric shapes +Wikipedia reference: https://en.wikipedia.org/wiki/Area +""" + +from math import pi, sqrt, tan + + +def surface_area_cube(side_length: float) -> float: + """ + Calculate the Surface Area of a Cube. + + >>> surface_area_cube(1) + 6 + >>> surface_area_cube(1.6) + 15.360000000000003 + >>> surface_area_cube(0) + 0 + >>> surface_area_cube(3) + 54 + >>> surface_area_cube(-1) + Traceback (most recent call last): + ... + ValueError: surface_area_cube() only accepts non-negative values + """ + if side_length < 0: + raise ValueError("surface_area_cube() only accepts non-negative values") + return 6 * side_length**2 + + +def surface_area_cuboid(length: float, breadth: float, height: float) -> float: + """ + Calculate the Surface Area of a Cuboid. + + >>> surface_area_cuboid(1, 2, 3) + 22 + >>> surface_area_cuboid(0, 0, 0) + 0 + >>> surface_area_cuboid(1.6, 2.6, 3.6) + 38.56 + >>> surface_area_cuboid(-1, 2, 3) + Traceback (most recent call last): + ... + ValueError: surface_area_cuboid() only accepts non-negative values + >>> surface_area_cuboid(1, -2, 3) + Traceback (most recent call last): + ... + ValueError: surface_area_cuboid() only accepts non-negative values + >>> surface_area_cuboid(1, 2, -3) + Traceback (most recent call last): + ... + ValueError: surface_area_cuboid() only accepts non-negative values + """ + if length < 0 or breadth < 0 or height < 0: + raise ValueError("surface_area_cuboid() only accepts non-negative values") + return 2 * ((length * breadth) + (breadth * height) + (length * height)) + + +def surface_area_sphere(radius: float) -> float: + """ + Calculate the Surface Area of a Sphere. + Wikipedia reference: https://en.wikipedia.org/wiki/Sphere + Formula: 4 * pi * r^2 + + >>> surface_area_sphere(5) + 314.1592653589793 + >>> surface_area_sphere(1) + 12.566370614359172 + >>> surface_area_sphere(1.6) + 32.169908772759484 + >>> surface_area_sphere(0) + 0.0 + >>> surface_area_sphere(-1) + Traceback (most recent call last): + ... + ValueError: surface_area_sphere() only accepts non-negative values + """ + if radius < 0: + raise ValueError("surface_area_sphere() only accepts non-negative values") + return 4 * pi * radius**2 + + +def surface_area_hemisphere(radius: float) -> float: + """ + Calculate the Surface Area of a Hemisphere. + Formula: 3 * pi * r^2 + + >>> surface_area_hemisphere(5) + 235.61944901923448 + >>> surface_area_hemisphere(1) + 9.42477796076938 + >>> surface_area_hemisphere(0) + 0.0 + >>> surface_area_hemisphere(1.1) + 11.40398133253095 + >>> surface_area_hemisphere(-1) + Traceback (most recent call last): + ... + ValueError: surface_area_hemisphere() only accepts non-negative values + """ + if radius < 0: + raise ValueError("surface_area_hemisphere() only accepts non-negative values") + return 3 * pi * radius**2 + + +def surface_area_cone(radius: float, height: float) -> float: + """ + Calculate the Surface Area of a Cone. + Wikipedia reference: https://en.wikipedia.org/wiki/Cone + Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5) + + >>> surface_area_cone(10, 24) + 1130.9733552923256 + >>> surface_area_cone(6, 8) + 301.59289474462014 + >>> surface_area_cone(1.6, 2.6) + 23.387862992395807 + >>> surface_area_cone(0, 0) + 0.0 + >>> surface_area_cone(-1, -2) + Traceback (most recent call last): + ... + ValueError: surface_area_cone() only accepts non-negative values + >>> surface_area_cone(1, -2) + Traceback (most recent call last): + ... + ValueError: surface_area_cone() only accepts non-negative values + >>> surface_area_cone(-1, 2) + Traceback (most recent call last): + ... + ValueError: surface_area_cone() only accepts non-negative values + """ + if radius < 0 or height < 0: + raise ValueError("surface_area_cone() only accepts non-negative values") + return pi * radius * (radius + (height**2 + radius**2) ** 0.5) + + +def surface_area_conical_frustum( + radius_1: float, radius_2: float, height: float +) -> float: + """ + Calculate the Surface Area of a Conical Frustum. + + >>> surface_area_conical_frustum(1, 2, 3) + 45.511728065337266 + >>> surface_area_conical_frustum(4, 5, 6) + 300.7913575056268 + >>> surface_area_conical_frustum(0, 0, 0) + 0.0 + >>> surface_area_conical_frustum(1.6, 2.6, 3.6) + 78.57907060751548 + >>> surface_area_conical_frustum(-1, 2, 3) + Traceback (most recent call last): + ... + ValueError: surface_area_conical_frustum() only accepts non-negative values + >>> surface_area_conical_frustum(1, -2, 3) + Traceback (most recent call last): + ... + ValueError: surface_area_conical_frustum() only accepts non-negative values + >>> surface_area_conical_frustum(1, 2, -3) + Traceback (most recent call last): + ... + ValueError: surface_area_conical_frustum() only accepts non-negative values + """ + if radius_1 < 0 or radius_2 < 0 or height < 0: + raise ValueError( + "surface_area_conical_frustum() only accepts non-negative values" + ) + slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5 + return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2) + + +def surface_area_cylinder(radius: float, height: float) -> float: + """ + Calculate the Surface Area of a Cylinder. + Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder + Formula: 2 * pi * r * (h + r) + + >>> surface_area_cylinder(7, 10) + 747.6990515543707 + >>> surface_area_cylinder(1.6, 2.6) + 42.22300526424682 + >>> surface_area_cylinder(0, 0) + 0.0 + >>> surface_area_cylinder(6, 8) + 527.7875658030853 + >>> surface_area_cylinder(-1, -2) + Traceback (most recent call last): + ... + ValueError: surface_area_cylinder() only accepts non-negative values + >>> surface_area_cylinder(1, -2) + Traceback (most recent call last): + ... + ValueError: surface_area_cylinder() only accepts non-negative values + >>> surface_area_cylinder(-1, 2) + Traceback (most recent call last): + ... + ValueError: surface_area_cylinder() only accepts non-negative values + """ + if radius < 0 or height < 0: + raise ValueError("surface_area_cylinder() only accepts non-negative values") + return 2 * pi * radius * (height + radius) + + +def surface_area_torus(torus_radius: float, tube_radius: float) -> float: + """Calculate the Area of a Torus. + Wikipedia reference: https://en.wikipedia.org/wiki/Torus + :return 4pi^2 * torus_radius * tube_radius + >>> surface_area_torus(1, 1) + 39.47841760435743 + >>> surface_area_torus(4, 3) + 473.7410112522892 + >>> surface_area_torus(3, 4) + Traceback (most recent call last): + ... + ValueError: surface_area_torus() does not support spindle or self intersecting tori + >>> surface_area_torus(1.6, 1.6) + 101.06474906715503 + >>> surface_area_torus(0, 0) + 0.0 + >>> surface_area_torus(-1, 1) + Traceback (most recent call last): + ... + ValueError: surface_area_torus() only accepts non-negative values + >>> surface_area_torus(1, -1) + Traceback (most recent call last): + ... + ValueError: surface_area_torus() only accepts non-negative values + """ + if torus_radius < 0 or tube_radius < 0: + raise ValueError("surface_area_torus() only accepts non-negative values") + if torus_radius < tube_radius: + raise ValueError( + "surface_area_torus() does not support spindle or self intersecting tori" + ) + return 4 * pow(pi, 2) * torus_radius * tube_radius + + +def area_rectangle(length: float, width: float) -> float: + """ + Calculate the area of a rectangle. + + >>> area_rectangle(10, 20) + 200 + >>> area_rectangle(1.6, 2.6) + 4.16 + >>> area_rectangle(0, 0) + 0 + >>> area_rectangle(-1, -2) + Traceback (most recent call last): + ... + ValueError: area_rectangle() only accepts non-negative values + >>> area_rectangle(1, -2) + Traceback (most recent call last): + ... + ValueError: area_rectangle() only accepts non-negative values + >>> area_rectangle(-1, 2) + Traceback (most recent call last): + ... + ValueError: area_rectangle() only accepts non-negative values + """ + if length < 0 or width < 0: + raise ValueError("area_rectangle() only accepts non-negative values") + return length * width + + +def area_square(side_length: float) -> float: + """ + Calculate the area of a square. + + >>> area_square(10) + 100 + >>> area_square(0) + 0 + >>> area_square(1.6) + 2.5600000000000005 + >>> area_square(-1) + Traceback (most recent call last): + ... + ValueError: area_square() only accepts non-negative values + """ + if side_length < 0: + raise ValueError("area_square() only accepts non-negative values") + return side_length**2 + + +def area_triangle(base: float, height: float) -> float: + """ + Calculate the area of a triangle given the base and height. + + >>> area_triangle(10, 10) + 50.0 + >>> area_triangle(1.6, 2.6) + 2.08 + >>> area_triangle(0, 0) + 0.0 + >>> area_triangle(-1, -2) + Traceback (most recent call last): + ... + ValueError: area_triangle() only accepts non-negative values + >>> area_triangle(1, -2) + Traceback (most recent call last): + ... + ValueError: area_triangle() only accepts non-negative values + >>> area_triangle(-1, 2) + Traceback (most recent call last): + ... + ValueError: area_triangle() only accepts non-negative values + """ + if base < 0 or height < 0: + raise ValueError("area_triangle() only accepts non-negative values") + return (base * height) / 2 + + +def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float: + """ + Calculate area of triangle when the length of 3 sides are known. + This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula + + >>> area_triangle_three_sides(5, 12, 13) + 30.0 + >>> area_triangle_three_sides(10, 11, 12) + 51.521233486786784 + >>> area_triangle_three_sides(0, 0, 0) + 0.0 + >>> area_triangle_three_sides(1.6, 2.6, 3.6) + 1.8703742940919619 + >>> area_triangle_three_sides(-1, -2, -1) + Traceback (most recent call last): + ... + ValueError: area_triangle_three_sides() only accepts non-negative values + >>> area_triangle_three_sides(1, -2, 1) + Traceback (most recent call last): + ... + ValueError: area_triangle_three_sides() only accepts non-negative values + >>> area_triangle_three_sides(2, 4, 7) + Traceback (most recent call last): + ... + ValueError: Given three sides do not form a triangle + >>> area_triangle_three_sides(2, 7, 4) + Traceback (most recent call last): + ... + ValueError: Given three sides do not form a triangle + >>> area_triangle_three_sides(7, 2, 4) + Traceback (most recent call last): + ... + ValueError: Given three sides do not form a triangle + """ + if side1 < 0 or side2 < 0 or side3 < 0: + raise ValueError("area_triangle_three_sides() only accepts non-negative values") + elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1: + raise ValueError("Given three sides do not form a triangle") + semi_perimeter = (side1 + side2 + side3) / 2 + area = sqrt( + semi_perimeter + * (semi_perimeter - side1) + * (semi_perimeter - side2) + * (semi_perimeter - side3) + ) + return area + + +def area_parallelogram(base: float, height: float) -> float: + """ + Calculate the area of a parallelogram. + + >>> area_parallelogram(10, 20) + 200 + >>> area_parallelogram(1.6, 2.6) + 4.16 + >>> area_parallelogram(0, 0) + 0 + >>> area_parallelogram(-1, -2) + Traceback (most recent call last): + ... + ValueError: area_parallelogram() only accepts non-negative values + >>> area_parallelogram(1, -2) + Traceback (most recent call last): + ... + ValueError: area_parallelogram() only accepts non-negative values + >>> area_parallelogram(-1, 2) + Traceback (most recent call last): + ... + ValueError: area_parallelogram() only accepts non-negative values + """ + if base < 0 or height < 0: + raise ValueError("area_parallelogram() only accepts non-negative values") + return base * height + + +def area_trapezium(base1: float, base2: float, height: float) -> float: + """ + Calculate the area of a trapezium. + + >>> area_trapezium(10, 20, 30) + 450.0 + >>> area_trapezium(1.6, 2.6, 3.6) + 7.5600000000000005 + >>> area_trapezium(0, 0, 0) + 0.0 + >>> area_trapezium(-1, -2, -3) + Traceback (most recent call last): + ... + ValueError: area_trapezium() only accepts non-negative values + >>> area_trapezium(-1, 2, 3) + Traceback (most recent call last): + ... + ValueError: area_trapezium() only accepts non-negative values + >>> area_trapezium(1, -2, 3) + Traceback (most recent call last): + ... + ValueError: area_trapezium() only accepts non-negative values + >>> area_trapezium(1, 2, -3) + Traceback (most recent call last): + ... + ValueError: area_trapezium() only accepts non-negative values + >>> area_trapezium(-1, -2, 3) + Traceback (most recent call last): + ... + ValueError: area_trapezium() only accepts non-negative values + >>> area_trapezium(1, -2, -3) + Traceback (most recent call last): + ... + ValueError: area_trapezium() only accepts non-negative values + >>> area_trapezium(-1, 2, -3) + Traceback (most recent call last): + ... + ValueError: area_trapezium() only accepts non-negative values + """ + if base1 < 0 or base2 < 0 or height < 0: + raise ValueError("area_trapezium() only accepts non-negative values") + return 1 / 2 * (base1 + base2) * height + + +def area_circle(radius: float) -> float: + """ + Calculate the area of a circle. + + >>> area_circle(20) + 1256.6370614359173 + >>> area_circle(1.6) + 8.042477193189871 + >>> area_circle(0) + 0.0 + >>> area_circle(-1) + Traceback (most recent call last): + ... + ValueError: area_circle() only accepts non-negative values + """ + if radius < 0: + raise ValueError("area_circle() only accepts non-negative values") + return pi * radius**2 + + +def area_ellipse(radius_x: float, radius_y: float) -> float: + """ + Calculate the area of a ellipse. + + >>> area_ellipse(10, 10) + 314.1592653589793 + >>> area_ellipse(10, 20) + 628.3185307179587 + >>> area_ellipse(0, 0) + 0.0 + >>> area_ellipse(1.6, 2.6) + 13.06902543893354 + >>> area_ellipse(-10, 20) + Traceback (most recent call last): + ... + ValueError: area_ellipse() only accepts non-negative values + >>> area_ellipse(10, -20) + Traceback (most recent call last): + ... + ValueError: area_ellipse() only accepts non-negative values + >>> area_ellipse(-10, -20) + Traceback (most recent call last): + ... + ValueError: area_ellipse() only accepts non-negative values + """ + if radius_x < 0 or radius_y < 0: + raise ValueError("area_ellipse() only accepts non-negative values") + return pi * radius_x * radius_y + + +def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: + """ + Calculate the area of a rhombus. + + >>> area_rhombus(10, 20) + 100.0 + >>> area_rhombus(1.6, 2.6) + 2.08 + >>> area_rhombus(0, 0) + 0.0 + >>> area_rhombus(-1, -2) + Traceback (most recent call last): + ... + ValueError: area_rhombus() only accepts non-negative values + >>> area_rhombus(1, -2) + Traceback (most recent call last): + ... + ValueError: area_rhombus() only accepts non-negative values + >>> area_rhombus(-1, 2) + Traceback (most recent call last): + ... + ValueError: area_rhombus() only accepts non-negative values + """ + if diagonal_1 < 0 or diagonal_2 < 0: + raise ValueError("area_rhombus() only accepts non-negative values") + return 1 / 2 * diagonal_1 * diagonal_2 + + +def area_reg_polygon(sides: int, length: float) -> float: + """ + Calculate the area of a regular polygon. + Wikipedia reference: https://en.wikipedia.org/wiki/Polygon#Regular_polygons + Formula: (n*s^2*cot(pi/n))/4 + + >>> area_reg_polygon(3, 10) + 43.301270189221945 + >>> area_reg_polygon(4, 10) + 100.00000000000001 + >>> area_reg_polygon(0, 0) + Traceback (most recent call last): + ... + ValueError: area_reg_polygon() only accepts integers greater than or equal to \ +three as number of sides + >>> area_reg_polygon(-1, -2) + Traceback (most recent call last): + ... + ValueError: area_reg_polygon() only accepts integers greater than or equal to \ +three as number of sides + >>> area_reg_polygon(5, -2) + Traceback (most recent call last): + ... + ValueError: area_reg_polygon() only accepts non-negative values as \ +length of a side + >>> area_reg_polygon(-1, 2) + Traceback (most recent call last): + ... + ValueError: area_reg_polygon() only accepts integers greater than or equal to \ +three as number of sides + """ + if not isinstance(sides, int) or sides < 3: + raise ValueError( + "area_reg_polygon() only accepts integers greater than or \ +equal to three as number of sides" + ) + elif length < 0: + raise ValueError( + "area_reg_polygon() only accepts non-negative values as \ +length of a side" + ) + return (sides * length**2) / (4 * tan(pi / sides)) + + +if __name__ == "__main__": + import doctest + + doctest.testmod(verbose=True) # verbose so we can see methods missing tests + + print("[DEMO] Areas of various geometric shapes: \n") + print(f"Rectangle: {area_rectangle(10, 20) = }") + print(f"Square: {area_square(10) = }") + print(f"Triangle: {area_triangle(10, 10) = }") + print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }") + print(f"Parallelogram: {area_parallelogram(10, 20) = }") + print(f"Rhombus: {area_rhombus(10, 20) = }") + print(f"Trapezium: {area_trapezium(10, 20, 30) = }") + print(f"Circle: {area_circle(20) = }") + print(f"Ellipse: {area_ellipse(10, 20) = }") + print("\nSurface Areas of various geometric shapes: \n") + print(f"Cube: {surface_area_cube(20) = }") + print(f"Cuboid: {surface_area_cuboid(10, 20, 30) = }") + print(f"Sphere: {surface_area_sphere(20) = }") + print(f"Hemisphere: {surface_area_hemisphere(20) = }") + print(f"Cone: {surface_area_cone(10, 20) = }") + print(f"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") + print(f"Cylinder: {surface_area_cylinder(10, 20) = }") + print(f"Torus: {surface_area_torus(20, 10) = }") + print(f"Equilateral Triangle: {area_reg_polygon(3, 10) = }") + print(f"Square: {area_reg_polygon(4, 10) = }") + print(f"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/area.py
Expand my code with proper documentation strings
from __future__ import annotations def allocation_num(number_of_bytes: int, partitions: int) -> list[str]: if partitions <= 0: raise ValueError("partitions must be a positive number!") if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!") bytes_per_partition = number_of_bytes // partitions allocation_list = [] for i in range(partitions): start_bytes = i * bytes_per_partition + 1 end_bytes = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f"{start_bytes}-{end_bytes}") return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,34 @@+""" +In a multi-threaded download, this algorithm could be used to provide +each worker thread with a block of non-overlapping bytes to download. +For example: + for i in allocation_list: + requests.get(url,headers={'Range':f'bytes={i}'}) +""" from __future__ import annotations def allocation_num(number_of_bytes: int, partitions: int) -> list[str]: + """ + Divide a number of bytes into x partitions. + :param number_of_bytes: the total of bytes. + :param partitions: the number of partition need to be allocated. + :return: list of bytes to be assigned to each worker thread + + >>> allocation_num(16647, 4) + ['1-4161', '4162-8322', '8323-12483', '12484-16647'] + >>> allocation_num(50000, 5) + ['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000'] + >>> allocation_num(888, 999) + Traceback (most recent call last): + ... + ValueError: partitions can not > number_of_bytes! + >>> allocation_num(888, -4) + Traceback (most recent call last): + ... + ValueError: partitions must be a positive number! + """ if partitions <= 0: raise ValueError("partitions must be a positive number!") if partitions > number_of_bytes: @@ -21,4 +47,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/allocation_number.py
Add standardized docstrings across the file
from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x**3 + x**2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
--- +++ @@ -1,3 +1,6 @@+""" +Approximates the area under the curve using the trapezoidal rule +""" from __future__ import annotations @@ -10,6 +13,26 @@ x_end: float, steps: int = 100, ) -> float: + """ + Treats curve as a collection of linear lines and sums the area of the + trapezium shape they form + :param fnc: a function which defines a curve + :param x_start: left end point to indicate the start of line segment + :param x_end: right end point to indicate end of line segment + :param steps: an accuracy gauge; more steps increases the accuracy + :return: a float representing the length of the curve + + >>> def f(x): + ... return 5 + >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}" + '10.000' + >>> def f(x): + ... return 9*x**2 + >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}" + '192.0000' + >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}" + '384.0000' + """ x1 = x_start fx1 = fnc(x_start) area = 0.0 @@ -35,4 +58,4 @@ i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") - i *= 10+ i *= 10
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/area_under_curve.py
Write Python docstrings for this snippet
import matplotlib.pyplot as plt import numpy as np class PolynomialRegression: __slots__ = "degree", "params" def __init__(self, degree: int) -> None: if degree < 0: raise ValueError("Polynomial degree must be non-negative") self.degree = degree self.params = None @staticmethod def _design_matrix(data: np.ndarray, degree: int) -> np.ndarray: _rows, *remaining = data.shape if remaining: raise ValueError("Data must have dimensions N x 1") return np.vander(data, N=degree + 1, increasing=True) def fit(self, x_train: np.ndarray, y_train: np.ndarray) -> None: X = PolynomialRegression._design_matrix(x_train, self.degree) # noqa: N806 _, cols = X.shape if np.linalg.matrix_rank(X) < cols: raise ArithmeticError( "Design matrix is not full rank, can't compute coefficients" ) # np.linalg.pinv() computes the Moore-Penrose pseudoinverse using SVD self.params = np.linalg.pinv(X) @ y_train def predict(self, data: np.ndarray) -> np.ndarray: if self.params is None: raise ArithmeticError("Predictor hasn't been fit yet") return PolynomialRegression._design_matrix(data, self.degree) @ self.params def main() -> None: import seaborn as sns mpg_data = sns.load_dataset("mpg") poly_reg = PolynomialRegression(degree=2) poly_reg.fit(mpg_data.weight, mpg_data.mpg) weight_sorted = np.sort(mpg_data.weight) predictions = poly_reg.predict(weight_sorted) plt.scatter(mpg_data.weight, mpg_data.mpg, color="gray", alpha=0.5) plt.plot(weight_sorted, predictions, color="red", linewidth=3) plt.title("Predicting Fuel Efficiency Using Polynomial Regression") plt.xlabel("Weight (lbs)") plt.ylabel("Fuel Efficiency (mpg)") plt.show() if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -1,3 +1,38 @@+""" +Polynomial regression is a type of regression analysis that models the relationship +between a predictor x and the response y as an mth-degree polynomial: + +y = β₀ + β₁x + β₂x² + ... + βₘxᵐ + ε + +By treating x, x², ..., xᵐ as distinct variables, we see that polynomial regression is a +special case of multiple linear regression. Therefore, we can use ordinary least squares +(OLS) estimation to estimate the vector of model parameters β = (β₀, β₁, β₂, ..., βₘ) +for polynomial regression: + +β = (XᵀX)⁻¹Xᵀy = X⁺y + +where X is the design matrix, y is the response vector, and X⁺ denotes the Moore-Penrose +pseudoinverse of X. In the case of polynomial regression, the design matrix is + + |1 x₁ x₁² ⋯ x₁ᵐ| +X = |1 x₂ x₂² ⋯ x₂ᵐ| + |⋮ ⋮ ⋮ ⋱ ⋮ | + |1 xₙ xₙ² ⋯ xₙᵐ| + +In OLS estimation, inverting XᵀX to compute X⁺ can be very numerically unstable. This +implementation sidesteps this need to invert XᵀX by computing X⁺ using singular value +decomposition (SVD): + +β = VΣ⁺Uᵀy + +where UΣVᵀ is an SVD of X. + +References: + - https://en.wikipedia.org/wiki/Polynomial_regression + - https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse + - https://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares + - https://en.wikipedia.org/wiki/Singular_value_decomposition +""" import matplotlib.pyplot as plt import numpy as np @@ -7,6 +42,9 @@ __slots__ = "degree", "params" def __init__(self, degree: int) -> None: + """ + @raises ValueError: if the polynomial degree is negative + """ if degree < 0: raise ValueError("Polynomial degree must be non-negative") @@ -15,6 +53,46 @@ @staticmethod def _design_matrix(data: np.ndarray, degree: int) -> np.ndarray: + """ + Constructs a polynomial regression design matrix for the given input data. For + input data x = (x₁, x₂, ..., xₙ) and polynomial degree m, the design matrix is + the Vandermonde matrix + + |1 x₁ x₁² ⋯ x₁ᵐ| + X = |1 x₂ x₂² ⋯ x₂ᵐ| + |⋮ ⋮ ⋮ ⋱ ⋮ | + |1 xₙ xₙ² ⋯ xₙᵐ| + + Reference: https://en.wikipedia.org/wiki/Vandermonde_matrix + + @param data: the input predictor values x, either for model fitting or for + prediction + @param degree: the polynomial degree m + @returns: the Vandermonde matrix X (see above) + @raises ValueError: if input data is not N x 1 + + >>> x = np.array([0, 1, 2]) + >>> PolynomialRegression._design_matrix(x, degree=0) + array([[1], + [1], + [1]]) + >>> PolynomialRegression._design_matrix(x, degree=1) + array([[1, 0], + [1, 1], + [1, 2]]) + >>> PolynomialRegression._design_matrix(x, degree=2) + array([[1, 0, 0], + [1, 1, 1], + [1, 2, 4]]) + >>> PolynomialRegression._design_matrix(x, degree=3) + array([[1, 0, 0, 0], + [1, 1, 1, 1], + [1, 2, 4, 8]]) + >>> PolynomialRegression._design_matrix(np.array([[0, 0], [0 , 0]]), degree=3) + Traceback (most recent call last): + ... + ValueError: Data must have dimensions N x 1 + """ _rows, *remaining = data.shape if remaining: raise ValueError("Data must have dimensions N x 1") @@ -22,6 +100,45 @@ return np.vander(data, N=degree + 1, increasing=True) def fit(self, x_train: np.ndarray, y_train: np.ndarray) -> None: + """ + Computes the polynomial regression model parameters using ordinary least squares + (OLS) estimation: + + β = (XᵀX)⁻¹Xᵀy = X⁺y + + where X⁺ denotes the Moore-Penrose pseudoinverse of the design matrix X. This + function computes X⁺ using singular value decomposition (SVD). + + References: + - https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse + - https://en.wikipedia.org/wiki/Singular_value_decomposition + - https://en.wikipedia.org/wiki/Multicollinearity + + @param x_train: the predictor values x for model fitting + @param y_train: the response values y for model fitting + @raises ArithmeticError: if X isn't full rank, then XᵀX is singular and β + doesn't exist + + >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + >>> y = x**3 - 2 * x**2 + 3 * x - 5 + >>> poly_reg = PolynomialRegression(degree=3) + >>> poly_reg.fit(x, y) + >>> poly_reg.params + array([-5., 3., -2., 1.]) + >>> poly_reg = PolynomialRegression(degree=20) + >>> poly_reg.fit(x, y) + Traceback (most recent call last): + ... + ArithmeticError: Design matrix is not full rank, can't compute coefficients + + Make sure errors don't grow too large: + >>> coefs = np.array([-250, 50, -2, 36, 20, -12, 10, 2, -1, -15, 1]) + >>> y = PolynomialRegression._design_matrix(x, len(coefs) - 1) @ coefs + >>> poly_reg = PolynomialRegression(degree=len(coefs) - 1) + >>> poly_reg.fit(x, y) + >>> np.allclose(poly_reg.params, coefs, atol=10e-3) + True + """ X = PolynomialRegression._design_matrix(x_train, self.degree) # noqa: N806 _, cols = X.shape if np.linalg.matrix_rank(X) < cols: @@ -33,6 +150,30 @@ self.params = np.linalg.pinv(X) @ y_train def predict(self, data: np.ndarray) -> np.ndarray: + """ + Computes the predicted response values y for the given input data by + constructing the design matrix X and evaluating y = Xβ. + + @param data: the predictor values x for prediction + @returns: the predicted response values y = Xβ + @raises ArithmeticError: if this function is called before the model + parameters are fit + + >>> x = np.array([0, 1, 2, 3, 4]) + >>> y = x**3 - 2 * x**2 + 3 * x - 5 + >>> poly_reg = PolynomialRegression(degree=3) + >>> poly_reg.fit(x, y) + >>> poly_reg.predict(np.array([-1])) + array([-11.]) + >>> poly_reg.predict(np.array([-2])) + array([-27.]) + >>> poly_reg.predict(np.array([6])) + array([157.]) + >>> PolynomialRegression(degree=3).predict(x) + Traceback (most recent call last): + ... + ArithmeticError: Predictor hasn't been fit yet + """ if self.params is None: raise ArithmeticError("Predictor hasn't been fit yet") @@ -40,6 +181,12 @@ def main() -> None: + """ + Fit a polynomial regression model to predict fuel efficiency using seaborn's mpg + dataset + + >>> pass # Placeholder, function is only for demo purposes + """ import seaborn as sns mpg_data = sns.load_dataset("mpg") @@ -63,4 +210,4 @@ doctest.testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/polynomial_regression.py
Add docstrings for utility scripts
def add(first: int, second: int) -> int: while second != 0: c = first & second first ^= second second = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() first = int(input("Enter the first number: ").strip()) second = int(input("Enter the second number: ").strip()) print(f"{add(first, second) = }")
--- +++ @@ -1,6 +1,27 @@+""" +Illustrate how to add the integer without arithmetic operation +Author: suraj Kumar +Time Complexity: 1 +https://en.wikipedia.org/wiki/Bitwise_operation +""" def add(first: int, second: int) -> int: + """ + Implementation of addition of integer + + Examples: + >>> add(3, 5) + 8 + >>> add(13, 5) + 18 + >>> add(-7, 2) + -5 + >>> add(0, -7) + -7 + >>> add(-321, 0) + -321 + """ while second != 0: c = first & second first ^= second @@ -15,4 +36,4 @@ first = int(input("Enter the first number: ").strip()) second = int(input("Enter the second number: ").strip()) - print(f"{add(first, second) = }")+ print(f"{add(first, second) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/addition_without_arithmetic.py
Help me comply with documentation standards
def binary_exp_recursive(base: float, exponent: int) -> float: if exponent < 0: raise ValueError("Exponent must be a non-negative integer") if exponent == 0: return 1 if exponent % 2 == 1: return binary_exp_recursive(base, exponent - 1) * base b = binary_exp_recursive(base, exponent // 2) return b * b def binary_exp_iterative(base: float, exponent: int) -> float: if exponent < 0: raise ValueError("Exponent must be a non-negative integer") res: int | float = 1 while exponent > 0: if exponent & 1: res *= base base *= base exponent >>= 1 return res def binary_exp_mod_recursive(base: float, exponent: int, modulus: int) -> float: if exponent < 0: raise ValueError("Exponent must be a non-negative integer") if modulus <= 0: raise ValueError("Modulus must be a positive integer") if exponent == 0: return 1 if exponent % 2 == 1: return (binary_exp_mod_recursive(base, exponent - 1, modulus) * base) % modulus r = binary_exp_mod_recursive(base, exponent // 2, modulus) return (r * r) % modulus def binary_exp_mod_iterative(base: float, exponent: int, modulus: int) -> float: if exponent < 0: raise ValueError("Exponent must be a non-negative integer") if modulus <= 0: raise ValueError("Modulus must be a positive integer") res: int | float = 1 while exponent > 0: if exponent & 1: res = ((res % modulus) * (base % modulus)) % modulus base *= base exponent >>= 1 return res if __name__ == "__main__": from timeit import timeit a = 1269380576 b = 374 c = 34 runs = 100_000 print( timeit( f"binary_exp_recursive({a}, {b})", setup="from __main__ import binary_exp_recursive", number=runs, ) ) print( timeit( f"binary_exp_iterative({a}, {b})", setup="from __main__ import binary_exp_iterative", number=runs, ) ) print( timeit( f"binary_exp_mod_recursive({a}, {b}, {c})", setup="from __main__ import binary_exp_mod_recursive", number=runs, ) ) print( timeit( f"binary_exp_mod_iterative({a}, {b}, {c})", setup="from __main__ import binary_exp_mod_iterative", number=runs, ) )
--- +++ @@ -1,6 +1,42 @@+""" +Binary Exponentiation + +This is a method to find a^b in O(log b) time complexity and is one of the most commonly +used methods of exponentiation. The method is also useful for modular exponentiation, +when the solution to (a^b) % c is required. + +To calculate a^b: +- If b is even, then a^b = (a * a)^(b / 2) +- If b is odd, then a^b = a * a^(b - 1) +Repeat until b = 1 or b = 0 + +For modular exponentiation, we use the fact that (a * b) % c = ((a % c) * (b % c)) % c +""" def binary_exp_recursive(base: float, exponent: int) -> float: + """ + Computes a^b recursively, where a is the base and b is the exponent + + >>> binary_exp_recursive(3, 5) + 243 + >>> binary_exp_recursive(11, 13) + 34522712143931 + >>> binary_exp_recursive(-1, 3) + -1 + >>> binary_exp_recursive(0, 5) + 0 + >>> binary_exp_recursive(3, 1) + 3 + >>> binary_exp_recursive(3, 0) + 1 + >>> binary_exp_recursive(1.5, 4) + 5.0625 + >>> binary_exp_recursive(3, -1) + Traceback (most recent call last): + ... + ValueError: Exponent must be a non-negative integer + """ if exponent < 0: raise ValueError("Exponent must be a non-negative integer") @@ -15,6 +51,28 @@ def binary_exp_iterative(base: float, exponent: int) -> float: + """ + Computes a^b iteratively, where a is the base and b is the exponent + + >>> binary_exp_iterative(3, 5) + 243 + >>> binary_exp_iterative(11, 13) + 34522712143931 + >>> binary_exp_iterative(-1, 3) + -1 + >>> binary_exp_iterative(0, 5) + 0 + >>> binary_exp_iterative(3, 1) + 3 + >>> binary_exp_iterative(3, 0) + 1 + >>> binary_exp_iterative(1.5, 4) + 5.0625 + >>> binary_exp_iterative(3, -1) + Traceback (most recent call last): + ... + ValueError: Exponent must be a non-negative integer + """ if exponent < 0: raise ValueError("Exponent must be a non-negative integer") @@ -30,6 +88,25 @@ def binary_exp_mod_recursive(base: float, exponent: int, modulus: int) -> float: + """ + Computes a^b % c recursively, where a is the base, b is the exponent, and c is the + modulus + + >>> binary_exp_mod_recursive(3, 4, 5) + 1 + >>> binary_exp_mod_recursive(11, 13, 7) + 4 + >>> binary_exp_mod_recursive(1.5, 4, 3) + 2.0625 + >>> binary_exp_mod_recursive(7, -1, 10) + Traceback (most recent call last): + ... + ValueError: Exponent must be a non-negative integer + >>> binary_exp_mod_recursive(7, 13, 0) + Traceback (most recent call last): + ... + ValueError: Modulus must be a positive integer + """ if exponent < 0: raise ValueError("Exponent must be a non-negative integer") if modulus <= 0: @@ -46,6 +123,25 @@ def binary_exp_mod_iterative(base: float, exponent: int, modulus: int) -> float: + """ + Computes a^b % c iteratively, where a is the base, b is the exponent, and c is the + modulus + + >>> binary_exp_mod_iterative(3, 4, 5) + 1 + >>> binary_exp_mod_iterative(11, 13, 7) + 4 + >>> binary_exp_mod_iterative(1.5, 4, 3) + 2.0625 + >>> binary_exp_mod_iterative(7, -1, 10) + Traceback (most recent call last): + ... + ValueError: Exponent must be a non-negative integer + >>> binary_exp_mod_iterative(7, 13, 0) + Traceback (most recent call last): + ... + ValueError: Modulus must be a positive integer + """ if exponent < 0: raise ValueError("Exponent must be a non-negative integer") if modulus <= 0: @@ -97,4 +193,4 @@ setup="from __main__ import binary_exp_mod_iterative", number=runs, ) - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/binary_exponentiation.py
Add clean documentation to messy code
def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str: if (not isinstance(digit_position, int)) or (digit_position <= 0): raise ValueError("Digit position must be a positive integer") elif (not isinstance(precision, int)) or (precision < 0): raise ValueError("Precision must be a nonnegative integer") # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly # accurate sum_result = ( 4 * _subsum(digit_position, 1, precision) - 2 * _subsum(digit_position, 4, precision) - _subsum(digit_position, 5, precision) - _subsum(digit_position, 6, precision) ) # return the first hex digit of the fractional part of the result return hex(int((sum_result % 1) * 16))[2:] def _subsum( digit_pos_to_extract: int, denominator_addend: int, precision: int ) -> float: # only care about first digit of fractional part; don't need decimal total = 0.0 for sum_index in range(digit_pos_to_extract + precision): denominator = 8 * sum_index + denominator_addend if sum_index < digit_pos_to_extract: # if the exponential term is an integer and we mod it by the denominator # before dividing, only the integer part of the sum will change; # the fractional part will not exponential_term = pow( 16, digit_pos_to_extract - 1 - sum_index, denominator ) else: exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index) total += exponential_term / denominator return total if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,4 +1,42 @@ def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str: + """ + Implement a popular pi-digit-extraction algorithm known as the + Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi. + Wikipedia page: + https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula + @param digit_position: a positive integer representing the position of the digit to + extract. + The digit immediately after the decimal point is located at position 1. + @param precision: number of terms in the second summation to calculate. + A higher number reduces the chance of an error but increases the runtime. + @return: a hexadecimal digit representing the digit at the nth position + in pi's decimal expansion. + + >>> "".join(bailey_borwein_plouffe(i) for i in range(1, 11)) + '243f6a8885' + >>> bailey_borwein_plouffe(5, 10000) + '6' + >>> bailey_borwein_plouffe(-10) + Traceback (most recent call last): + ... + ValueError: Digit position must be a positive integer + >>> bailey_borwein_plouffe(0) + Traceback (most recent call last): + ... + ValueError: Digit position must be a positive integer + >>> bailey_borwein_plouffe(1.7) + Traceback (most recent call last): + ... + ValueError: Digit position must be a positive integer + >>> bailey_borwein_plouffe(2, -10) + Traceback (most recent call last): + ... + ValueError: Precision must be a nonnegative integer + >>> bailey_borwein_plouffe(2, 1.6) + Traceback (most recent call last): + ... + ValueError: Precision must be a nonnegative integer + """ if (not isinstance(digit_position, int)) or (digit_position <= 0): raise ValueError("Digit position must be a positive integer") elif (not isinstance(precision, int)) or (precision < 0): @@ -21,6 +59,14 @@ digit_pos_to_extract: int, denominator_addend: int, precision: int ) -> float: # only care about first digit of fractional part; don't need decimal + """ + Private helper function to implement the summation + functionality. + @param digit_pos_to_extract: digit position to extract + @param denominator_addend: added to denominator of fractions in the formula + @param precision: same as precision in main function + @return: floating-point number whose integer part is not important + """ total = 0.0 for sum_index in range(digit_pos_to_extract + precision): denominator = 8 * sum_index + denominator_addend @@ -40,4 +86,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/bailey_borwein_plouffe.py
Generate docstrings for exported functions
from __future__ import annotations # Extended Euclid def extended_euclid(a: int, b: int) -> tuple[int, int]: if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: (b, _x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b # Same a above using InvertingModulo def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
--- +++ @@ -1,9 +1,30 @@+""" +Chinese Remainder Theorem: +GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) + +If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b +there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are +two such integers, then n1=n2(mod ab) + +Algorithm : + +1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 +2. Take n = ra*by + rb*ax +""" from __future__ import annotations # Extended Euclid def extended_euclid(a: int, b: int) -> tuple[int, int]: + """ + >>> extended_euclid(10, 6) + (-1, 2) + + >>> extended_euclid(7, 5) + (-2, 3) + + """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) @@ -13,6 +34,18 @@ # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: + """ + >>> chinese_remainder_theorem(5,1,7,3) + 31 + + Explanation : 31 is the smallest number such that + (i) When we divide it by 5, we get remainder 1 + (ii) When we divide it by 7, we get remainder 3 + + >>> chinese_remainder_theorem(6,1,4,3) + 14 + + """ (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 @@ -24,6 +57,14 @@ # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: + """ + >>> invert_modulo(2, 5) + 3 + + >>> invert_modulo(8,7) + 1 + + """ (b, _x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n @@ -32,6 +73,14 @@ # Same a above using InvertingModulo def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: + """ + >>> chinese_remainder_theorem2(5,1,7,3) + 31 + + >>> chinese_remainder_theorem2(6,1,4,3) + 14 + + """ x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 @@ -44,4 +93,4 @@ testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) - testmod(name="extended_euclid", verbose=True)+ testmod(name="extended_euclid", verbose=True)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/chinese_remainder_theorem.py
Generate descriptive docstrings automatically
def ceil(x: float) -> int: return int(x) if x - int(x) <= 0 else int(x) + 1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,10 +1,24 @@+""" +https://en.wikipedia.org/wiki/Floor_and_ceiling_functions +""" def ceil(x: float) -> int: + """ + Return the ceiling of x as an Integral. + + :param x: the number + :return: the smallest integer >= x. + + >>> import math + >>> all(ceil(n) == math.ceil(n) for n + ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) + True + """ return int(x) if x - int(x) <= 0 else int(x) + 1 if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/ceil.py
Write docstrings for algorithm functions
from __future__ import annotations def find_min_iterative(nums: list[int | float]) -> int | float: if len(nums) == 0: raise ValueError("find_min_iterative() arg is an empty sequence") min_num = nums[0] for num in nums: min_num = min(min_num, num) return min_num # Divide and Conquer algorithm def find_min_recursive(nums: list[int | float], left: int, right: int) -> int | float: if len(nums) == 0: raise ValueError("find_min_recursive() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_min = find_min_recursive(nums, left, mid) # find min in range[left, mid] right_min = find_min_recursive( nums, mid + 1, right ) # find min in range[mid + 1, right] return left_min if left_min <= right_min else right_min if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
--- +++ @@ -2,6 +2,24 @@ def find_min_iterative(nums: list[int | float]) -> int | float: + """ + Find Minimum Number in a List + :param nums: contains elements + :return: min number in list + + >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): + ... find_min_iterative(nums) == min(nums) + True + True + True + True + >>> find_min_iterative([0, 1, 2, 3, 4, 5, -3, 24, -56]) + -56 + >>> find_min_iterative([]) + Traceback (most recent call last): + ... + ValueError: find_min_iterative() arg is an empty sequence + """ if len(nums) == 0: raise ValueError("find_min_iterative() arg is an empty sequence") min_num = nums[0] @@ -12,6 +30,37 @@ # Divide and Conquer algorithm def find_min_recursive(nums: list[int | float], left: int, right: int) -> int | float: + """ + find min value in list + :param nums: contains elements + :param left: index of first element + :param right: index of last element + :return: min in nums + + >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): + ... find_min_recursive(nums, 0, len(nums) - 1) == min(nums) + True + True + True + True + >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] + >>> find_min_recursive(nums, 0, len(nums) - 1) == min(nums) + True + >>> find_min_recursive([], 0, 0) + Traceback (most recent call last): + ... + ValueError: find_min_recursive() arg is an empty sequence + >>> find_min_recursive(nums, 0, len(nums)) == min(nums) + Traceback (most recent call last): + ... + IndexError: list index out of range + >>> find_min_recursive(nums, -len(nums), -1) == min(nums) + True + >>> find_min_recursive(nums, -len(nums) - 1, -1) == min(nums) + Traceback (most recent call last): + ... + IndexError: list index out of range + """ if len(nums) == 0: raise ValueError("find_min_recursive() arg is an empty sequence") if ( @@ -35,4 +84,4 @@ if __name__ == "__main__": import doctest - doctest.testmod(verbose=True)+ doctest.testmod(verbose=True)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/find_min.py
Document this module using docstrings
def combinations(n: int, k: int) -> int: # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k") res = 1 for i in range(k): res *= n - i res //= i + 1 return res if __name__ == "__main__": print( "The number of five-card hands possible from a standard", f"fifty-two card deck is: {combinations(52, 5)}\n", ) print( "If a class of 40 students must be arranged into groups of", f"4 for group projects, there are {combinations(40, 4)} ways", "to arrange them.\n", ) print( "If 10 teams are competing in a Formula One race, there", f"are {combinations(10, 3)} ways that first, second and", "third place can be awarded.", )
--- +++ @@ -1,6 +1,34 @@+""" +https://en.wikipedia.org/wiki/Combination +""" def combinations(n: int, k: int) -> int: + """ + Returns the number of different combinations of k length which can + be made from n values, where n >= k. + + Examples: + >>> combinations(10,5) + 252 + + >>> combinations(6,3) + 20 + + >>> combinations(20,5) + 15504 + + >>> combinations(52, 5) + 2598960 + + >>> combinations(0, 0) + 1 + + >>> combinations(-4, -5) + ... + Traceback (most recent call last): + ValueError: Please enter positive integers for n and k where n >= k + """ # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible @@ -29,4 +57,4 @@ "If 10 teams are competing in a Formula One race, there", f"are {combinations(10, 3)} ways that first, second and", "third place can be awarded.", - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/combinations.py
Fully document this Python code with docstrings
def decimal_isolate(number: float, digit_amount: int) -> float: if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
--- +++ @@ -1,6 +1,32 @@+""" +Isolate the Decimal part of a Number +https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point +""" def decimal_isolate(number: float, digit_amount: int) -> float: + """ + Isolates the decimal part of a number. + If digitAmount > 0 round to that decimal place, else print the entire decimal. + >>> decimal_isolate(1.53, 0) + 0.53 + >>> decimal_isolate(35.345, 1) + 0.3 + >>> decimal_isolate(35.345, 2) + 0.34 + >>> decimal_isolate(35.345, 3) + 0.345 + >>> decimal_isolate(-14.789, 3) + -0.789 + >>> decimal_isolate(0, 2) + 0 + >>> decimal_isolate(-14.123, 1) + -0.1 + >>> decimal_isolate(-14.123, 2) + -0.12 + >>> decimal_isolate(-14.123, 3) + -0.123 + """ if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) @@ -15,4 +41,4 @@ print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) - print(decimal_isolate(-14.123, 3))+ print(decimal_isolate(-14.123, 3))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/decimal_isolate.py
Write beginner-friendly docstrings
# dodecahedron.py def dodecahedron_surface_area(edge: float) -> float: if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def dodecahedron_volume(edge: float) -> float: if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,36 @@ # dodecahedron.py +""" +A regular dodecahedron is a three-dimensional figure made up of +12 pentagon faces having the same equal size. +""" def dodecahedron_surface_area(edge: float) -> float: + """ + Calculates the surface area of a regular dodecahedron + a = 3 * ((25 + 10 * (5** (1 / 2))) ** (1 / 2 )) * (e**2) + where: + a --> is the area of the dodecahedron + e --> is the length of the edge + reference-->"Dodecahedron" Study.com + <https://study.com/academy/lesson/dodecahedron-volume-surface-area-formulas.html> + + :param edge: length of the edge of the dodecahedron + :type edge: float + :return: the surface area of the dodecahedron as a float + + + Tests: + >>> dodecahedron_surface_area(5) + 516.1432201766901 + >>> dodecahedron_surface_area(10) + 2064.5728807067603 + >>> dodecahedron_surface_area(-1) + Traceback (most recent call last): + ... + ValueError: Length must be a positive. + """ if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") @@ -10,6 +38,29 @@ def dodecahedron_volume(edge: float) -> float: + """ + Calculates the volume of a regular dodecahedron + v = ((15 + (7 * (5** (1 / 2)))) / 4) * (e**3) + where: + v --> is the volume of the dodecahedron + e --> is the length of the edge + reference-->"Dodecahedron" Study.com + <https://study.com/academy/lesson/dodecahedron-volume-surface-area-formulas.html> + + :param edge: length of the edge of the dodecahedron + :type edge: float + :return: the volume of the dodecahedron as a float + + Tests: + >>> dodecahedron_volume(5) + 957.8898700780791 + >>> dodecahedron_volume(10) + 7663.118960624633 + >>> dodecahedron_volume(-1) + Traceback (most recent call last): + ... + ValueError: Length must be a positive. + """ if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") @@ -19,4 +70,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/dodecahedron.py
Create structured documentation for my script
from fractions import Fraction from math import floor def continued_fraction(num: Fraction) -> list[int]: numerator, denominator = num.as_integer_ratio() continued_fraction_list: list[int] = [] while True: integer_part = floor(numerator / denominator) continued_fraction_list.append(integer_part) numerator -= integer_part * denominator if numerator == 0: break numerator, denominator = denominator, numerator return continued_fraction_list if __name__ == "__main__": import doctest doctest.testmod() print("Continued Fraction of 0.84375 is: ", continued_fraction(Fraction("0.84375")))
--- +++ @@ -1,9 +1,41 @@+""" +Finding the continuous fraction for a rational number using python + +https://en.wikipedia.org/wiki/Continued_fraction +""" from fractions import Fraction from math import floor def continued_fraction(num: Fraction) -> list[int]: + """ + :param num: + Fraction of the number whose continued fractions to be found. + Use Fraction(str(number)) for more accurate results due to + float inaccuracies. + + :return: + The continued fraction of rational number. + It is the all commas in the (n + 1)-tuple notation. + + >>> continued_fraction(Fraction(2)) + [2] + >>> continued_fraction(Fraction("3.245")) + [3, 4, 12, 4] + >>> continued_fraction(Fraction("2.25")) + [2, 4] + >>> continued_fraction(1/Fraction("2.25")) + [0, 2, 4] + >>> continued_fraction(Fraction("415/93")) + [4, 2, 6, 7] + >>> continued_fraction(Fraction(0)) + [0] + >>> continued_fraction(Fraction(0.75)) + [0, 1, 3] + >>> continued_fraction(Fraction("-2.25")) # -2.25 = -3 + 0.75 + [-3, 1, 3] + """ numerator, denominator = num.as_integer_ratio() continued_fraction_list: list[int] = [] while True: @@ -22,4 +54,4 @@ doctest.testmod() - print("Continued Fraction of 0.84375 is: ", continued_fraction(Fraction("0.84375")))+ print("Continued Fraction of 0.84375 is: ", continued_fraction(Fraction("0.84375")))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/continued_fraction.py
Add docstrings that explain purpose and usage
from maths.prime_check import is_prime def is_germain_prime(number: int) -> bool: if not isinstance(number, int) or number < 1: msg = f"Input value must be a positive integer. Input value: {number}" raise TypeError(msg) return is_prime(number) and is_prime(2 * number + 1) def is_safe_prime(number: int) -> bool: if not isinstance(number, int) or number < 1: msg = f"Input value must be a positive integer. Input value: {number}" raise TypeError(msg) return (number - 1) % 2 == 0 and is_prime(number) and is_prime((number - 1) // 2) if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -1,8 +1,36 @@+""" +A Sophie Germain prime is any prime p, where 2p + 1 is also prime. +The second number, 2p + 1 is called a safe prime. + +Examples of Germain primes include: 2, 3, 5, 11, 23 + +Their corresponding safe primes: 5, 7, 11, 23, 47 +https://en.wikipedia.org/wiki/Safe_and_Sophie_Germain_primes +""" from maths.prime_check import is_prime def is_germain_prime(number: int) -> bool: + """Checks if input number and 2*number + 1 are prime. + + >>> is_germain_prime(3) + True + >>> is_germain_prime(11) + True + >>> is_germain_prime(4) + False + >>> is_germain_prime(23) + True + >>> is_germain_prime(13) + False + >>> is_germain_prime(20) + False + >>> is_germain_prime('abc') + Traceback (most recent call last): + ... + TypeError: Input value must be a positive integer. Input value: abc + """ if not isinstance(number, int) or number < 1: msg = f"Input value must be a positive integer. Input value: {number}" raise TypeError(msg) @@ -11,6 +39,26 @@ def is_safe_prime(number: int) -> bool: + """Checks if input number and (number - 1)/2 are prime. + The smallest safe prime is 5, with the Germain prime is 2. + + >>> is_safe_prime(5) + True + >>> is_safe_prime(11) + True + >>> is_safe_prime(1) + False + >>> is_safe_prime(2) + False + >>> is_safe_prime(3) + False + >>> is_safe_prime(47) + True + >>> is_safe_prime('abc') + Traceback (most recent call last): + ... + TypeError: Input value must be a positive integer. Input value: abc + """ if not isinstance(number, int) or number < 1: msg = f"Input value must be a positive integer. Input value: {number}" raise TypeError(msg) @@ -21,4 +69,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/germain_primes.py
Insert docstrings into my code
#!/usr/bin/env python3 from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def calculate_prob(text: str) -> None: single_char_strings, two_char_strings = analyze_text(text) my_alphas = list(" " + ascii_lowercase) # what is our total sum of probabilities. all_sum = sum(single_char_strings.values()) # one length string my_fir_sum = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: my_str = single_char_strings[ch] prob = my_str / all_sum my_fir_sum += prob * math.log2(prob) # entropy formula. # print entropy print(f"{round(-1 * my_fir_sum):.1f}") # two len string all_sum = sum(two_char_strings.values()) my_sec_sum = 0 # for each alpha (two in size) calculate entropy. for ch0 in my_alphas: for ch1 in my_alphas: sequence = ch0 + ch1 if sequence in two_char_strings: my_str = two_char_strings[sequence] prob = int(my_str) / all_sum my_sec_sum += prob * math.log2(prob) # print second entropy print(f"{round(-1 * my_sec_sum):.1f}") # print the difference between them print(f"{round((-1 * my_sec_sum) - (-1 * my_fir_sum)):.1f}") def analyze_text(text: str) -> tuple[dict, dict]: single_char_strings = Counter() # type: ignore[var-annotated] two_char_strings = Counter() # type: ignore[var-annotated] single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(len(text) - 1): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def main(): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python3 +""" +Implementation of entropy of information +https://en.wikipedia.org/wiki/Entropy_(information_theory) +""" from __future__ import annotations @@ -9,6 +13,47 @@ def calculate_prob(text: str) -> None: + """ + This method takes path and two dict as argument + and than calculates entropy of them. + :param dict: + :param dict: + :return: Prints + 1) Entropy of information based on 1 alphabet + 2) Entropy of information based on couples of 2 alphabet + 3) print Entropy of H(X n|Xn-1) + + Text from random books. Also, random quotes. + >>> text = ("Behind Winston's back the voice " + ... "from the telescreen was still " + ... "babbling and the overfulfilment") + >>> calculate_prob(text) + 4.0 + 6.0 + 2.0 + + >>> text = ("The Ministry of Truth—Minitrue, in Newspeak [Newspeak was the official" + ... "face in elegant lettering, the three") + >>> calculate_prob(text) + 4.0 + 5.0 + 1.0 + >>> text = ("Had repulsive dashwoods suspicion sincerity but advantage now him. " + ... "Remark easily garret nor nay. Civil those mrs enjoy shy fat merry. " + ... "You greatest jointure saw horrible. He private he on be imagine " + ... "suppose. Fertile beloved evident through no service elderly is. Blind " + ... "there if every no so at. Own neglected you preferred way sincerity " + ... "delivered his attempted. To of message cottage windows do besides " + ... "against uncivil. Delightful unreserved impossible few estimating " + ... "men favourable see entreaties. She propriety immediate was improving. " + ... "He or entrance humoured likewise moderate. Much nor game son say " + ... "feel. Fat make met can must form into gate. Me we offending prevailed " + ... "discovery.") + >>> calculate_prob(text) + 4.0 + 7.0 + 3.0 + """ single_char_strings, two_char_strings = analyze_text(text) my_alphas = list(" " + ascii_lowercase) # what is our total sum of probabilities. @@ -46,6 +91,11 @@ def analyze_text(text: str) -> tuple[dict, dict]: + """ + Convert text input into two dicts of counts. + The first dictionary stores the frequency of single character strings. + The second dictionary stores the frequency of two character strings. + """ single_char_strings = Counter() # type: ignore[var-annotated] two_char_strings = Counter() # type: ignore[var-annotated] single_char_strings[text[-1]] += 1 @@ -79,4 +129,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/entropy.py
Generate docstrings for this script
from __future__ import annotations import typing from collections.abc import Iterable import numpy as np Vector = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 VectorOut = typing.Union[np.float64, int, float] # noqa: UP007 def euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut: return np.sqrt(np.sum((np.asarray(vector_1) - np.asarray(vector_2)) ** 2)) def euclidean_distance_no_np(vector_1: Vector, vector_2: Vector) -> VectorOut: return sum((v1 - v2) ** 2 for v1, v2 in zip(vector_1, vector_2)) ** (1 / 2) if __name__ == "__main__": def benchmark() -> None: from timeit import timeit print("Without Numpy") print( timeit( "euclidean_distance_no_np([1, 2, 3], [4, 5, 6])", number=10000, globals=globals(), ) ) print("With Numpy") print( timeit( "euclidean_distance([1, 2, 3], [4, 5, 6])", number=10000, globals=globals(), ) ) benchmark()
--- +++ @@ -10,16 +10,39 @@ def euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut: + """ + Calculate the distance between the two endpoints of two vectors. + A vector is defined as a list, tuple, or numpy 1D array. + >>> float(euclidean_distance((0, 0), (2, 2))) + 2.8284271247461903 + >>> float(euclidean_distance(np.array([0, 0, 0]), np.array([2, 2, 2]))) + 3.4641016151377544 + >>> float(euclidean_distance(np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]))) + 8.0 + >>> float(euclidean_distance([1, 2, 3, 4], [5, 6, 7, 8])) + 8.0 + """ return np.sqrt(np.sum((np.asarray(vector_1) - np.asarray(vector_2)) ** 2)) def euclidean_distance_no_np(vector_1: Vector, vector_2: Vector) -> VectorOut: + """ + Calculate the distance between the two endpoints of two vectors without numpy. + A vector is defined as a list, tuple, or numpy 1D array. + >>> euclidean_distance_no_np((0, 0), (2, 2)) + 2.8284271247461903 + >>> euclidean_distance_no_np([1, 2, 3, 4], [5, 6, 7, 8]) + 8.0 + """ return sum((v1 - v2) ** 2 for v1, v2 in zip(vector_1, vector_2)) ** (1 / 2) if __name__ == "__main__": def benchmark() -> None: + """ + Benchmarks + """ from timeit import timeit print("Without Numpy") @@ -39,4 +62,4 @@ ) ) - benchmark()+ benchmark()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/euclidean_distance.py
Write beginner-friendly docstrings
def double_factorial_recursive(n: int) -> int: if not isinstance(n, int): raise ValueError("double_factorial_recursive() only accepts integral values") if n < 0: raise ValueError("double_factorial_recursive() not defined for negative values") return 1 if n <= 1 else n * double_factorial_recursive(n - 2) def double_factorial_iterative(num: int) -> int: if not isinstance(num, int): raise ValueError("double_factorial_iterative() only accepts integral values") if num < 0: raise ValueError("double_factorial_iterative() not defined for negative values") value = 1 for i in range(num, 0, -2): value *= i return value if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,4 +1,23 @@ def double_factorial_recursive(n: int) -> int: + """ + Compute double factorial using recursive method. + Recursion can be costly for large numbers. + + To learn about the theory behind this algorithm: + https://en.wikipedia.org/wiki/Double_factorial + + >>> from math import prod + >>> all(double_factorial_recursive(i) == prod(range(i, 0, -2)) for i in range(20)) + True + >>> double_factorial_recursive(0.1) + Traceback (most recent call last): + ... + ValueError: double_factorial_recursive() only accepts integral values + >>> double_factorial_recursive(-1) + Traceback (most recent call last): + ... + ValueError: double_factorial_recursive() not defined for negative values + """ if not isinstance(n, int): raise ValueError("double_factorial_recursive() only accepts integral values") if n < 0: @@ -7,6 +26,24 @@ def double_factorial_iterative(num: int) -> int: + """ + Compute double factorial using iterative method. + + To learn about the theory behind this algorithm: + https://en.wikipedia.org/wiki/Double_factorial + + >>> from math import prod + >>> all(double_factorial_iterative(i) == prod(range(i, 0, -2)) for i in range(20)) + True + >>> double_factorial_iterative(0.1) + Traceback (most recent call last): + ... + ValueError: double_factorial_iterative() only accepts integral values + >>> double_factorial_iterative(-1) + Traceback (most recent call last): + ... + ValueError: double_factorial_iterative() not defined for negative values + """ if not isinstance(num, int): raise ValueError("double_factorial_iterative() only accepts integral values") if num < 0: @@ -20,4 +57,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/double_factorial.py
Create simple docstrings for beginners
# @Author: S. Sharma <silentcat> # @Date: 2019-02-25T12:08:53-06:00 # @Email: silentcat@protonmail.com # @Last modified by: pikulet # @Last modified time: 2020-10-02 from __future__ import annotations import sys def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: # base cases if abs(a) == 1: return a, 0 elif abs(b) == 1: return 0, b old_remainder, remainder = a, b old_coeff_a, coeff_a = 1, 0 old_coeff_b, coeff_b = 0, 1 while remainder != 0: quotient = old_remainder // remainder old_remainder, remainder = remainder, old_remainder - quotient * remainder old_coeff_a, coeff_a = coeff_a, old_coeff_a - quotient * coeff_a old_coeff_b, coeff_b = coeff_b, old_coeff_b - quotient * coeff_b # sign correction for negative numbers if a < 0: old_coeff_a = -old_coeff_a if b < 0: old_coeff_b = -old_coeff_b return old_coeff_a, old_coeff_b def main(): if len(sys.argv) < 3: print("2 integer arguments required") return 1 a = int(sys.argv[1]) b = int(sys.argv[2]) print(extended_euclidean_algorithm(a, b)) return 0 if __name__ == "__main__": raise SystemExit(main())
--- +++ @@ -1,3 +1,11 @@+""" +Extended Euclidean Algorithm. + +Finds 2 numbers a and b such that it satisfies +the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) + +https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm +""" # @Author: S. Sharma <silentcat> # @Date: 2019-02-25T12:08:53-06:00 @@ -10,6 +18,34 @@ def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: + """ + Extended Euclidean Algorithm. + + Finds 2 numbers a and b such that it satisfies + the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) + + >>> extended_euclidean_algorithm(1, 24) + (1, 0) + + >>> extended_euclidean_algorithm(8, 14) + (2, -1) + + >>> extended_euclidean_algorithm(240, 46) + (-9, 47) + + >>> extended_euclidean_algorithm(1, -4) + (1, 0) + + >>> extended_euclidean_algorithm(-2, -4) + (-1, 0) + + >>> extended_euclidean_algorithm(0, -4) + (0, -1) + + >>> extended_euclidean_algorithm(2, 0) + (1, 0) + + """ # base cases if abs(a) == 1: return a, 0 @@ -36,6 +72,7 @@ def main(): + """Call Extended Euclidean Algorithm.""" if len(sys.argv) < 3: print("2 integer arguments required") return 1 @@ -46,4 +83,4 @@ if __name__ == "__main__": - raise SystemExit(main())+ raise SystemExit(main())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/extended_euclidean_algorithm.py
Add docstrings for utility scripts
from math import factorial def binomial_distribution(successes: int, trials: int, prob: float) -> float: if successes > trials: raise ValueError("""successes must be lower or equal to trials""") if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integers") if not isinstance(successes, int) or not isinstance(trials, int): raise ValueError("the function is defined for non-negative integers") if not 0 < prob < 1: raise ValueError("prob has to be in range of 1 - 0") probability = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! coefficient = float(factorial(trials)) coefficient /= factorial(successes) * factorial(trials - successes) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("Probability of 2 successes out of 4 trails") print("with probability of 0.75 is:", end=" ") print(binomial_distribution(2, 4, 0.75))
--- +++ @@ -1,27 +1,41 @@- -from math import factorial - - -def binomial_distribution(successes: int, trials: int, prob: float) -> float: - if successes > trials: - raise ValueError("""successes must be lower or equal to trials""") - if trials < 0 or successes < 0: - raise ValueError("the function is defined for non-negative integers") - if not isinstance(successes, int) or not isinstance(trials, int): - raise ValueError("the function is defined for non-negative integers") - if not 0 < prob < 1: - raise ValueError("prob has to be in range of 1 - 0") - probability = (prob**successes) * ((1 - prob) ** (trials - successes)) - # Calculate the binomial coefficient: n! / k!(n-k)! - coefficient = float(factorial(trials)) - coefficient /= factorial(successes) * factorial(trials - successes) - return probability * coefficient - - -if __name__ == "__main__": - from doctest import testmod - - testmod() - print("Probability of 2 successes out of 4 trails") - print("with probability of 0.75 is:", end=" ") - print(binomial_distribution(2, 4, 0.75))+"""For more information about the Binomial Distribution - +https://en.wikipedia.org/wiki/Binomial_distribution""" + +from math import factorial + + +def binomial_distribution(successes: int, trials: int, prob: float) -> float: + """ + Return probability of k successes out of n tries, with p probability for one + success + + The function uses the factorial function in order to calculate the binomial + coefficient + + >>> binomial_distribution(3, 5, 0.7) + 0.30870000000000003 + >>> binomial_distribution (2, 4, 0.5) + 0.375 + """ + if successes > trials: + raise ValueError("""successes must be lower or equal to trials""") + if trials < 0 or successes < 0: + raise ValueError("the function is defined for non-negative integers") + if not isinstance(successes, int) or not isinstance(trials, int): + raise ValueError("the function is defined for non-negative integers") + if not 0 < prob < 1: + raise ValueError("prob has to be in range of 1 - 0") + probability = (prob**successes) * ((1 - prob) ** (trials - successes)) + # Calculate the binomial coefficient: n! / k!(n-k)! + coefficient = float(factorial(trials)) + coefficient /= factorial(successes) * factorial(trials - successes) + return probability * coefficient + + +if __name__ == "__main__": + from doctest import testmod + + testmod() + print("Probability of 2 successes out of 4 trails") + print("with probability of 0.75 is:", end=" ") + print(binomial_distribution(2, 4, 0.75))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/binomial_distribution.py
Annotate my code with docstrings
def compute_geometric_mean(*args: int) -> float: product = 1 for number in args: if not isinstance(number, int) and not isinstance(number, float): raise TypeError("Not a Number") product *= number # Cannot calculate the even root for negative product. # Frequently they are restricted to being positive. if product < 0 and len(args) % 2 == 0: raise ArithmeticError("Cannot Compute Geometric Mean for these numbers.") mean = abs(product) ** (1 / len(args)) # Since python calculates complex roots for negative products with odd roots. if product < 0: mean = -mean # Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996 possible_mean = float(round(mean)) # To check if the rounded number is actually the mean. if possible_mean ** len(args) == product: mean = possible_mean return mean if __name__ == "__main__": from doctest import testmod testmod(name="compute_geometric_mean") print(compute_geometric_mean(-3, -27))
--- +++ @@ -1,6 +1,32 @@+""" +The Geometric Mean of n numbers is defined as the n-th root of the product +of those numbers. It is used to measure the central tendency of the numbers. +https://en.wikipedia.org/wiki/Geometric_mean +""" def compute_geometric_mean(*args: int) -> float: + """ + Return the geometric mean of the argument numbers. + >>> compute_geometric_mean(2,8) + 4.0 + >>> compute_geometric_mean('a', 4) + Traceback (most recent call last): + ... + TypeError: Not a Number + >>> compute_geometric_mean(5, 125) + 25.0 + >>> compute_geometric_mean(1, 0) + 0.0 + >>> compute_geometric_mean(1, 5, 25, 5) + 5.0 + >>> compute_geometric_mean(2, -2) + Traceback (most recent call last): + ... + ArithmeticError: Cannot Compute Geometric Mean for these numbers. + >>> compute_geometric_mean(-5, 25, 1) + -5.0 + """ product = 1 for number in args: if not isinstance(number, int) and not isinstance(number, float): @@ -26,4 +52,4 @@ from doctest import testmod testmod(name="compute_geometric_mean") - print(compute_geometric_mean(-3, -27))+ print(compute_geometric_mean(-3, -27))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/geometric_mean.py
Create Google-style docstrings for my code
import functools from collections.abc import Iterator from math import sqrt from time import time import numpy as np from numpy import ndarray def time_func(func, *args, **kwargs): start = time() output = func(*args, **kwargs) end = time() if int(end - start) > 0: print(f"{func.__name__} runtime: {(end - start):0.4f} s") else: print(f"{func.__name__} runtime: {(end - start) * 1000:0.4f} ms") return output def fib_iterative_yield(n: int) -> Iterator[int]: if n < 0: raise ValueError("n is negative") a, b = 0, 1 yield a for _ in range(n): yield b a, b = b, a + b def fib_iterative(n: int) -> list[int]: if n < 0: raise ValueError("n is negative") if n == 0: return [0] fib = [0, 1] for _ in range(n - 1): fib.append(fib[-1] + fib[-2]) return fib def fib_recursive(n: int) -> list[int]: def fib_recursive_term(i: int) -> int: if i < 0: raise ValueError("n is negative") if i < 2: return i return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) if n < 0: raise ValueError("n is negative") return [fib_recursive_term(i) for i in range(n + 1)] def fib_recursive_cached(n: int) -> list[int]: @functools.cache def fib_recursive_term(i: int) -> int: if i < 0: raise ValueError("n is negative") if i < 2: return i return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) if n < 0: raise ValueError("n is negative") return [fib_recursive_term(i) for i in range(n + 1)] def fib_memoization(n: int) -> list[int]: if n < 0: raise ValueError("n is negative") # Cache must be outside recursive function # other it will reset every time it calls itself. cache: dict[int, int] = {0: 0, 1: 1, 2: 1} # Prefilled cache def rec_fn_memoized(num: int) -> int: if num in cache: return cache[num] value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2) cache[num] = value return value return [rec_fn_memoized(i) for i in range(n + 1)] def fib_binet(n: int) -> list[int]: if n < 0: raise ValueError("n is negative") if n >= 1475: raise ValueError("n is too large") sqrt_5 = sqrt(5) phi = (1 + sqrt_5) / 2 return [round(phi**i / sqrt_5) for i in range(n + 1)] def matrix_pow_np(m: ndarray, power: int) -> ndarray: result = np.array([[1, 0], [0, 1]], dtype=int) # Identity Matrix base = m if power < 0: # Negative power is not allowed raise ValueError("power is negative") while power: if power % 2 == 1: result = np.dot(result, base) base = np.dot(base, base) power //= 2 return result def fib_matrix_np(n: int) -> int: if n < 0: raise ValueError("n is negative") if n == 0: return 0 m = np.array([[1, 1], [1, 0]], dtype=int) result = matrix_pow_np(m, n - 1) return int(result[0, 0]) if __name__ == "__main__": from doctest import testmod testmod() # Time on an M1 MacBook Pro -- Fastest to slowest num = 30 time_func(fib_iterative_yield, num) # 0.0012 ms time_func(fib_iterative, num) # 0.0031 ms time_func(fib_binet, num) # 0.0062 ms time_func(fib_memoization, num) # 0.0100 ms time_func(fib_recursive_cached, num) # 0.0153 ms time_func(fib_recursive, num) # 257.0910 ms time_func(fib_matrix_np, num) # 0.0000 ms
--- +++ @@ -1,3 +1,18 @@+""" +Calculates the Fibonacci sequence using iteration, recursion, memoization, +and a simplified form of Binet's formula + +NOTE 1: the iterative, recursive, memoization functions are more accurate than +the Binet's formula function because the Binet formula function uses floats + +NOTE 2: the Binet's formula function is much more limited in the size of inputs +that it can handle due to the size limitations of Python floats +NOTE 3: the matrix function is the fastest and most memory efficient for large n + + +See benchmark numbers in __main__ for performance comparisons/ +https://en.wikipedia.org/wiki/Fibonacci_number for more information +""" import functools from collections.abc import Iterator @@ -9,6 +24,9 @@ def time_func(func, *args, **kwargs): + """ + Times the execution of a function with parameters + """ start = time() output = func(*args, **kwargs) end = time() @@ -20,6 +38,21 @@ def fib_iterative_yield(n: int) -> Iterator[int]: + """ + Calculates the first n (1-indexed) Fibonacci numbers using iteration with yield + >>> list(fib_iterative_yield(0)) + [0] + >>> tuple(fib_iterative_yield(1)) + (0, 1) + >>> tuple(fib_iterative_yield(5)) + (0, 1, 1, 2, 3, 5) + >>> tuple(fib_iterative_yield(10)) + (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55) + >>> tuple(fib_iterative_yield(-1)) + Traceback (most recent call last): + ... + ValueError: n is negative + """ if n < 0: raise ValueError("n is negative") a, b = 0, 1 @@ -30,6 +63,21 @@ def fib_iterative(n: int) -> list[int]: + """ + Calculates the first n (0-indexed) Fibonacci numbers using iteration + >>> fib_iterative(0) + [0] + >>> fib_iterative(1) + [0, 1] + >>> fib_iterative(5) + [0, 1, 1, 2, 3, 5] + >>> fib_iterative(10) + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + >>> fib_iterative(-1) + Traceback (most recent call last): + ... + ValueError: n is negative + """ if n < 0: raise ValueError("n is negative") if n == 0: @@ -41,8 +89,38 @@ def fib_recursive(n: int) -> list[int]: + """ + Calculates the first n (0-indexed) Fibonacci numbers using recursion + >>> fib_recursive(0) + [0] + >>> fib_recursive(1) + [0, 1] + >>> fib_recursive(5) + [0, 1, 1, 2, 3, 5] + >>> fib_recursive(10) + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + >>> fib_recursive(-1) + Traceback (most recent call last): + ... + ValueError: n is negative + """ def fib_recursive_term(i: int) -> int: + """ + Calculates the i-th (0-indexed) Fibonacci number using recursion + >>> fib_recursive_term(0) + 0 + >>> fib_recursive_term(1) + 1 + >>> fib_recursive_term(5) + 5 + >>> fib_recursive_term(10) + 55 + >>> fib_recursive_term(-1) + Traceback (most recent call last): + ... + ValueError: n is negative + """ if i < 0: raise ValueError("n is negative") if i < 2: @@ -55,9 +133,27 @@ def fib_recursive_cached(n: int) -> list[int]: + """ + Calculates the first n (0-indexed) Fibonacci numbers using recursion + >>> fib_recursive_cached(0) + [0] + >>> fib_recursive_cached(1) + [0, 1] + >>> fib_recursive_cached(5) + [0, 1, 1, 2, 3, 5] + >>> fib_recursive_cached(10) + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + >>> fib_recursive_cached(-1) + Traceback (most recent call last): + ... + ValueError: n is negative + """ @functools.cache def fib_recursive_term(i: int) -> int: + """ + Calculates the i-th (0-indexed) Fibonacci number using recursion + """ if i < 0: raise ValueError("n is negative") if i < 2: @@ -70,6 +166,21 @@ def fib_memoization(n: int) -> list[int]: + """ + Calculates the first n (0-indexed) Fibonacci numbers using memoization + >>> fib_memoization(0) + [0] + >>> fib_memoization(1) + [0, 1] + >>> fib_memoization(5) + [0, 1, 1, 2, 3, 5] + >>> fib_memoization(10) + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + >>> fib_memoization(-1) + Traceback (most recent call last): + ... + ValueError: n is negative + """ if n < 0: raise ValueError("n is negative") # Cache must be outside recursive function @@ -88,6 +199,33 @@ def fib_binet(n: int) -> list[int]: + """ + Calculates the first n (0-indexed) Fibonacci numbers using a simplified form + of Binet's formula: + https://en.m.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding + + NOTE 1: this function diverges from fib_iterative at around n = 71, likely + due to compounding floating-point arithmetic errors + + NOTE 2: this function doesn't accept n >= 1475 because it overflows + thereafter due to the size limitations of Python floats + >>> fib_binet(0) + [0] + >>> fib_binet(1) + [0, 1] + >>> fib_binet(5) + [0, 1, 1, 2, 3, 5] + >>> fib_binet(10) + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + >>> fib_binet(-1) + Traceback (most recent call last): + ... + ValueError: n is negative + >>> fib_binet(1475) + Traceback (most recent call last): + ... + ValueError: n is too large + """ if n < 0: raise ValueError("n is negative") if n >= 1475: @@ -98,6 +236,37 @@ def matrix_pow_np(m: ndarray, power: int) -> ndarray: + """ + Raises a matrix to the power of 'power' using binary exponentiation. + + Args: + m: Matrix as a numpy array. + power: The power to which the matrix is to be raised. + + Returns: + The matrix raised to the power. + + Raises: + ValueError: If power is negative. + + >>> m = np.array([[1, 1], [1, 0]], dtype=int) + >>> matrix_pow_np(m, 0) # Identity matrix when raised to the power of 0 + array([[1, 0], + [0, 1]]) + + >>> matrix_pow_np(m, 1) # Same matrix when raised to the power of 1 + array([[1, 1], + [1, 0]]) + + >>> matrix_pow_np(m, 5) + array([[8, 5], + [5, 3]]) + + >>> matrix_pow_np(m, -1) + Traceback (most recent call last): + ... + ValueError: power is negative + """ result = np.array([[1, 0], [0, 1]], dtype=int) # Identity Matrix base = m if power < 0: # Negative power is not allowed @@ -111,6 +280,33 @@ def fib_matrix_np(n: int) -> int: + """ + Calculates the n-th Fibonacci number using matrix exponentiation. + https://www.nayuki.io/page/fast-fibonacci-algorithms#:~:text= + Summary:%20The%20two%20fast%20Fibonacci%20algorithms%20are%20matrix + + Args: + n: Fibonacci sequence index + + Returns: + The n-th Fibonacci number. + + Raises: + ValueError: If n is negative. + + >>> fib_matrix_np(0) + 0 + >>> fib_matrix_np(1) + 1 + >>> fib_matrix_np(5) + 5 + >>> fib_matrix_np(10) + 55 + >>> fib_matrix_np(-1) + Traceback (most recent call last): + ... + ValueError: n is negative + """ if n < 0: raise ValueError("n is negative") if n == 0: @@ -133,4 +329,4 @@ time_func(fib_memoization, num) # 0.0100 ms time_func(fib_recursive_cached, num) # 0.0153 ms time_func(fib_recursive, num) # 257.0910 ms - time_func(fib_matrix_np, num) # 0.0000 ms+ time_func(fib_matrix_np, num) # 0.0000 ms
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/fibonacci.py
Create documentation strings for testing functions
def factorial(number: int) -> int: if number != int(number): raise ValueError("factorial() only accepts integral values") if number < 0: raise ValueError("factorial() not defined for negative values") value = 1 for i in range(1, number + 1): value *= i return value def factorial_recursive(n: int) -> int: if not isinstance(n, int): raise ValueError("factorial_recursive() only accepts integral values") if n < 0: raise ValueError("factorial_recursive() not defined for negative values") return 1 if n in {0, 1} else n * factorial_recursive(n - 1) if __name__ == "__main__": import doctest doctest.testmod() n = int(input("Enter a positive integer: ").strip() or 0) print(f"factorial{n} is {factorial(n)}")
--- +++ @@ -1,6 +1,30 @@+""" +Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial +""" def factorial(number: int) -> int: + """ + Calculate the factorial of specified number (n!). + + >>> import math + >>> all(factorial(i) == math.factorial(i) for i in range(20)) + True + >>> factorial(0.1) + Traceback (most recent call last): + ... + ValueError: factorial() only accepts integral values + >>> factorial(-1) + Traceback (most recent call last): + ... + ValueError: factorial() not defined for negative values + >>> factorial(1) + 1 + >>> factorial(6) + 720 + >>> factorial(0) + 1 + """ if number != int(number): raise ValueError("factorial() only accepts integral values") if number < 0: @@ -12,6 +36,22 @@ def factorial_recursive(n: int) -> int: + """ + Calculate the factorial of a positive integer + https://en.wikipedia.org/wiki/Factorial + + >>> import math + >>> all(factorial_recursive(i) == math.factorial(i) for i in range(20)) + True + >>> factorial_recursive(0.1) + Traceback (most recent call last): + ... + ValueError: factorial_recursive() only accepts integral values + >>> factorial_recursive(-1) + Traceback (most recent call last): + ... + ValueError: factorial_recursive() not defined for negative values + """ if not isinstance(n, int): raise ValueError("factorial_recursive() only accepts integral values") if n < 0: @@ -25,4 +65,4 @@ doctest.testmod() n = int(input("Enter a positive integer: ").strip() or 0) - print(f"factorial{n} is {factorial(n)}")+ print(f"factorial{n} is {factorial(n)}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/factorial.py
Document this script properly
def karatsuba(a: int, b: int) -> int: if len(str(a)) == 1 or len(str(b)) == 1: return a * b m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
--- +++ @@ -1,6 +1,13 @@+"""Multiply two numbers using Karatsuba algorithm""" def karatsuba(a: int, b: int) -> int: + """ + >>> karatsuba(15463, 23489) == 15463 * 23489 + True + >>> karatsuba(3, 9) == 3 * 9 + True + """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b @@ -22,4 +29,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/karatsuba.py
Generate consistent docstrings
from __future__ import annotations def find_max_iterative(nums: list[int | float]) -> int | float: if len(nums) == 0: raise ValueError("find_max_iterative() arg is an empty sequence") max_num = nums[0] for x in nums: if x > max_num: # noqa: PLR1730 max_num = x return max_num # Divide and Conquer algorithm def find_max_recursive(nums: list[int | float], left: int, right: int) -> int | float: if len(nums) == 0: raise ValueError("find_max_recursive() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_max = find_max_recursive(nums, left, mid) # find max in range[left, mid] right_max = find_max_recursive( nums, mid + 1, right ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
--- +++ @@ -2,6 +2,20 @@ def find_max_iterative(nums: list[int | float]) -> int | float: + """ + >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): + ... find_max_iterative(nums) == max(nums) + True + True + True + True + >>> find_max_iterative([2, 4, 9, 7, 19, 94, 5]) + 94 + >>> find_max_iterative([]) + Traceback (most recent call last): + ... + ValueError: find_max_iterative() arg is an empty sequence + """ if len(nums) == 0: raise ValueError("find_max_iterative() arg is an empty sequence") max_num = nums[0] @@ -13,6 +27,37 @@ # Divide and Conquer algorithm def find_max_recursive(nums: list[int | float], left: int, right: int) -> int | float: + """ + find max value in list + :param nums: contains elements + :param left: index of first element + :param right: index of last element + :return: max in nums + + >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): + ... find_max_recursive(nums, 0, len(nums) - 1) == max(nums) + True + True + True + True + >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] + >>> find_max_recursive(nums, 0, len(nums) - 1) == max(nums) + True + >>> find_max_recursive([], 0, 0) + Traceback (most recent call last): + ... + ValueError: find_max_recursive() arg is an empty sequence + >>> find_max_recursive(nums, 0, len(nums)) == max(nums) + Traceback (most recent call last): + ... + IndexError: list index out of range + >>> find_max_recursive(nums, -len(nums), -1) == max(nums) + True + >>> find_max_recursive(nums, -len(nums) - 1, -1) == max(nums) + Traceback (most recent call last): + ... + IndexError: list index out of range + """ if len(nums) == 0: raise ValueError("find_max_recursive() arg is an empty sequence") if ( @@ -36,4 +81,4 @@ if __name__ == "__main__": import doctest - doctest.testmod(verbose=True)+ doctest.testmod(verbose=True)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/find_max.py
Document this code for team use
import unittest from timeit import timeit from maths.greatest_common_divisor import greatest_common_divisor def least_common_multiple_slow(first_num: int, second_num: int) -> int: max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (common_mult % second_num > 0): common_mult += max_num return common_mult def least_common_multiple_fast(first_num: int, second_num: int) -> int: return first_num // greatest_common_divisor(first_num, second_num) * second_num def benchmark(): setup = ( "from __main__ import least_common_multiple_slow, least_common_multiple_fast" ) print( "least_common_multiple_slow():", timeit("least_common_multiple_slow(1000, 999)", setup=setup), ) print( "least_common_multiple_fast():", timeit("least_common_multiple_fast(1000, 999)", setup=setup), ) class TestLeastCommonMultiple(unittest.TestCase): test_inputs = ( (10, 20), (13, 15), (4, 31), (10, 42), (43, 34), (5, 12), (12, 25), (10, 25), (6, 9), ) expected_results = (20, 195, 124, 210, 1462, 60, 300, 50, 18) def test_lcm_function(self): for i, (first_num, second_num) in enumerate(self.test_inputs): slow_result = least_common_multiple_slow(first_num, second_num) fast_result = least_common_multiple_fast(first_num, second_num) with self.subTest(i=i): assert slow_result == self.expected_results[i] assert fast_result == self.expected_results[i] if __name__ == "__main__": benchmark() unittest.main()
--- +++ @@ -5,6 +5,16 @@ def least_common_multiple_slow(first_num: int, second_num: int) -> int: + """ + Find the least common multiple of two numbers. + + Learn more: https://en.wikipedia.org/wiki/Least_common_multiple + + >>> least_common_multiple_slow(5, 2) + 10 + >>> least_common_multiple_slow(12, 76) + 228 + """ max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (common_mult % second_num > 0): @@ -13,6 +23,14 @@ def least_common_multiple_fast(first_num: int, second_num: int) -> int: + """ + Find the least common multiple of two numbers. + https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor + >>> least_common_multiple_fast(5,2) + 10 + >>> least_common_multiple_fast(12,76) + 228 + """ return first_num // greatest_common_divisor(first_num, second_num) * second_num @@ -55,4 +73,4 @@ if __name__ == "__main__": benchmark() - unittest.main()+ unittest.main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/least_common_multiple.py
Add docstrings to existing functions
def floor(x: float) -> int: return int(x) if x - int(x) >= 0 else int(x) - 1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,10 +1,22 @@+""" +https://en.wikipedia.org/wiki/Floor_and_ceiling_functions +""" def floor(x: float) -> int: + """ + Return the floor of x as an Integral. + :param x: the number + :return: the largest integer <= x. + >>> import math + >>> all(floor(n) == math.floor(n) for n + ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) + True + """ return int(x) if x - int(x) >= 0 else int(x) - 1 if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/floor.py
Generate docstrings for script automation
import math from timeit import timeit def num_digits(n: int) -> int: if not isinstance(n, int): raise TypeError("Input must be an integer") digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: if not isinstance(n, int): raise TypeError("Input must be an integer") return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: if not isinstance(n, int): raise TypeError("Input must be an integer") return len(str(abs(n))) def benchmark() -> None: from collections.abc import Callable def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") print(f"{call}: {func(value)} -- {timing} seconds") for value in (262144, 1125899906842624, 1267650600228229401496703205376): for func in (num_digits, num_digits_fast, num_digits_faster): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
--- +++ @@ -3,6 +3,24 @@ def num_digits(n: int) -> int: + """ + Find the number of digits in a number. + + >>> num_digits(12345) + 5 + >>> num_digits(123) + 3 + >>> num_digits(0) + 1 + >>> num_digits(-1) + 1 + >>> num_digits(-123456) + 6 + >>> num_digits('123') # Raises a TypeError for non-integer input + Traceback (most recent call last): + ... + TypeError: Input must be an integer + """ if not isinstance(n, int): raise TypeError("Input must be an integer") @@ -18,6 +36,25 @@ def num_digits_fast(n: int) -> int: + """ + Find the number of digits in a number. + abs() is used as logarithm for negative numbers is not defined. + + >>> num_digits_fast(12345) + 5 + >>> num_digits_fast(123) + 3 + >>> num_digits_fast(0) + 1 + >>> num_digits_fast(-1) + 1 + >>> num_digits_fast(-123456) + 6 + >>> num_digits('123') # Raises a TypeError for non-integer input + Traceback (most recent call last): + ... + TypeError: Input must be an integer + """ if not isinstance(n, int): raise TypeError("Input must be an integer") @@ -26,6 +63,25 @@ def num_digits_faster(n: int) -> int: + """ + Find the number of digits in a number. + abs() is used for negative numbers + + >>> num_digits_faster(12345) + 5 + >>> num_digits_faster(123) + 3 + >>> num_digits_faster(0) + 1 + >>> num_digits_faster(-1) + 1 + >>> num_digits_faster(-123456) + 6 + >>> num_digits('123') # Raises a TypeError for non-integer input + Traceback (most recent call last): + ... + TypeError: Input must be an integer + """ if not isinstance(n, int): raise TypeError("Input must be an integer") @@ -34,6 +90,9 @@ def benchmark() -> None: + """ + Benchmark multiple functions, with three different length int values. + """ from collections.abc import Callable def benchmark_a_function(func: Callable, value: int) -> None: @@ -51,4 +110,4 @@ import doctest doctest.testmod() - benchmark()+ benchmark()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/number_of_digits.py
Generate docstrings with examples
from __future__ import annotations def find_median(nums: list[int | float]) -> float: div, mod = divmod(len(nums), 2) if mod: return nums[div] return (nums[div] + nums[(div) - 1]) / 2 def interquartile_range(nums: list[int | float]) -> float: if not nums: raise ValueError("The list is empty. Provide a non-empty list.") nums.sort() length = len(nums) div, mod = divmod(length, 2) q1 = find_median(nums[:div]) half_length = sum((div, mod)) q3 = find_median(nums[half_length:length]) return q3 - q1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,30 @@+""" +An implementation of interquartile range (IQR) which is a measure of statistical +dispersion, which is the spread of the data. + +The function takes the list of numeric values as input and returns the IQR. + +Script inspired by this Wikipedia article: +https://en.wikipedia.org/wiki/Interquartile_range +""" from __future__ import annotations def find_median(nums: list[int | float]) -> float: + """ + This is the implementation of the median. + :param nums: The list of numeric nums + :return: Median of the list + >>> find_median(nums=([1, 2, 2, 3, 4])) + 2 + >>> find_median(nums=([1, 2, 2, 3, 4, 4])) + 2.5 + >>> find_median(nums=([-1, 2, 0, 3, 4, -4])) + 1.5 + >>> find_median(nums=([1.1, 2.2, 2, 3.3, 4.4, 4])) + 2.65 + """ div, mod = divmod(len(nums), 2) if mod: return nums[div] @@ -10,6 +32,24 @@ def interquartile_range(nums: list[int | float]) -> float: + """ + Return the interquartile range for a list of numeric values. + :param nums: The list of numeric values. + :return: interquartile range + + >>> interquartile_range(nums=[4, 1, 2, 3, 2]) + 2.0 + >>> interquartile_range(nums = [-2, -7, -10, 9, 8, 4, -67, 45]) + 17.0 + >>> interquartile_range(nums = [-2.1, -7.1, -10.1, 9.1, 8.1, 4.1, -67.1, 45.1]) + 17.2 + >>> interquartile_range(nums = [0, 0, 0, 0, 0]) + 0.0 + >>> interquartile_range(nums=[]) + Traceback (most recent call last): + ... + ValueError: The list is empty. Provide a non-empty list. + """ if not nums: raise ValueError("The list is empty. Provide a non-empty list.") nums.sort() @@ -24,4 +64,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/interquartile_range.py
Document functions with detailed explanations
import struct def fast_inverse_sqrt(number: float) -> float: if number <= 0: raise ValueError("Input must be a positive number.") i = struct.unpack(">i", struct.pack(">f", number))[0] i = 0x5F3759DF - (i >> 1) y = struct.unpack(">f", struct.pack(">i", i))[0] return y * (1.5 - 0.5 * number * y * y) if __name__ == "__main__": from doctest import testmod testmod() # https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy from math import sqrt for i in range(5, 101, 5): print(f"{i:>3}: {(1 / sqrt(i)) - fast_inverse_sqrt(i):.5f}")
--- +++ @@ -1,8 +1,40 @@+""" +Fast inverse square root (1/sqrt(x)) using the Quake III algorithm. +Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root +Accuracy: https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy +""" import struct def fast_inverse_sqrt(number: float) -> float: + """ + Compute the fast inverse square root of a floating-point number using the famous + Quake III algorithm. + + :param float number: Input number for which to calculate the inverse square root. + :return float: The fast inverse square root of the input number. + + Example: + >>> fast_inverse_sqrt(10) + 0.3156857923527257 + >>> fast_inverse_sqrt(4) + 0.49915357479239103 + >>> fast_inverse_sqrt(4.1) + 0.4932849504615651 + >>> fast_inverse_sqrt(0) + Traceback (most recent call last): + ... + ValueError: Input must be a positive number. + >>> fast_inverse_sqrt(-1) + Traceback (most recent call last): + ... + ValueError: Input must be a positive number. + >>> from math import isclose, sqrt + >>> all(isclose(fast_inverse_sqrt(i), 1 / sqrt(i), rel_tol=0.00132) + ... for i in range(50, 60)) + True + """ if number <= 0: raise ValueError("Input must be a positive number.") i = struct.unpack(">i", struct.pack(">f", number))[0] @@ -19,4 +51,4 @@ from math import sqrt for i in range(5, 101, 5): - print(f"{i:>3}: {(1 / sqrt(i)) - fast_inverse_sqrt(i):.5f}")+ print(f"{i:>3}: {(1 / sqrt(i)) - fast_inverse_sqrt(i):.5f}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/fast_inverse_sqrt.py
Write Python docstrings for this snippet
import math from numpy import inf from scipy.integrate import quad def gamma_iterative(num: float) -> float: if num <= 0: raise ValueError("math domain error") return quad(integrand, 0, inf, args=(num))[0] def integrand(x: float, z: float) -> float: return math.pow(x, z - 1) * math.exp(-x) def gamma_recursive(num: float) -> float: if num <= 0: raise ValueError("math domain error") if num > 171.5: raise OverflowError("math range error") elif num - int(num) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer") elif num == 0.5: return math.sqrt(math.pi) else: return 1.0 if num == 1 else (num - 1) * gamma_recursive(num - 1) if __name__ == "__main__": from doctest import testmod testmod() num = 1.0 while num: num = float(input("Gamma of: ")) print(f"gamma_iterative({num}) = {gamma_iterative(num)}") print(f"gamma_recursive({num}) = {gamma_recursive(num)}") print("\nEnter 0 to exit...")
--- +++ @@ -1,3 +1,13 @@+""" +Gamma function is a very useful tool in math and physics. +It helps calculating complex integral in a convenient way. +for more info: https://en.wikipedia.org/wiki/Gamma_function +In mathematics, the gamma function is one commonly +used extension of the factorial function to complex numbers. +The gamma function is defined for all complex numbers except +the non-positive integers +Python's Standard Library math.gamma() function overflows around gamma(171.624). +""" import math @@ -6,6 +16,31 @@ def gamma_iterative(num: float) -> float: + """ + Calculates the value of Gamma function of num + where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...). + + >>> gamma_iterative(-1) + Traceback (most recent call last): + ... + ValueError: math domain error + >>> gamma_iterative(0) + Traceback (most recent call last): + ... + ValueError: math domain error + >>> gamma_iterative(9) + 40320.0 + >>> from math import gamma as math_gamma + >>> all(.99999999 < gamma_iterative(i) / math_gamma(i) <= 1.000000001 + ... for i in range(1, 50)) + True + >>> gamma_iterative(-1)/math_gamma(-1) <= 1.000000001 + Traceback (most recent call last): + ... + ValueError: math domain error + >>> gamma_iterative(3.3) - math_gamma(3.3) <= 0.00000001 + True + """ if num <= 0: raise ValueError("math domain error") @@ -17,6 +52,46 @@ def gamma_recursive(num: float) -> float: + """ + Calculates the value of Gamma function of num + where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...). + Implemented using recursion + Examples: + >>> from math import isclose, gamma as math_gamma + >>> gamma_recursive(0.5) + 1.7724538509055159 + >>> gamma_recursive(1) + 1.0 + >>> gamma_recursive(2) + 1.0 + >>> gamma_recursive(3.5) + 3.3233509704478426 + >>> gamma_recursive(171.5) + 9.483367566824795e+307 + >>> all(isclose(gamma_recursive(num), math_gamma(num)) + ... for num in (0.5, 2, 3.5, 171.5)) + True + >>> gamma_recursive(0) + Traceback (most recent call last): + ... + ValueError: math domain error + >>> gamma_recursive(-1.1) + Traceback (most recent call last): + ... + ValueError: math domain error + >>> gamma_recursive(-4) + Traceback (most recent call last): + ... + ValueError: math domain error + >>> gamma_recursive(172) + Traceback (most recent call last): + ... + OverflowError: math range error + >>> gamma_recursive(1.1) + Traceback (most recent call last): + ... + NotImplementedError: num must be an integer or a half-integer + """ if num <= 0: raise ValueError("math domain error") if num > 171.5: @@ -38,4 +113,4 @@ num = float(input("Gamma of: ")) print(f"gamma_iterative({num}) = {gamma_iterative(num)}") print(f"gamma_recursive({num}) = {gamma_recursive(num)}") - print("\nEnter 0 to exit...")+ print("\nEnter 0 to exit...")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/gamma.py
Write docstrings that follow conventions
def recursive_lucas_number(n_th_number: int) -> int: if not isinstance(n_th_number, int): raise TypeError("recursive_lucas_number accepts only integer arguments.") if n_th_number == 0: return 2 if n_th_number == 1: return 1 return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number( n_th_number - 2 ) def dynamic_lucas_number(n_th_number: int) -> int: if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 for _ in range(n_th_number): a, b = b, a + b return a if __name__ == "__main__": from doctest import testmod testmod() n = int(input("Enter the number of terms in lucas series:\n").strip()) print("Using recursive function to calculate lucas series:") print(" ".join(str(recursive_lucas_number(i)) for i in range(n))) print("\nUsing dynamic function to calculate lucas series:") print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))
--- +++ @@ -1,6 +1,24 @@+""" +https://en.wikipedia.org/wiki/Lucas_number +""" def recursive_lucas_number(n_th_number: int) -> int: + """ + Returns the nth lucas number + >>> recursive_lucas_number(1) + 1 + >>> recursive_lucas_number(20) + 15127 + >>> recursive_lucas_number(0) + 2 + >>> recursive_lucas_number(25) + 167761 + >>> recursive_lucas_number(-1.5) + Traceback (most recent call last): + ... + TypeError: recursive_lucas_number accepts only integer arguments. + """ if not isinstance(n_th_number, int): raise TypeError("recursive_lucas_number accepts only integer arguments.") if n_th_number == 0: @@ -14,6 +32,21 @@ def dynamic_lucas_number(n_th_number: int) -> int: + """ + Returns the nth lucas number + >>> dynamic_lucas_number(1) + 1 + >>> dynamic_lucas_number(20) + 15127 + >>> dynamic_lucas_number(0) + 2 + >>> dynamic_lucas_number(25) + 167761 + >>> dynamic_lucas_number(-1.5) + Traceback (most recent call last): + ... + TypeError: dynamic_lucas_number accepts only integer arguments. + """ if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 @@ -30,4 +63,4 @@ print("Using recursive function to calculate lucas series:") print(" ".join(str(recursive_lucas_number(i)) for i in range(n))) print("\nUsing dynamic function to calculate lucas series:") - print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))+ print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/lucas_series.py
Write reusable docstrings
import timeit """ Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time. You read more about it here: https://zobayer.blogspot.com/2010/11/matrix-exponentiation.html https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/ """ class Matrix: def __init__(self, arg: list[list] | int) -> None: if isinstance(arg, list): # Initializes a matrix identical to the one provided. self.t = arg self.n = len(arg) else: # Initializes a square matrix of the given size and set values to zero. self.n = arg self.t = [[0 for _ in range(self.n)] for _ in range(self.n)] def __mul__(self, b: Matrix) -> Matrix: matrix = Matrix(self.n) for i in range(self.n): for j in range(self.n): for k in range(self.n): matrix.t[i][j] += self.t[i][k] * b.t[k][j] return matrix def modular_exponentiation(a: Matrix, b: int) -> Matrix: matrix = Matrix([[1, 0], [0, 1]]) while b > 0: if b & 1: matrix *= a a *= a b >>= 1 return matrix def fibonacci_with_matrix_exponentiation(n: int, f1: int, f2: int) -> int: # Trivial Cases if n == 1: return f1 elif n == 2: return f2 matrix = Matrix([[1, 1], [1, 0]]) matrix = modular_exponentiation(matrix, n - 2) return f2 * matrix.t[0][0] + f1 * matrix.t[0][1] def simple_fibonacci(n: int, f1: int, f2: int) -> int: # Trivial Cases if n == 1: return f1 elif n == 2: return f2 n -= 2 while n > 0: f2, f1 = f1 + f2, f2 n -= 1 return f2 def matrix_exponentiation_time() -> float: setup = """ from random import randint from __main__ import fibonacci_with_matrix_exponentiation """ code = "fibonacci_with_matrix_exponentiation(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print("With matrix exponentiation the average execution time is ", exec_time / 100) return exec_time def simple_fibonacci_time() -> float: setup = """ from random import randint from __main__ import simple_fibonacci """ code = "simple_fibonacci(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print( "Without matrix exponentiation the average execution time is ", exec_time / 100 ) return exec_time def main() -> None: matrix_exponentiation_time() simple_fibonacci_time() if __name__ == "__main__": main()
--- +++ @@ -1,3 +1,4 @@+"""Matrix Exponentiation""" import timeit @@ -38,6 +39,21 @@ def fibonacci_with_matrix_exponentiation(n: int, f1: int, f2: int) -> int: + """ + Returns the nth number of the Fibonacci sequence that + starts with f1 and f2 + Uses the matrix exponentiation + >>> fibonacci_with_matrix_exponentiation(1, 5, 6) + 5 + >>> fibonacci_with_matrix_exponentiation(2, 10, 11) + 11 + >>> fibonacci_with_matrix_exponentiation(13, 0, 1) + 144 + >>> fibonacci_with_matrix_exponentiation(10, 5, 9) + 411 + >>> fibonacci_with_matrix_exponentiation(9, 2, 3) + 89 + """ # Trivial Cases if n == 1: return f1 @@ -49,6 +65,21 @@ def simple_fibonacci(n: int, f1: int, f2: int) -> int: + """ + Returns the nth number of the Fibonacci sequence that + starts with f1 and f2 + Uses the definition + >>> simple_fibonacci(1, 5, 6) + 5 + >>> simple_fibonacci(2, 10, 11) + 11 + >>> simple_fibonacci(13, 0, 1) + 144 + >>> simple_fibonacci(10, 5, 9) + 411 + >>> simple_fibonacci(9, 2, 3) + 89 + """ # Trivial Cases if n == 1: return f1 @@ -94,4 +125,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/matrix_exponentiation.py
Can you add docstrings to this Python file?
def integer_square_root(num: int) -> int: if not isinstance(num, int) or num < 0: raise ValueError("num must be non-negative integer") if num < 2: return num left_bound = 0 right_bound = num // 2 while left_bound <= right_bound: mid = left_bound + (right_bound - left_bound) // 2 mid_squared = mid * mid if mid_squared == num: return mid if mid_squared < num: left_bound = mid + 1 else: right_bound = mid - 1 return right_bound if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,49 @@+""" +Integer Square Root Algorithm -- An efficient method to calculate the square root of a +non-negative integer 'num' rounded down to the nearest integer. It uses a binary search +approach to find the integer square root without using any built-in exponent functions +or operators. +* https://en.wikipedia.org/wiki/Integer_square_root +* https://docs.python.org/3/library/math.html#math.isqrt +Note: + - This algorithm is designed for non-negative integers only. + - The result is rounded down to the nearest integer. + - The algorithm has a time complexity of O(log(x)). + - Original algorithm idea based on binary search. +""" def integer_square_root(num: int) -> int: + """ + Returns the integer square root of a non-negative integer num. + Args: + num: A non-negative integer. + Returns: + The integer square root of num. + Raises: + ValueError: If num is not an integer or is negative. + >>> [integer_square_root(i) for i in range(18)] + [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4] + >>> integer_square_root(625) + 25 + >>> integer_square_root(2_147_483_647) + 46340 + >>> from math import isqrt + >>> all(integer_square_root(i) == isqrt(i) for i in range(20)) + True + >>> integer_square_root(-1) + Traceback (most recent call last): + ... + ValueError: num must be non-negative integer + >>> integer_square_root(1.5) + Traceback (most recent call last): + ... + ValueError: num must be non-negative integer + >>> integer_square_root("0") + Traceback (most recent call last): + ... + ValueError: num must be non-negative integer + """ if not isinstance(num, int) or num < 0: raise ValueError("num must be non-negative integer") @@ -27,4 +70,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/integer_square_root.py
Write docstrings describing each step
from collections import Counter def get_factors( number: int, factors: Counter | None = None, factor: int = 2 ) -> Counter: match number: case int(number) if number == 1: return Counter({1: 1}) case int(num) if number > 0: number = num case _: raise TypeError("number must be integer and greater than zero") factors = factors or Counter() if number == factor: # break condition # all numbers are factors of itself factors[factor] += 1 return factors if number % factor > 0: # if it is greater than zero # so it is not a factor of number and we check next number return get_factors(number, factors, factor + 1) factors[factor] += 1 # else we update factors (that is Counter(dict-like) type) and check again return get_factors(number // factor, factors, factor) def get_greatest_common_divisor(*numbers: int) -> int: # we just need factors, not numbers itself try: same_factors, *factors = map(get_factors, numbers) except TypeError as e: raise Exception("numbers must be integer and greater than zero") from e for factor in factors: same_factors &= factor # get common factor between all # `&` return common elements with smaller value (for Counter type) # now, same_factors is something like {2: 2, 3: 4} that means 2 * 2 * 3 * 3 * 3 * 3 mult = 1 # power each factor and multiply # for {2: 2, 3: 4}, it is [4, 81] and then 324 for m in [factor**power for factor, power in same_factors.items()]: mult *= m return mult if __name__ == "__main__": print(get_greatest_common_divisor(18, 45)) # 9
--- +++ @@ -1,3 +1,7 @@+""" +Gcd of N Numbers +Reference: https://en.wikipedia.org/wiki/Greatest_common_divisor +""" from collections import Counter @@ -5,6 +9,31 @@ def get_factors( number: int, factors: Counter | None = None, factor: int = 2 ) -> Counter: + """ + this is a recursive function for get all factors of number + >>> get_factors(45) + Counter({3: 2, 5: 1}) + >>> get_factors(2520) + Counter({2: 3, 3: 2, 5: 1, 7: 1}) + >>> get_factors(23) + Counter({23: 1}) + >>> get_factors(0) + Traceback (most recent call last): + ... + TypeError: number must be integer and greater than zero + >>> get_factors(-1) + Traceback (most recent call last): + ... + TypeError: number must be integer and greater than zero + >>> get_factors(1.5) + Traceback (most recent call last): + ... + TypeError: number must be integer and greater than zero + + factor can be all numbers from 2 to number that we check if number % factor == 0 + if it is equal to zero, we check again with number // factor + else we increase factor by one + """ match number: case int(number) if number == 1: @@ -32,6 +61,29 @@ def get_greatest_common_divisor(*numbers: int) -> int: + """ + get gcd of n numbers: + >>> get_greatest_common_divisor(18, 45) + 9 + >>> get_greatest_common_divisor(23, 37) + 1 + >>> get_greatest_common_divisor(2520, 8350) + 10 + >>> get_greatest_common_divisor(-10, 20) + Traceback (most recent call last): + ... + Exception: numbers must be integer and greater than zero + >>> get_greatest_common_divisor(1.5, 2) + Traceback (most recent call last): + ... + Exception: numbers must be integer and greater than zero + >>> get_greatest_common_divisor(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + 1 + >>> get_greatest_common_divisor("1", 2, 3, 4, 5, 6, 7, 8, 9, 10) + Traceback (most recent call last): + ... + Exception: numbers must be integer and greater than zero + """ # we just need factors, not numbers itself try: @@ -54,4 +106,4 @@ if __name__ == "__main__": - print(get_greatest_common_divisor(18, 45)) # 9+ print(get_greatest_common_divisor(18, 45)) # 9
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/gcd_of_n_numbers.py
Can you add docstrings to this Python file?
def joint_probability_distribution( x_values: list[int], y_values: list[int], x_probabilities: list[float], y_probabilities: list[float], ) -> dict: return { (x, y): x_prob * y_prob for x, x_prob in zip(x_values, x_probabilities) for y, y_prob in zip(y_values, y_probabilities) } # Function to calculate the expectation (mean) def expectation(values: list, probabilities: list) -> float: return sum(x * p for x, p in zip(values, probabilities)) # Function to calculate the variance def variance(values: list[int], probabilities: list[float]) -> float: mean = expectation(values, probabilities) return sum((x - mean) ** 2 * p for x, p in zip(values, probabilities)) # Function to calculate the covariance def covariance( x_values: list[int], y_values: list[int], x_probabilities: list[float], y_probabilities: list[float], ) -> float: mean_x = expectation(x_values, x_probabilities) mean_y = expectation(y_values, y_probabilities) return sum( (x - mean_x) * (y - mean_y) * px * py for x, px in zip(x_values, x_probabilities) for y, py in zip(y_values, y_probabilities) ) # Function to calculate the standard deviation def standard_deviation(variance: float) -> float: return variance**0.5 if __name__ == "__main__": from doctest import testmod testmod() # Input values for X and Y x_vals = input("Enter values of X separated by spaces: ").split() y_vals = input("Enter values of Y separated by spaces: ").split() # Convert input values to integers x_values = [int(x) for x in x_vals] y_values = [int(y) for y in y_vals] # Input probabilities for X and Y x_probs = input("Enter probabilities for X separated by spaces: ").split() y_probs = input("Enter probabilities for Y separated by spaces: ").split() assert len(x_values) == len(x_probs) assert len(y_values) == len(y_probs) # Convert input probabilities to floats x_probabilities = [float(p) for p in x_probs] y_probabilities = [float(p) for p in y_probs] # Calculate the joint probability distribution jpd = joint_probability_distribution( x_values, y_values, x_probabilities, y_probabilities ) # Print the joint probability distribution print( "\n".join( f"P(X={x}, Y={y}) = {probability}" for (x, y), probability in jpd.items() ) ) mean_xy = expectation( [x * y for x in x_values for y in y_values], [px * py for px in x_probabilities for py in y_probabilities], ) print(f"x mean: {expectation(x_values, x_probabilities) = }") print(f"y mean: {expectation(y_values, y_probabilities) = }") print(f"xy mean: {mean_xy}") print(f"x: {variance(x_values, x_probabilities) = }") print(f"y: {variance(y_values, y_probabilities) = }") print(f"{covariance(x_values, y_values, x_probabilities, y_probabilities) = }") print(f"x: {standard_deviation(variance(x_values, x_probabilities)) = }") print(f"y: {standard_deviation(variance(y_values, y_probabilities)) = }")
--- +++ @@ -1,3 +1,7 @@+""" +Calculate joint probability distribution +https://en.wikipedia.org/wiki/Joint_probability_distribution +""" def joint_probability_distribution( @@ -6,6 +10,16 @@ x_probabilities: list[float], y_probabilities: list[float], ) -> dict: + """ + >>> joint_distribution = joint_probability_distribution( + ... [1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2] + ... ) + >>> from math import isclose + >>> isclose(joint_distribution.pop((1, 8)), 0.14) + True + >>> joint_distribution + {(1, -2): 0.21, (1, 5): 0.35, (2, -2): 0.09, (2, 5): 0.15, (2, 8): 0.06} + """ return { (x, y): x_prob * y_prob for x, x_prob in zip(x_values, x_probabilities) @@ -15,11 +29,21 @@ # Function to calculate the expectation (mean) def expectation(values: list, probabilities: list) -> float: + """ + >>> from math import isclose + >>> isclose(expectation([1, 2], [0.7, 0.3]), 1.3) + True + """ return sum(x * p for x, p in zip(values, probabilities)) # Function to calculate the variance def variance(values: list[int], probabilities: list[float]) -> float: + """ + >>> from math import isclose + >>> isclose(variance([1,2],[0.7,0.3]), 0.21) + True + """ mean = expectation(values, probabilities) return sum((x - mean) ** 2 * p for x, p in zip(values, probabilities)) @@ -31,6 +55,10 @@ x_probabilities: list[float], y_probabilities: list[float], ) -> float: + """ + >>> covariance([1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2]) + -2.7755575615628914e-17 + """ mean_x = expectation(x_values, x_probabilities) mean_y = expectation(y_values, y_probabilities) return sum( @@ -42,6 +70,10 @@ # Function to calculate the standard deviation def standard_deviation(variance: float) -> float: + """ + >>> standard_deviation(0.21) + 0.458257569495584 + """ return variance**0.5 @@ -89,4 +121,4 @@ print(f"y: {variance(y_values, y_probabilities) = }") print(f"{covariance(x_values, y_values, x_probabilities, y_probabilities) = }") print(f"x: {standard_deviation(variance(x_values, x_probabilities)) = }") - print(f"y: {standard_deviation(variance(y_values, y_probabilities)) = }")+ print(f"y: {standard_deviation(variance(y_values, y_probabilities)) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/joint_probability_distribution.py
Document this code for team use
def josephus_recursive(num_people: int, step_size: int) -> int: if ( not isinstance(num_people, int) or not isinstance(step_size, int) or num_people <= 0 or step_size <= 0 ): raise ValueError("num_people or step_size is not a positive integer.") if num_people == 1: return 0 return (josephus_recursive(num_people - 1, step_size) + step_size) % num_people def find_winner(num_people: int, step_size: int) -> int: return josephus_recursive(num_people, step_size) + 1 def josephus_iterative(num_people: int, step_size: int) -> int: circle = list(range(1, num_people + 1)) current = 0 while len(circle) > 1: current = (current + step_size - 1) % len(circle) circle.pop(current) return circle[0] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,68 @@+""" +The Josephus problem is a famous theoretical problem related to a certain +counting-out game. This module provides functions to solve the Josephus problem +for num_people and a step_size. + +The Josephus problem is defined as follows: +- num_people are standing in a circle. +- Starting with a specified person, you count around the circle, + skipping a fixed number of people (step_size). +- The person at which you stop counting is eliminated from the circle. +- The counting continues until only one person remains. + +For more information about the Josephus problem, refer to: +https://en.wikipedia.org/wiki/Josephus_problem +""" def josephus_recursive(num_people: int, step_size: int) -> int: + """ + Solve the Josephus problem for num_people and a step_size recursively. + + Args: + num_people: A positive integer representing the number of people. + step_size: A positive integer representing the step size for elimination. + + Returns: + The position of the last person remaining. + + Raises: + ValueError: If num_people or step_size is not a positive integer. + + Examples: + >>> josephus_recursive(7, 3) + 3 + >>> josephus_recursive(10, 2) + 4 + >>> josephus_recursive(0, 2) + Traceback (most recent call last): + ... + ValueError: num_people or step_size is not a positive integer. + >>> josephus_recursive(1.9, 2) + Traceback (most recent call last): + ... + ValueError: num_people or step_size is not a positive integer. + >>> josephus_recursive(-2, 2) + Traceback (most recent call last): + ... + ValueError: num_people or step_size is not a positive integer. + >>> josephus_recursive(7, 0) + Traceback (most recent call last): + ... + ValueError: num_people or step_size is not a positive integer. + >>> josephus_recursive(7, -2) + Traceback (most recent call last): + ... + ValueError: num_people or step_size is not a positive integer. + >>> josephus_recursive(1_000, 0.01) + Traceback (most recent call last): + ... + ValueError: num_people or step_size is not a positive integer. + >>> josephus_recursive("cat", "dog") + Traceback (most recent call last): + ... + ValueError: num_people or step_size is not a positive integer. + """ if ( not isinstance(num_people, int) or not isinstance(step_size, int) @@ -16,10 +78,42 @@ def find_winner(num_people: int, step_size: int) -> int: + """ + Find the winner of the Josephus problem for num_people and a step_size. + + Args: + num_people (int): Number of people. + step_size (int): Step size for elimination. + + Returns: + int: The position of the last person remaining (1-based index). + + Examples: + >>> find_winner(7, 3) + 4 + >>> find_winner(10, 2) + 5 + """ return josephus_recursive(num_people, step_size) + 1 def josephus_iterative(num_people: int, step_size: int) -> int: + """ + Solve the Josephus problem for num_people and a step_size iteratively. + + Args: + num_people (int): The number of people in the circle. + step_size (int): The number of steps to take before eliminating someone. + + Returns: + int: The position of the last person standing. + + Examples: + >>> josephus_iterative(5, 2) + 3 + >>> josephus_iterative(7, 3) + 4 + """ circle = list(range(1, num_people + 1)) current = 0 @@ -33,4 +127,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/josephus_problem.py
Add docstrings that explain purpose and usage
from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> float: return 1 / sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) / (2 * sigma**2)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,62 @@+""" +Reference: https://en.wikipedia.org/wiki/Gaussian_function +""" from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> float: + """ + >>> float(gaussian(1)) + 0.24197072451914337 + + >>> float(gaussian(24)) + 3.342714441794458e-126 + + >>> float(gaussian(1, 4, 2)) + 0.06475879783294587 + + >>> float(gaussian(1, 5, 3)) + 0.05467002489199788 + + Supports NumPy Arrays + Use numpy.meshgrid with this to generate gaussian blur on images. + >>> import numpy as np + >>> x = np.arange(15) + >>> gaussian(x) + array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, + 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, + 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, + 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) + + >>> float(gaussian(15)) + 5.530709549844416e-50 + + >>> gaussian([1,2, 'string']) + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for -: 'list' and 'float' + + >>> gaussian('hello world') + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for -: 'str' and 'float' + + >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + OverflowError: (34, 'Result too large') + + >>> float(gaussian(10**-326)) + 0.3989422804014327 + + >>> float(gaussian(2523, mu=234234, sigma=3425)) + 0.0 + """ return 1 / sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) / (2 * sigma**2)) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/gaussian.py
Add docstrings to make code maintainable
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: if n <= 1: raise ValueError("Modulus n must be greater than 1") if a <= 0: raise ValueError("Divisor a must be a positive integer") if greatest_common_divisor(a, n) != 1: raise ValueError("a and n must be coprime (gcd(a, n) = 1)") (_d, _t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: (b, _x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> tuple[int, int, int]: assert a >= 0 assert b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 assert b % d == 0 assert d == a * x + b * y return (d, x, y) def extended_euclid(a: int, b: int) -> tuple[int, int]: if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) def greatest_common_divisor(a: int, b: int) -> int: if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
--- +++ @@ -2,6 +2,32 @@ def modular_division(a: int, b: int, n: int) -> int: + """ + Modular Division : + An efficient algorithm for dividing b by a modulo n. + + GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) + + Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should + return an integer x such that 0≤x≤n-1, and b/a=x(modn) (that is, b=ax(modn)). + + Theorem: + a has a multiplicative inverse modulo n iff gcd(a,n) = 1 + + + This find x = b*a^(-1) mod n + Uses ExtendedEuclid to find the inverse of a + + >>> modular_division(4,8,5) + 2 + + >>> modular_division(3,8,5) + 1 + + >>> modular_division(4, 11, 5) + 4 + + """ if n <= 1: raise ValueError("Modulus n must be greater than 1") if a <= 0: @@ -15,6 +41,16 @@ def invert_modulo(a: int, n: int) -> int: + """ + This function find the inverses of a i.e., a^(-1) + + >>> invert_modulo(2, 5) + 3 + + >>> invert_modulo(8,7) + 1 + + """ (b, _x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n @@ -25,12 +61,37 @@ def modular_division2(a: int, b: int, n: int) -> int: + """ + This function used the above inversion of a to find x = (b*a^(-1))mod n + + >>> modular_division2(4,8,5) + 2 + + >>> modular_division2(3,8,5) + 1 + + >>> modular_division2(4, 11, 5) + 4 + + """ s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> tuple[int, int, int]: + """ + Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x + and y, then d = gcd(a,b) + >>> extended_gcd(10, 6) + (2, -1, 2) + + >>> extended_gcd(7, 5) + (1, -2, 3) + + ** extended_gcd function is used when d = gcd(a,b) is required in output + + """ assert a >= 0 assert b >= 0 @@ -49,6 +110,15 @@ def extended_euclid(a: int, b: int) -> tuple[int, int]: + """ + Extended Euclid + >>> extended_euclid(10, 6) + (-1, 2) + + >>> extended_euclid(7, 5) + (-2, 3) + + """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) @@ -57,6 +127,21 @@ def greatest_common_divisor(a: int, b: int) -> int: + """ + Euclid's Lemma : d divides a and b, if and only if d divides a-b and b + Euclid's Algorithm + + >>> greatest_common_divisor(7,5) + 1 + + Note : In number theory, two integers a and b are said to be relatively prime, + mutually prime, or co-prime if the only positive integer (factor) that divides + both of them is 1 i.e., gcd(a,b) = 1. + + >>> greatest_common_divisor(121, 11) + 11 + + """ if a < b: a, b = b, a @@ -74,4 +159,4 @@ testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) - testmod(name="greatest_common_divisor", verbose=True)+ testmod(name="greatest_common_divisor", verbose=True)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/modular_division.py
Create docstrings for API functions
from __future__ import annotations def is_square_free(factors: list[int]) -> bool: return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,40 @@- -from __future__ import annotations - - -def is_square_free(factors: list[int]) -> bool: - return len(set(factors)) == len(factors) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +References: wikipedia:square free number +psf/black : True +ruff : True +""" + +from __future__ import annotations + + +def is_square_free(factors: list[int]) -> bool: + """ + # doctest: +NORMALIZE_WHITESPACE + This functions takes a list of prime factors as input. + returns True if the factors are square free. + >>> is_square_free([1, 1, 2, 3, 4]) + False + + These are wrong but should return some value + it simply checks for repetition in the numbers. + >>> is_square_free([1, 3, 4, 'sd', 0.0]) + True + + >>> is_square_free([1, 0.5, 2, 0.0]) + True + >>> is_square_free([1, 2, 2, 5]) + False + >>> is_square_free('asd') + True + >>> is_square_free(24) + Traceback (most recent call last): + ... + TypeError: 'int' object is not iterable + """ + return len(set(factors)) == len(factors) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/is_square_free.py
Auto-generate documentation strings for this file
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def mobius(n: int) -> int: factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,16 +1,43 @@- -from maths.is_square_free import is_square_free -from maths.prime_factors import prime_factors - - -def mobius(n: int) -> int: - factors = prime_factors(n) - if is_square_free(factors): - return -1 if len(factors) % 2 else 1 - return 0 - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +References: https://en.wikipedia.org/wiki/M%C3%B6bius_function +References: wikipedia:square free number +psf/black : True +ruff : True +""" + +from maths.is_square_free import is_square_free +from maths.prime_factors import prime_factors + + +def mobius(n: int) -> int: + """ + Mobius function + >>> mobius(24) + 0 + >>> mobius(-1) + 1 + >>> mobius('asd') + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'str' + >>> mobius(10**400) + 0 + >>> mobius(10**-400) + 1 + >>> mobius(-1424) + 1 + >>> mobius([1, '2', 2.0]) + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'list' + """ + factors = prime_factors(n) + if is_square_free(factors): + return -1 if len(factors) % 2 else 1 + return 0 + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/mobius_function.py
Write docstrings for data processing functions
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_factors import prime_factors def liouville_lambda(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise ValueError("Input must be a positive integer") return -1 if len(prime_factors(number)) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,9 +1,37 @@+""" +== Liouville Lambda Function == +The Liouville Lambda function, denoted by λ(n) +and λ(n) is 1 if n is the product of an even number of prime numbers, +and -1 if it is the product of an odd number of primes. + +https://en.wikipedia.org/wiki/Liouville_function +""" # Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_factors import prime_factors def liouville_lambda(number: int) -> int: + """ + This functions takes an integer number as input. + returns 1 if n has even number of prime factors and -1 otherwise. + >>> liouville_lambda(10) + 1 + >>> liouville_lambda(11) + -1 + >>> liouville_lambda(0) + Traceback (most recent call last): + ... + ValueError: Input must be a positive integer + >>> liouville_lambda(-1) + Traceback (most recent call last): + ... + ValueError: Input must be a positive integer + >>> liouville_lambda(11.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=11.0] must be an integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) @@ -15,4 +43,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/liouville_lambda.py
Add missing documentation to my Python functions
from __future__ import annotations def max_sum_in_array(array: list[int], k: int) -> int: if len(array) < k or k < 0: raise ValueError("Invalid Input") max_sum = current_sum = sum(array[:k]) for i in range(len(array) - k): current_sum = current_sum - array[i] + array[i + k] max_sum = max(max_sum, current_sum) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() array = [randint(-1000, 1000) for i in range(100)] k = randint(0, 110) print( f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}" )
--- +++ @@ -1,8 +1,32 @@+""" +Given an array of integer elements and an integer 'k', we are required to find the +maximum sum of 'k' consecutive elements in the array. + +Instead of using a nested for loop, in a Brute force approach we will use a technique +called 'Window sliding technique' where the nested loops can be converted to a single +loop to reduce time complexity. +""" from __future__ import annotations def max_sum_in_array(array: list[int], k: int) -> int: + """ + Returns the maximum sum of k consecutive elements + >>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] + >>> k = 4 + >>> max_sum_in_array(arr, k) + 24 + >>> k = 10 + >>> max_sum_in_array(arr,k) + Traceback (most recent call last): + ... + ValueError: Invalid Input + >>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2] + >>> k = 4 + >>> max_sum_in_array(arr, k) + 27 + """ if len(array) < k or k < 0: raise ValueError("Invalid Input") max_sum = current_sum = sum(array[:k]) @@ -21,4 +45,4 @@ k = randint(0, 110) print( f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}" - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/max_sum_sliding_window.py
Document functions with clear intent
def method_2(boundary: list[int], steps: int) -> float: # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) if steps <= 0: raise ZeroDivisionError("Number of steps must be greater than zero") h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # number of steps or resolution boundary = [a, b] # boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -1,8 +1,46 @@+""" +Numerical integration or quadrature for a smooth function f with known values at x_i + +This method is the classical approach of summing 'Equally Spaced Abscissas' + +method 2: +"Simpson Rule" + +""" def method_2(boundary: list[int], steps: int) -> float: # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) + """ + Calculate the definite integral of a function using Simpson's Rule. + :param boundary: A list containing the lower and upper bounds of integration. + :param steps: The number of steps or resolution for the integration. + :return: The approximate integral value. + + >>> round(method_2([0, 2, 4], 10), 10) + 2.6666666667 + >>> round(method_2([2, 0], 10), 10) + -0.2666666667 + >>> round(method_2([-2, -1], 10), 10) + 2.172 + >>> round(method_2([0, 1], 10), 10) + 0.3333333333 + >>> round(method_2([0, 2], 10), 10) + 2.6666666667 + >>> round(method_2([0, 2], 100), 10) + 2.5621226667 + >>> round(method_2([0, 1], 1000), 10) + 0.3320026653 + >>> round(method_2([0, 2], 0), 10) + Traceback (most recent call last): + ... + ZeroDivisionError: Number of steps must be greater than zero + >>> round(method_2([0, 2], -10), 10) + Traceback (most recent call last): + ... + ZeroDivisionError: Number of steps must be greater than zero + """ if steps <= 0: raise ZeroDivisionError("Number of steps must be greater than zero") @@ -45,4 +83,4 @@ import doctest doctest.testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/simpson_rule.py
Add documentation for all methods
def is_ip_v4_address_valid(ip: str) -> bool: octets = ip.split(".") if len(octets) != 4: return False for octet in octets: if not octet.isdigit(): return False number = int(octet) if len(str(number)) != len(octet): return False if not 0 <= number <= 255: return False return True if __name__ == "__main__": ip = input().strip() valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid" print(f"{ip} is a {valid_or_invalid} IPv4 address.")
--- +++ @@ -1,6 +1,56 @@+""" +wiki: https://en.wikipedia.org/wiki/IPv4 + +Is IP v4 address valid? +A valid IP address must be four octets in the form of A.B.C.D, +where A, B, C and D are numbers from 0-255 +for example: 192.168.23.1, 172.255.255.255 are valid IP address + 192.168.256.0, 256.192.3.121 are invalid IP address +""" def is_ip_v4_address_valid(ip: str) -> bool: + """ + print "Valid IP address" If IP is valid. + or + print "Invalid IP address" If IP is invalid. + + >>> is_ip_v4_address_valid("192.168.0.23") + True + + >>> is_ip_v4_address_valid("192.256.15.8") + False + + >>> is_ip_v4_address_valid("172.100.0.8") + True + + >>> is_ip_v4_address_valid("255.256.0.256") + False + + >>> is_ip_v4_address_valid("1.2.33333333.4") + False + + >>> is_ip_v4_address_valid("1.2.-3.4") + False + + >>> is_ip_v4_address_valid("1.2.3") + False + + >>> is_ip_v4_address_valid("1.2.3.4.5") + False + + >>> is_ip_v4_address_valid("1.2.A.4") + False + + >>> is_ip_v4_address_valid("0.0.0.0") + True + + >>> is_ip_v4_address_valid("1.2.3.") + False + + >>> is_ip_v4_address_valid("1.2.3.05") + False + """ octets = ip.split(".") if len(octets) != 4: return False @@ -22,4 +72,4 @@ if __name__ == "__main__": ip = input().strip() valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid" - print(f"{ip} is a {valid_or_invalid} IPv4 address.")+ print(f"{ip} is a {valid_or_invalid} IPv4 address.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/is_ip_v4_address_valid.py
Add docstrings to clarify complex logic
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 for _ in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): number_in_unit_circle += 1 return 4 * number_in_unit_circle / number_of_simulations if __name__ == "__main__": # import doctest # doctest.testmod() from math import pi prompt = "Please enter the desired number of Monte Carlo simulations: " my_pi = estimate_pi(int(input(prompt).strip())) print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
--- +++ @@ -7,14 +7,42 @@ self.y = y def is_in_unit_circle(self) -> bool: + """ + True, if the point lies in the unit circle + False, otherwise + """ return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): + """ + Generates a point randomly drawn from the unit square [0, 1) x [0, 1). + """ return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: + """ + Generates an estimate of the mathematical constant PI. + See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview + + The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from + the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: + + P[U in unit circle] = 1/4 PI + + and therefore + + PI = 4 * P[U in unit circle] + + We can get an estimate of the probability P[U in unit circle]. + See https://en.wikipedia.org/wiki/Empirical_probability by: + + 1. Draw a point uniformly from the unit square. + 2. Repeat the first step n times and count the number of points in the unit + circle, which is called m. + 3. An estimate of P[U in unit circle] is m/n + """ if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") @@ -36,4 +64,4 @@ prompt = "Please enter the desired number of Monte Carlo simulations: " my_pi = estimate_pi(int(input(prompt).strip())) - print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")+ print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/pi_monte_carlo_estimation.py
Generate NumPy-style docstrings
def manhattan_distance(point_a: list, point_b: list) -> float: _validate_point(point_a) _validate_point(point_b) if len(point_a) != len(point_b): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(point_a, point_b))) def _validate_point(point: list[float]) -> None: if point: if isinstance(point, list): for item in point: if not isinstance(item, (int, float)): msg = ( "Expected a list of numbers as input, found " f"{type(item).__name__}" ) raise TypeError(msg) else: msg = f"Expected a list of numbers as input, found {type(point).__name__}" raise TypeError(msg) else: raise ValueError("Missing an input") def manhattan_distance_one_liner(point_a: list, point_b: list) -> float: _validate_point(point_a) _validate_point(point_b) if len(point_a) != len(point_b): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(point_a, point_b))) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,4 +1,39 @@ def manhattan_distance(point_a: list, point_b: list) -> float: + """ + Expectts two list of numbers representing two points in the same + n-dimensional space + + https://en.wikipedia.org/wiki/Taxicab_geometry + + >>> manhattan_distance([1,1], [2,2]) + 2.0 + >>> manhattan_distance([1.5,1.5], [2,2]) + 1.0 + >>> manhattan_distance([1.5,1.5], [2.5,2]) + 1.5 + >>> manhattan_distance([-3, -3, -3], [0, 0, 0]) + 9.0 + >>> manhattan_distance([1,1], None) + Traceback (most recent call last): + ... + ValueError: Missing an input + >>> manhattan_distance([1,1], [2, 2, 2]) + Traceback (most recent call last): + ... + ValueError: Both points must be in the same n-dimensional space + >>> manhattan_distance([1,"one"], [2, 2, 2]) + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found str + >>> manhattan_distance(1, [2, 2, 2]) + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found int + >>> manhattan_distance([1,1], "not_a_list") + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found str + """ _validate_point(point_a) _validate_point(point_b) @@ -9,6 +44,24 @@ def _validate_point(point: list[float]) -> None: + """ + >>> _validate_point(None) + Traceback (most recent call last): + ... + ValueError: Missing an input + >>> _validate_point([1,"one"]) + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found str + >>> _validate_point(1) + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found int + >>> _validate_point("not_a_list") + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found str + """ if point: if isinstance(point, list): for item in point: @@ -26,6 +79,38 @@ def manhattan_distance_one_liner(point_a: list, point_b: list) -> float: + """ + Version with one liner + + >>> manhattan_distance_one_liner([1,1], [2,2]) + 2.0 + >>> manhattan_distance_one_liner([1.5,1.5], [2,2]) + 1.0 + >>> manhattan_distance_one_liner([1.5,1.5], [2.5,2]) + 1.5 + >>> manhattan_distance_one_liner([-3, -3, -3], [0, 0, 0]) + 9.0 + >>> manhattan_distance_one_liner([1,1], None) + Traceback (most recent call last): + ... + ValueError: Missing an input + >>> manhattan_distance_one_liner([1,1], [2, 2, 2]) + Traceback (most recent call last): + ... + ValueError: Both points must be in the same n-dimensional space + >>> manhattan_distance_one_liner([1,"one"], [2, 2, 2]) + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found str + >>> manhattan_distance_one_liner(1, [2, 2, 2]) + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found int + >>> manhattan_distance_one_liner([1,1], "not_a_list") + Traceback (most recent call last): + ... + TypeError: Expected a list of numbers as input, found str + """ _validate_point(point_a) _validate_point(point_b) @@ -38,4 +123,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/manhattan_distance.py
Add docstrings explaining edge cases
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be a positive integer" raise ValueError(msg) sequence = [number] while number != 1: if number % 2 == 0: number = math.floor(math.sqrt(number)) else: number = math.floor( math.sqrt(number) * math.sqrt(number) * math.sqrt(number) ) sequence.append(number) return sequence if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,9 +1,44 @@+""" +== Juggler Sequence == +Juggler sequence start with any positive integer n. The next term is +obtained as follows: + If n term is even, the next term is floor value of square root of n . + If n is odd, the next term is floor value of 3 time the square root of n. + +https://en.wikipedia.org/wiki/Juggler_sequence +""" # Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: + """ + >>> juggler_sequence(0) + Traceback (most recent call last): + ... + ValueError: Input value of [number=0] must be a positive integer + >>> juggler_sequence(1) + [1] + >>> juggler_sequence(2) + [2, 1] + >>> juggler_sequence(3) + [3, 5, 11, 36, 6, 2, 1] + >>> juggler_sequence(5) + [5, 11, 36, 6, 2, 1] + >>> juggler_sequence(10) + [10, 3, 5, 11, 36, 6, 2, 1] + >>> juggler_sequence(25) + [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1] + >>> juggler_sequence(6.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=6.0] must be an integer + >>> juggler_sequence(-1) + Traceback (most recent call last): + ... + ValueError: Input value of [number=-1] must be a positive integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) @@ -25,4 +60,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/juggler_sequence.py
Generate docstrings for each module
import math from collections.abc import Generator def slow_primes(max_n: int) -> Generator[int]: numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): if (i % j) == 0: break else: yield i def primes(max_n: int) -> Generator[int]: numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) bound = int(math.sqrt(i)) + 1 for j in range(2, bound): if (i % j) == 0: break else: yield i def fast_primes(max_n: int) -> Generator[int]: numbers: Generator = (i for i in range(1, (max_n + 1), 2)) # It's useless to test even numbers as they will not be prime if max_n > 2: yield 2 # Because 2 will not be tested, it's necessary to yield it now for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 for j in range(3, bound, 2): # As we removed the even numbers, we don't need them now if (i % j) == 0: break else: yield i def benchmark(): from timeit import timeit setup = "from __main__ import slow_primes, primes, fast_primes" print(timeit("slow_primes(1_000_000_000_000)", setup=setup, number=1_000_000)) print(timeit("primes(1_000_000_000_000)", setup=setup, number=1_000_000)) print(timeit("fast_primes(1_000_000_000_000)", setup=setup, number=1_000_000)) if __name__ == "__main__": number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) benchmark()
--- +++ @@ -3,6 +3,23 @@ def slow_primes(max_n: int) -> Generator[int]: + """ + Return a list of all primes numbers up to max. + >>> list(slow_primes(0)) + [] + >>> list(slow_primes(-1)) + [] + >>> list(slow_primes(-10)) + [] + >>> list(slow_primes(25)) + [2, 3, 5, 7, 11, 13, 17, 19, 23] + >>> list(slow_primes(11)) + [2, 3, 5, 7, 11] + >>> list(slow_primes(33)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] + >>> list(slow_primes(1000))[-1] + 997 + """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): @@ -13,6 +30,23 @@ def primes(max_n: int) -> Generator[int]: + """ + Return a list of all primes numbers up to max. + >>> list(primes(0)) + [] + >>> list(primes(-1)) + [] + >>> list(primes(-10)) + [] + >>> list(primes(25)) + [2, 3, 5, 7, 11, 13, 17, 19, 23] + >>> list(primes(11)) + [2, 3, 5, 7, 11] + >>> list(primes(33)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] + >>> list(primes(1000))[-1] + 997 + """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) @@ -25,6 +59,23 @@ def fast_primes(max_n: int) -> Generator[int]: + """ + Return a list of all primes numbers up to max. + >>> list(fast_primes(0)) + [] + >>> list(fast_primes(-1)) + [] + >>> list(fast_primes(-10)) + [] + >>> list(fast_primes(25)) + [2, 3, 5, 7, 11, 13, 17, 19, 23] + >>> list(fast_primes(11)) + [2, 3, 5, 7, 11] + >>> list(fast_primes(33)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] + >>> list(fast_primes(1000))[-1] + 997 + """ numbers: Generator = (i for i in range(1, (max_n + 1), 2)) # It's useless to test even numbers as they will not be prime if max_n > 2: @@ -40,6 +91,9 @@ def benchmark(): + """ + Let's benchmark our functions side-by-side... + """ from timeit import timeit setup = "from __main__ import slow_primes, primes, fast_primes" @@ -52,4 +106,4 @@ number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) - benchmark()+ benchmark()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/prime_numbers.py
Add concise docstrings to each method
from collections.abc import Callable from dataclasses import dataclass import numpy as np @dataclass class AdamsBashforth: func: Callable[[float, float], float] x_initials: list[float] y_initials: list[float] step_size: float x_final: float def __post_init__(self) -> None: if self.x_initials[-1] >= self.x_final: raise ValueError( "The final value of x must be greater than the initial values of x." ) if self.step_size <= 0: raise ValueError("Step size must be positive.") if not all( round(x1 - x0, 10) == self.step_size for x0, x1 in zip(self.x_initials, self.x_initials[1:]) ): raise ValueError("x-values must be equally spaced according to step size.") def step_2(self) -> np.ndarray: if len(self.x_initials) != 2 or len(self.y_initials) != 2: raise ValueError("Insufficient initial points information.") x_0, x_1 = self.x_initials[:2] y_0, y_1 = self.y_initials[:2] n = int((self.x_final - x_1) / self.step_size) y = np.zeros(n + 2) y[0] = y_0 y[1] = y_1 for i in range(n): y[i + 2] = y[i + 1] + (self.step_size / 2) * ( 3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i]) ) x_0 = x_1 x_1 += self.step_size return y def step_3(self) -> np.ndarray: if len(self.x_initials) != 3 or len(self.y_initials) != 3: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2 = self.x_initials[:3] y_0, y_1, y_2 = self.y_initials[:3] n = int((self.x_final - x_2) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 for i in range(n + 1): y[i + 3] = y[i + 2] + (self.step_size / 12) * ( 23 * self.func(x_2, y[i + 2]) - 16 * self.func(x_1, y[i + 1]) + 5 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 += self.step_size return y def step_4(self) -> np.ndarray: if len(self.x_initials) != 4 or len(self.y_initials) != 4: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3 = self.x_initials[:4] y_0, y_1, y_2, y_3 = self.y_initials[:4] n = int((self.x_final - x_3) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 for i in range(n): y[i + 4] = y[i + 3] + (self.step_size / 24) * ( 55 * self.func(x_3, y[i + 3]) - 59 * self.func(x_2, y[i + 2]) + 37 * self.func(x_1, y[i + 1]) - 9 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 += self.step_size return y def step_5(self) -> np.ndarray: if len(self.x_initials) != 5 or len(self.y_initials) != 5: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5] y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5] n = int((self.x_final - x_4) / self.step_size) y = np.zeros(n + 6) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 y[4] = y_4 for i in range(n + 1): y[i + 5] = y[i + 4] + (self.step_size / 720) * ( 1901 * self.func(x_4, y[i + 4]) - 2774 * self.func(x_3, y[i + 3]) - 2616 * self.func(x_2, y[i + 2]) - 1274 * self.func(x_1, y[i + 1]) + 251 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 = x_4 x_4 += self.step_size return y if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,9 @@+""" +Use the Adams-Bashforth methods to solve Ordinary Differential Equations. + +https://en.wikipedia.org/wiki/Linear_multistep_method +Author : Ravi Kumar +""" from collections.abc import Callable from dataclasses import dataclass @@ -7,6 +13,35 @@ @dataclass class AdamsBashforth: + """ + args: + func: An ordinary differential equation (ODE) as function of x and y. + x_initials: List containing initial required values of x. + y_initials: List containing initial required values of y. + step_size: The increment value of x. + x_final: The final value of x. + + Returns: Solution of y at each nodal point + + >>> def f(x, y): + ... return x + y + >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS + AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...) + >>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2() + Traceback (most recent call last): + ... + ValueError: The final value of x must be greater than the initial values of x. + + >>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3() + Traceback (most recent call last): + ... + ValueError: x-values must be equally spaced according to step size. + + >>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5() + Traceback (most recent call last): + ... + ValueError: Step size must be positive. + """ func: Callable[[float, float], float] x_initials: list[float] @@ -30,6 +65,17 @@ raise ValueError("x-values must be equally spaced according to step size.") def step_2(self) -> np.ndarray: + """ + >>> def f(x, y): + ... return x + >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2() + array([0. , 0. , 0.06, 0.16, 0.3 , 0.48]) + + >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2() + Traceback (most recent call last): + ... + ValueError: Insufficient initial points information. + """ if len(self.x_initials) != 2 or len(self.y_initials) != 2: raise ValueError("Insufficient initial points information.") @@ -52,6 +98,18 @@ return y def step_3(self) -> np.ndarray: + """ + >>> def f(x, y): + ... return x + y + >>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3() + >>> float(y[3]) + 0.15533333333333332 + + >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3() + Traceback (most recent call last): + ... + ValueError: Insufficient initial points information. + """ if len(self.x_initials) != 3 or len(self.y_initials) != 3: raise ValueError("Insufficient initial points information.") @@ -77,6 +135,21 @@ return y def step_4(self) -> np.ndarray: + """ + >>> def f(x,y): + ... return x + y + >>> y = AdamsBashforth( + ... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4() + >>> float(y[4]) + 0.30699999999999994 + >>> float(y[5]) + 0.5771083333333333 + + >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4() + Traceback (most recent call last): + ... + ValueError: Insufficient initial points information. + """ if len(self.x_initials) != 4 or len(self.y_initials) != 4: raise ValueError("Insufficient initial points information.") @@ -106,6 +179,20 @@ return y def step_5(self) -> np.ndarray: + """ + >>> def f(x,y): + ... return x + y + >>> y = AdamsBashforth( + ... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536], + ... 0.2, 1).step_5() + >>> float(y[-1]) + 0.05436839444444452 + + >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5() + Traceback (most recent call last): + ... + ValueError: Insufficient initial points information. + """ if len(self.x_initials) != 5 or len(self.y_initials) != 5: raise ValueError("Insufficient initial points information.") @@ -141,4 +228,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/adams_bashforth.py
Add docstrings to incomplete code
def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): q[i][1] = y_points[i] for i in range(2, n): for j in range(i, n): q[j][i] = ( (x0 - x_points[j - i + 1]) * q[j][i - 1] - (x0 - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,39 @@+""" +Python program to show how to interpolate and evaluate a polynomial +using Neville's method. +Neville's method evaluates a polynomial that passes through a +given set of x and y points for a particular x value (x0) using the +Newton polynomial form. +Reference: + https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation +""" def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: + """ + Interpolate and evaluate a polynomial using Neville's method. + Arguments: + x_points, y_points: Iterables of x and corresponding y points through + which the polynomial passes. + x0: The value of x to evaluate the polynomial for. + Return Value: A list of the approximated value and the Neville iterations + table respectively. + >>> import pprint + >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0] + 10.0 + >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1]) + [[0, 6, 0, 0, 0], + [0, 7, 0, 0, 0], + [0, 8, 104.0, 0, 0], + [0, 9, 104.0, 104.0, 0], + [0, 11, 104.0, 104.0, 104.0]] + >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0] + 104.0 + >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '') + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for -: 'str' and 'int' + """ n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): @@ -19,4 +52,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/nevilles_method.py
Generate NumPy-style docstrings
"""Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -1,8 +1,22 @@+""" +Modular Exponential. +Modular exponentiation is a type of exponentiation performed over a modulus. +For more explanation, please check +https://en.wikipedia.org/wiki/Modular_exponentiation +""" """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): + """ + >>> modular_exponential(5, 0, 10) + 1 + >>> modular_exponential(2, 8, 7) + 4 + >>> modular_exponential(3, -2, 9) + -1 + """ if power < 0: return -1 @@ -19,6 +33,7 @@ def main(): + """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) @@ -27,4 +42,4 @@ doctest.testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/modular_exponential.py
Fully document this Python code with docstrings
Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: x = end_point2[0] - end_point1[0] y = end_point2[1] - end_point1[1] z = end_point2[2] - end_point1[2] return (x, y, z) def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d: x = ab[1] * ac[2] - ab[2] * ac[1] # *i y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j z = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def is_zero_vector(vector: Vector3d, accuracy: int) -> bool: return tuple(round(x, accuracy) for x in vector) == (0, 0, 0) def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool: ab = create_vector(a, b) ac = create_vector(a, c) return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
--- +++ @@ -1,9 +1,48 @@+""" +Check if three points are collinear in 3D. + +In short, the idea is that we are able to create a triangle using three points, +and the area of that triangle can determine if the three points are collinear or not. + + +First, we create two vectors with the same initial point from the three points, +then we will calculate the cross-product of them. + +The length of the cross vector is numerically equal to the area of a parallelogram. + +Finally, the area of the triangle is equal to half of the area of the parallelogram. + +Since we are only differentiating between zero and anything else, +we can get rid of the square root when calculating the length of the vector, +and also the division by two at the end. + +From a second perspective, if the two vectors are parallel and overlapping, +we can't get a nonzero perpendicular vector, +since there will be an infinite number of orthogonal vectors. + +To simplify the solution we will not calculate the length, +but we will decide directly from the vector whether it is equal to (0, 0, 0) or not. + + +Read More: + https://math.stackexchange.com/a/1951650 +""" Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: + """ + Pass two points to get the vector from them in the form (x, y, z). + + >>> create_vector((0, 0, 0), (1, 1, 1)) + (1, 1, 1) + >>> create_vector((45, 70, 24), (47, 32, 1)) + (2, -38, -23) + >>> create_vector((-14, -1, -8), (-7, 6, 4)) + (7, 7, 12) + """ x = end_point2[0] - end_point1[0] y = end_point2[1] - end_point1[1] z = end_point2[2] - end_point1[2] @@ -11,6 +50,24 @@ def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d: + """ + Get the cross of the two vectors AB and AC. + + I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process. + + Read More: + https://en.wikipedia.org/wiki/Cross_product + https://en.wikipedia.org/wiki/Determinant + + >>> get_3d_vectors_cross((3, 4, 7), (4, 9, 2)) + (-55, 22, 11) + >>> get_3d_vectors_cross((1, 1, 1), (1, 1, 1)) + (0, 0, 0) + >>> get_3d_vectors_cross((-4, 3, 0), (3, -9, -12)) + (-36, -48, 27) + >>> get_3d_vectors_cross((17.67, 4.7, 6.78), (-9.5, 4.78, -19.33)) + (-123.2594, 277.15110000000004, 129.11260000000001) + """ x = ab[1] * ac[2] - ab[2] * ac[1] # *i y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j z = ab[0] * ac[1] - ab[1] * ac[0] # *k @@ -18,10 +75,52 @@ def is_zero_vector(vector: Vector3d, accuracy: int) -> bool: + """ + Check if vector is equal to (0, 0, 0) or not. + + Since the algorithm is very accurate, we will never get a zero vector, + so we need to round the vector axis, + because we want a result that is either True or False. + In other applications, we can return a float that represents the collinearity ratio. + + >>> is_zero_vector((0, 0, 0), accuracy=10) + True + >>> is_zero_vector((15, 74, 32), accuracy=10) + False + >>> is_zero_vector((-15, -74, -32), accuracy=10) + False + """ return tuple(round(x, accuracy) for x in vector) == (0, 0, 0) def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool: + """ + Check if three points are collinear or not. + + 1- Create two vectors AB and AC. + 2- Get the cross vector of the two vectors. + 3- Calculate the length of the cross vector. + 4- If the length is zero then the points are collinear, else they are not. + + The use of the accuracy parameter is explained in is_zero_vector docstring. + + >>> are_collinear((4.802293498137402, 3.536233125455244, 0), + ... (-2.186788107953106, -9.24561398001649, 7.141509524846482), + ... (1.530169574640268, -2.447927606600034, 3.343487096469054)) + True + >>> are_collinear((-6, -2, 6), + ... (6.200213806439997, -4.930157614926678, -4.482371908289856), + ... (-4.085171149525941, -2.459889509029438, 4.354787180795383)) + True + >>> are_collinear((2.399001826862445, -2.452009976680793, 4.464656666157666), + ... (-3.682816335934376, 5.753788986533145, 9.490993909044244), + ... (1.962903518985307, 3.741415730125627, 7)) + False + >>> are_collinear((1.875375340689544, -7.268426006071538, 7.358196269835993), + ... (-3.546599383667157, -4.630005261513976, 3.208784032924246), + ... (-2.564606140206386, 3.937845170672183, 7)) + False + """ ab = create_vector(a, b) ac = create_vector(a, c) - return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)+ return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/points_are_collinear_3d.py
Write Python docstrings for this snippet
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def pi_estimator(iterations: int) -> None: # A local function to see if a dot lands in the circle. def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x**2) + (y**2)) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle proportion = mean( int(is_in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0))) for _ in range(iterations) ) # The ratio of the area for circle to square is pi/4. pi_estimate = proportion * 4 print(f"The estimated value of pi is {pi_estimate}") print(f"The numpy value of pi is {pi}") print(f"The total error is {abs(pi - pi_estimate)}") def area_under_curve_estimator( iterations: int, function_to_integrate: Callable[[float], float], min_value: float = 0.0, max_value: float = 1.0, ) -> float: return mean( function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations) ) * (max_value - min_value) def area_under_line_estimator_check( iterations: int, min_value: float = 0.0, max_value: float = 1.0 ) -> None: def identity_function(x: float) -> float: return x estimated_value = area_under_curve_estimator( iterations, identity_function, min_value, max_value ) expected_value = (max_value * max_value - min_value * min_value) / 2 print("******************") print(f"Estimating area under y=x where x varies from {min_value} to {max_value}") print(f"Estimated value is {estimated_value}") print(f"Expected value is {expected_value}") print(f"Total error is {abs(estimated_value - expected_value)}") print("******************") def pi_estimator_using_area_under_curve(iterations: int) -> None: def function_to_integrate(x: float) -> float: return sqrt(4.0 - x * x) estimated_value = area_under_curve_estimator( iterations, function_to_integrate, 0.0, 2.0 ) print("******************") print("Estimating pi using area_under_curve_estimator") print(f"Estimated value is {estimated_value}") print(f"Expected value is {pi}") print(f"Total error is {abs(estimated_value - pi)}") print("******************") if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,6 @@+""" +@author: MatteoRaso +""" from collections.abc import Callable from math import pi, sqrt @@ -6,6 +9,16 @@ def pi_estimator(iterations: int) -> None: + """ + An implementation of the Monte Carlo method used to find pi. + 1. Draw a 2x2 square centred at (0,0). + 2. Inscribe a circle within the square. + 3. For each iteration, place a dot anywhere in the square. + a. Record the number of dots within the circle. + 4. After all the dots are placed, divide the dots in the circle by the total. + 5. Multiply this value by 4 to get your estimate of pi. + 6. Print the estimated and numpy value of pi + """ # A local function to see if a dot lands in the circle. def is_in_circle(x: float, y: float) -> bool: @@ -32,6 +45,23 @@ min_value: float = 0.0, max_value: float = 1.0, ) -> float: + """ + An implementation of the Monte Carlo method to find area under + a single variable non-negative real-valued continuous function, + say f(x), where x lies within a continuous bounded interval, + say [min_value, max_value], where min_value and max_value are + finite numbers + 1. Let x be a uniformly distributed random variable between min_value to + max_value + 2. Expected value of f(x) = + (integrate f(x) from min_value to max_value)/(max_value - min_value) + 3. Finding expected value of f(x): + a. Repeatedly draw x from uniform distribution + b. Evaluate f(x) at each of the drawn x values + c. Expected value = average of the function evaluations + 4. Estimated value of integral = Expected value * (max_value - min_value) + 5. Returns estimated value + """ return mean( function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations) @@ -41,8 +71,20 @@ def area_under_line_estimator_check( iterations: int, min_value: float = 0.0, max_value: float = 1.0 ) -> None: + """ + Checks estimation error for area_under_curve_estimator function + for f(x) = x where x lies within min_value to max_value + 1. Calls "area_under_curve_estimator" function + 2. Compares with the expected value + 3. Prints estimated, expected and error value + """ def identity_function(x: float) -> float: + """ + Represents identity function + >>> [function_to_integrate(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]] + [-2.0, -1.0, 0.0, 1.0, 2.0] + """ return x estimated_value = area_under_curve_estimator( @@ -59,8 +101,16 @@ def pi_estimator_using_area_under_curve(iterations: int) -> None: + """ + Area under curve y = sqrt(4 - x^2) where x lies in 0 to 2 is equal to pi + """ def function_to_integrate(x: float) -> float: + """ + Represents semi-circle with radius 2 + >>> [function_to_integrate(x) for x in [-2.0, 0.0, 2.0]] + [0.0, 2.0, 0.0] + """ return sqrt(4.0 - x * x) estimated_value = area_under_curve_estimator( @@ -78,4 +128,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/monte_carlo.py
Add detailed documentation for each class
def jaccard_similarity( set_a: set[str] | list[str] | tuple[str], set_b: set[str] | list[str] | tuple[str], alternative_union=False, ): if isinstance(set_a, set) and isinstance(set_b, set): intersection_length = len(set_a.intersection(set_b)) if alternative_union: union_length = len(set_a) + len(set_b) else: union_length = len(set_a.union(set_b)) return intersection_length / union_length elif isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)): intersection = [element for element in set_a if element in set_b] if alternative_union: return len(intersection) / (len(set_a) + len(set_b)) else: # Cast set_a to list because tuples cannot be mutated union = list(set_a) + [element for element in set_b if element not in set_a] return len(intersection) / len(union) raise ValueError( "Set a and b must either both be sets or be either a list or a tuple." ) if __name__ == "__main__": set_a = {"a", "b", "c", "d", "e"} set_b = {"c", "d", "e", "f", "h", "i"} print(jaccard_similarity(set_a, set_b))
--- +++ @@ -1,3 +1,17 @@+""" +The Jaccard similarity coefficient is a commonly used indicator of the +similarity between two sets. Let U be a set and A and B be subsets of U, +then the Jaccard index/similarity is defined to be the ratio of the number +of elements of their intersection and the number of elements of their union. + +Inspired from Wikipedia and +the book Mining of Massive Datasets [MMDS 2nd Edition, Chapter 3] + +https://en.wikipedia.org/wiki/Jaccard_index +https://mmds.org + +Jaccard similarity is widely used with MinHashing. +""" def jaccard_similarity( @@ -5,6 +19,51 @@ set_b: set[str] | list[str] | tuple[str], alternative_union=False, ): + """ + Finds the jaccard similarity between two sets. + Essentially, its intersection over union. + + The alternative way to calculate this is to take union as sum of the + number of items in the two sets. This will lead to jaccard similarity + of a set with itself be 1/2 instead of 1. [MMDS 2nd Edition, Page 77] + + Parameters: + :set_a (set,list,tuple): A non-empty set/list + :set_b (set,list,tuple): A non-empty set/list + :alternativeUnion (boolean): If True, use sum of number of + items as union + + Output: + (float) The jaccard similarity between the two sets. + + Examples: + >>> set_a = {'a', 'b', 'c', 'd', 'e'} + >>> set_b = {'c', 'd', 'e', 'f', 'h', 'i'} + >>> jaccard_similarity(set_a, set_b) + 0.375 + >>> jaccard_similarity(set_a, set_a) + 1.0 + >>> jaccard_similarity(set_a, set_a, True) + 0.5 + >>> set_a = ['a', 'b', 'c', 'd', 'e'] + >>> set_b = ('c', 'd', 'e', 'f', 'h', 'i') + >>> jaccard_similarity(set_a, set_b) + 0.375 + >>> set_a = ('c', 'd', 'e', 'f', 'h', 'i') + >>> set_b = ['a', 'b', 'c', 'd', 'e'] + >>> jaccard_similarity(set_a, set_b) + 0.375 + >>> set_a = ('c', 'd', 'e', 'f', 'h', 'i') + >>> set_b = ['a', 'b', 'c', 'd'] + >>> jaccard_similarity(set_a, set_b, True) + 0.2 + >>> set_a = {'a', 'b'} + >>> set_b = ['c', 'd'] + >>> jaccard_similarity(set_a, set_b) + Traceback (most recent call last): + ... + ValueError: Set a and b must either both be sets or be either a list or a tuple. + """ if isinstance(set_a, set) and isinstance(set_b, set): intersection_length = len(set_a.intersection(set_b)) @@ -33,4 +92,4 @@ if __name__ == "__main__": set_a = {"a", "b", "c", "d", "e"} set_b = {"c", "d", "e", "f", "h", "i"} - print(jaccard_similarity(set_a, set_b))+ print(jaccard_similarity(set_a, set_b))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/jaccard_similarity.py
Create documentation for each function signature
from math import factorial, pi def maclaurin_sin(theta: float, accuracy: int = 30) -> float: if not isinstance(theta, (int, float)): raise ValueError("maclaurin_sin() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1) for r in range(accuracy) ) def maclaurin_cos(theta: float, accuracy: int = 30) -> float: if not isinstance(theta, (int, float)): raise ValueError("maclaurin_cos() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy)) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
--- +++ @@ -1,48 +1,123 @@- -from math import factorial, pi - - -def maclaurin_sin(theta: float, accuracy: int = 30) -> float: - - if not isinstance(theta, (int, float)): - raise ValueError("maclaurin_sin() requires either an int or float for theta") - - if not isinstance(accuracy, int) or accuracy <= 0: - raise ValueError("maclaurin_sin() requires a positive int for accuracy") - - theta = float(theta) - div = theta // (2 * pi) - theta -= 2 * div * pi - return sum( - (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1) for r in range(accuracy) - ) - - -def maclaurin_cos(theta: float, accuracy: int = 30) -> float: - - if not isinstance(theta, (int, float)): - raise ValueError("maclaurin_cos() requires either an int or float for theta") - - if not isinstance(accuracy, int) or accuracy <= 0: - raise ValueError("maclaurin_cos() requires a positive int for accuracy") - - theta = float(theta) - div = theta // (2 * pi) - theta -= 2 * div * pi - return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy)) - - -if __name__ == "__main__": - import doctest - - doctest.testmod() - - print(maclaurin_sin(10)) - print(maclaurin_sin(-10)) - print(maclaurin_sin(10, 15)) - print(maclaurin_sin(-10, 15)) - - print(maclaurin_cos(5)) - print(maclaurin_cos(-5)) - print(maclaurin_cos(10, 15)) - print(maclaurin_cos(-10, 15))+""" +https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions +""" + +from math import factorial, pi + + +def maclaurin_sin(theta: float, accuracy: int = 30) -> float: + """ + Finds the maclaurin approximation of sin + + :param theta: the angle to which sin is found + :param accuracy: the degree of accuracy wanted minimum + :return: the value of sine in radians + + + >>> from math import isclose, sin + >>> all(isclose(maclaurin_sin(x, 50), sin(x)) for x in range(-25, 25)) + True + >>> maclaurin_sin(10) + -0.5440211108893691 + >>> maclaurin_sin(-10) + 0.5440211108893704 + >>> maclaurin_sin(10, 15) + -0.544021110889369 + >>> maclaurin_sin(-10, 15) + 0.5440211108893704 + >>> maclaurin_sin("10") + Traceback (most recent call last): + ... + ValueError: maclaurin_sin() requires either an int or float for theta + >>> maclaurin_sin(10, -30) + Traceback (most recent call last): + ... + ValueError: maclaurin_sin() requires a positive int for accuracy + >>> maclaurin_sin(10, 30.5) + Traceback (most recent call last): + ... + ValueError: maclaurin_sin() requires a positive int for accuracy + >>> maclaurin_sin(10, "30") + Traceback (most recent call last): + ... + ValueError: maclaurin_sin() requires a positive int for accuracy + """ + + if not isinstance(theta, (int, float)): + raise ValueError("maclaurin_sin() requires either an int or float for theta") + + if not isinstance(accuracy, int) or accuracy <= 0: + raise ValueError("maclaurin_sin() requires a positive int for accuracy") + + theta = float(theta) + div = theta // (2 * pi) + theta -= 2 * div * pi + return sum( + (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1) for r in range(accuracy) + ) + + +def maclaurin_cos(theta: float, accuracy: int = 30) -> float: + """ + Finds the maclaurin approximation of cos + + :param theta: the angle to which cos is found + :param accuracy: the degree of accuracy wanted + :return: the value of cosine in radians + + + >>> from math import isclose, cos + >>> all(isclose(maclaurin_cos(x, 50), cos(x)) for x in range(-25, 25)) + True + >>> maclaurin_cos(5) + 0.2836621854632268 + >>> maclaurin_cos(-5) + 0.2836621854632265 + >>> maclaurin_cos(10, 15) + -0.8390715290764524 + >>> maclaurin_cos(-10, 15) + -0.8390715290764521 + >>> maclaurin_cos("10") + Traceback (most recent call last): + ... + ValueError: maclaurin_cos() requires either an int or float for theta + >>> maclaurin_cos(10, -30) + Traceback (most recent call last): + ... + ValueError: maclaurin_cos() requires a positive int for accuracy + >>> maclaurin_cos(10, 30.5) + Traceback (most recent call last): + ... + ValueError: maclaurin_cos() requires a positive int for accuracy + >>> maclaurin_cos(10, "30") + Traceback (most recent call last): + ... + ValueError: maclaurin_cos() requires a positive int for accuracy + """ + + if not isinstance(theta, (int, float)): + raise ValueError("maclaurin_cos() requires either an int or float for theta") + + if not isinstance(accuracy, int) or accuracy <= 0: + raise ValueError("maclaurin_cos() requires a positive int for accuracy") + + theta = float(theta) + div = theta // (2 * pi) + theta -= 2 * div * pi + return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy)) + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + + print(maclaurin_sin(10)) + print(maclaurin_sin(-10)) + print(maclaurin_sin(10, 15)) + print(maclaurin_sin(-10, 15)) + + print(maclaurin_cos(5)) + print(maclaurin_cos(-5)) + print(maclaurin_cos(10, 15)) + print(maclaurin_cos(-10, 15))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/maclaurin_series.py
Add missing documentation to my Python functions
def prime_sieve_eratosthenes(num: int) -> list[int]: if num <= 0: raise ValueError("Input must be a positive integer") primes = [True] * (num + 1) p = 2 while p * p <= num: if primes[p]: for i in range(p * p, num + 1, p): primes[i] = False p += 1 return [prime for prime in range(2, num + 1) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() user_num = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
--- +++ @@ -1,6 +1,34 @@+""" +Sieve of Eratosthenes + +Input: n = 10 +Output: 2 3 5 7 + +Input: n = 20 +Output: 2 3 5 7 11 13 17 19 + +you can read in detail about this at +https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes +""" def prime_sieve_eratosthenes(num: int) -> list[int]: + """ + Print the prime numbers up to n + + >>> prime_sieve_eratosthenes(10) + [2, 3, 5, 7] + >>> prime_sieve_eratosthenes(20) + [2, 3, 5, 7, 11, 13, 17, 19] + >>> prime_sieve_eratosthenes(2) + [2] + >>> prime_sieve_eratosthenes(1) + [] + >>> prime_sieve_eratosthenes(-1) + Traceback (most recent call last): + ... + ValueError: Input must be a positive integer + """ if num <= 0: raise ValueError("Input must be a positive integer") @@ -23,4 +51,4 @@ doctest.testmod() user_num = int(input("Enter a positive integer: ").strip()) - print(prime_sieve_eratosthenes(user_num))+ print(prime_sieve_eratosthenes(user_num))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/prime_sieve_eratosthenes.py
Document functions with detailed explanations
def is_harmonic_series(series: list) -> bool: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [1, 2/3, 2]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1 and series[0] != 0: return True rec_series = [] series_len = len(series) for i in range(series_len): if series[i] == 0: raise ValueError("Input series cannot have 0 as an element") rec_series.append(1 / series[i]) common_diff = rec_series[1] - rec_series[0] for index in range(2, series_len): if rec_series[index] - rec_series[index - 1] != common_diff: return False return True def harmonic_mean(series: list) -> float: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += 1 / val return len(series) / answer if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,42 @@+""" +Harmonic mean +Reference: https://en.wikipedia.org/wiki/Harmonic_mean + +Harmonic series +Reference: https://en.wikipedia.org/wiki/Harmonic_series(mathematics) +""" def is_harmonic_series(series: list) -> bool: + """ + checking whether the input series is arithmetic series or not + >>> is_harmonic_series([ 1, 2/3, 1/2, 2/5, 1/3]) + True + >>> is_harmonic_series([ 1, 2/3, 2/5, 1/3]) + False + >>> is_harmonic_series([1, 2, 3]) + False + >>> is_harmonic_series([1/2, 1/3, 1/4]) + True + >>> is_harmonic_series([2/5, 2/10, 2/15, 2/20, 2/25]) + True + >>> is_harmonic_series(4) + Traceback (most recent call last): + ... + ValueError: Input series is not valid, valid series - [1, 2/3, 2] + >>> is_harmonic_series([]) + Traceback (most recent call last): + ... + ValueError: Input list must be a non empty list + >>> is_harmonic_series([0]) + Traceback (most recent call last): + ... + ValueError: Input series cannot have 0 as an element + >>> is_harmonic_series([1,2,0,6]) + Traceback (most recent call last): + ... + ValueError: Input series cannot have 0 as an element + """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [1, 2/3, 2]") if len(series) == 0: @@ -21,6 +57,25 @@ def harmonic_mean(series: list) -> float: + """ + return the harmonic mean of series + + >>> harmonic_mean([1, 4, 4]) + 2.0 + >>> harmonic_mean([3, 6, 9, 12]) + 5.759999999999999 + >>> harmonic_mean(4) + Traceback (most recent call last): + ... + ValueError: Input series is not valid, valid series - [2, 4, 6] + >>> harmonic_mean([1, 2, 3]) + 1.6363636363636365 + >>> harmonic_mean([]) + Traceback (most recent call last): + ... + ValueError: Input list must be a non empty list + + """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: @@ -34,4 +89,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/harmonic.py
Add professional docstrings to my codebase
from __future__ import annotations def prime_factors(n: int) -> list[int]: i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors def unique_prime_factors(n: int) -> list[int]: i = 2 factors = [] while i * i <= n: if not n % i: while not n % i: n //= i factors.append(i) i += 1 if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,39 @@+""" +python/black : True +""" from __future__ import annotations def prime_factors(n: int) -> list[int]: + """ + Returns prime factors of n as a list. + + >>> prime_factors(0) + [] + >>> prime_factors(100) + [2, 2, 5, 5] + >>> prime_factors(2560) + [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] + >>> prime_factors(10**-2) + [] + >>> prime_factors(0.02) + [] + >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE + >>> x == [2]*241 + [5]*241 + True + >>> prime_factors(10**-354) + [] + >>> prime_factors('hello') + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'str' + >>> prime_factors([1,2,'hello']) + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'list' + + """ i = 2 factors = [] while i * i <= n: @@ -17,6 +48,32 @@ def unique_prime_factors(n: int) -> list[int]: + """ + Returns unique prime factors of n as a list. + + >>> unique_prime_factors(0) + [] + >>> unique_prime_factors(100) + [2, 5] + >>> unique_prime_factors(2560) + [2, 5] + >>> unique_prime_factors(10**-2) + [] + >>> unique_prime_factors(0.02) + [] + >>> unique_prime_factors(10**241) + [2, 5] + >>> unique_prime_factors(10**-354) + [] + >>> unique_prime_factors('hello') + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'str' + >>> unique_prime_factors([1,2,'hello']) + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'list' + """ i = 2 factors = [] while i * i <= n: @@ -33,4 +90,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/prime_factors.py
Write docstrings for backend logic
import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,4 @@+"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math @@ -13,10 +14,16 @@ def distance(a: Point, b: Point) -> float: + """ + >>> point1 = Point(2, -1, 7) + >>> point2 = Point(1, -3, 5) + >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") + Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 + """ return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/pythagoras.py
Insert docstrings into my code
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2") # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(value: int, step: int, modulus: int) -> int: return (pow(value, 2) + step) % modulus for _ in range(attempts): # These track the position within the cycle detection logic. tortoise = seed hare = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. tortoise = rand_fn(tortoise, step, num) hare = rand_fn(hare, step, num) hare = rand_fn(hare, step, num) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. divisor = gcd(hare - tortoise, num) if divisor == 1: # No common divisor yet, just keep searching. continue # We found a common divisor! elif divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. seed = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) args = parser.parse_args() divisor = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"{args.num} is probably prime") else: quotient = args.num // divisor print(f"{args.num} = {divisor} * {quotient}")
--- +++ @@ -9,6 +9,31 @@ step: int = 1, attempts: int = 3, ) -> int | None: + """ + Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. + The returned factor may be composite and require further factorization. + If the algorithm will return None if it fails to find a factor within + the specified number of attempts or within the specified number of steps. + If ``num`` is prime, this algorithm is guaranteed to return None. + https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm + + >>> pollard_rho(18446744073709551617) + 274177 + >>> pollard_rho(97546105601219326301) + 9876543191 + >>> pollard_rho(100) + 2 + >>> pollard_rho(17) + >>> pollard_rho(17**3) + 17 + >>> pollard_rho(17**3, attempts=1) + >>> pollard_rho(3*5*7) + 21 + >>> pollard_rho(1) + Traceback (most recent call last): + ... + ValueError: The input value cannot be less than 2 + """ # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2") @@ -31,6 +56,21 @@ # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(value: int, step: int, modulus: int) -> int: + """ + Returns a pseudorandom value modulo ``modulus`` based on the + input ``value`` and attempt-specific ``step`` size. + + >>> rand_fn(0, 0, 0) + Traceback (most recent call last): + ... + ZeroDivisionError: integer division or modulo by zero + >>> rand_fn(1, 2, 3) + 0 + >>> rand_fn(0, 10, 7) + 3 + >>> rand_fn(1234, 1, 17) + 16 + """ return (pow(value, 2) + step) % modulus for _ in range(attempts): @@ -105,4 +145,4 @@ print(f"{args.num} is probably prime") else: quotient = args.num // divisor - print(f"{args.num} = {divisor} * {quotient}")+ print(f"{args.num} = {divisor} * {quotient}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/pollard_rho.py
Improve documentation using docstrings
import math def perfect_square(num: int) -> bool: return math.sqrt(num) * math.sqrt(num) == num def perfect_square_binary_search(n: int) -> bool: left = 0 right = n while left <= right: mid = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: right = mid - 1 else: left = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -2,10 +2,58 @@ def perfect_square(num: int) -> bool: + """ + Check if a number is perfect square number or not + :param num: the number to be checked + :return: True if number is square number, otherwise False + + >>> perfect_square(9) + True + >>> perfect_square(16) + True + >>> perfect_square(1) + True + >>> perfect_square(0) + True + >>> perfect_square(10) + False + """ return math.sqrt(num) * math.sqrt(num) == num def perfect_square_binary_search(n: int) -> bool: + """ + Check if a number is perfect square using binary search. + Time complexity : O(Log(n)) + Space complexity: O(1) + + >>> perfect_square_binary_search(9) + True + >>> perfect_square_binary_search(16) + True + >>> perfect_square_binary_search(1) + True + >>> perfect_square_binary_search(0) + True + >>> perfect_square_binary_search(10) + False + >>> perfect_square_binary_search(-1) + False + >>> perfect_square_binary_search(1.1) + False + >>> perfect_square_binary_search("a") + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'str' + >>> perfect_square_binary_search(None) + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'NoneType' + >>> perfect_square_binary_search([]) + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'int' and 'list' + """ left = 0 right = n while left <= right: @@ -22,4 +70,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/perfect_square.py
Write docstrings that follow conventions
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: x_n: float = x0 x_n1: float = x1 while True: if x_n == x_n1 or function(x_n1) == function(x_n): raise ZeroDivisionError("float division by zero, could not find root") x_n2: float = x_n1 - ( function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n)) ) if abs(x_n2 - x_n1) < 10**-5: return x_n2 x_n = x_n1 x_n1 = x_n2 def f(x: float) -> float: return math.pow(x, 3) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
--- +++ @@ -3,6 +3,30 @@ def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: + """ + function is the f we want to find its root + x0 and x1 are two random starting points + >>> intersection(lambda x: x ** 3 - 1, -5, 5) + 0.9999999999954654 + >>> intersection(lambda x: x ** 3 - 1, 5, 5) + Traceback (most recent call last): + ... + ZeroDivisionError: float division by zero, could not find root + >>> intersection(lambda x: x ** 3 - 1, 100, 200) + 1.0000000000003888 + >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2) + 0.9999999998088019 + >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4) + 2.9999999998088023 + >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) + 3.0000000001786042 + >>> intersection(math.sin, -math.pi, math.pi) + 0.0 + >>> intersection(math.cos, -math.pi, math.pi) + Traceback (most recent call last): + ... + ZeroDivisionError: float division by zero, could not find root + """ x_n: float = x0 x_n1: float = x1 while True: @@ -18,8 +42,13 @@ def f(x: float) -> float: + """ + function is f(x) = x^3 - 2x - 5 + >>> f(2) + -1.0 + """ return math.pow(x, 3) - (2 * x) - 5 if __name__ == "__main__": - print(intersection(f, 3, 3.5))+ print(intersection(f, 3, 3.5))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/intersection.py
Help me comply with documentation standards
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-vector)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,39 @@+""" +This script demonstrates the implementation of the Sigmoid function. + +The function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)). +After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1. + +Script inspired from its corresponding Wikipedia article +https://en.wikipedia.org/wiki/Sigmoid_function +""" import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: + """ + Implements the sigmoid function + + Parameters: + vector (np.array): A numpy array of shape (1,n) + consisting of real values + + Returns: + sigmoid_vec (np.array): The input numpy array, after applying + sigmoid. + + Examples: + >>> sigmoid(np.array([-1.0, 1.0, 2.0])) + array([0.26894142, 0.73105858, 0.88079708]) + + >>> sigmoid(np.array([0.0])) + array([0.5]) + """ return 1 / (1 + np.exp(-vector)) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sigmoid.py
Fill in missing docstrings in my code
# constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a xi = a + i * h xn = b """ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: assert callable(function), ( f"the function(object) passed should be callable your input : {function}" ) assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" assert isinstance(precision, int) and precision > 0, ( f"precision should be positive integer your input : {precision}" ) # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,17 @@+""" +Author : Syed Faizan ( 3rd Year IIIT Pune ) +Github : faizan2700 + +Purpose : You have one function f(x) which takes float integer and returns +float you have to integrate the function in limits a to b. +The approximation proposed by Thomas Simpson in 1743 is one way to calculate +integration. + +( read article : https://cp-algorithms.com/num_methods/simpson-integration.html ) + +simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and +returns the integration of function in given limit. +""" # constants # the more the number of steps the more accurate @@ -21,6 +35,59 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: + """ + Args: + function : the function which's integration is desired + a : the lower limit of integration + b : upper limit of integration + precision : precision of the result,error required default is 4 + + Returns: + result : the value of the approximated integration of function in range a to b + + Raises: + AssertionError: function is not callable + AssertionError: a is not float or integer + AssertionError: function should return float or integer + AssertionError: b is not float or integer + AssertionError: precision is not positive integer + + >>> simpson_integration(lambda x : x*x,1,2,3) + 2.333 + + >>> simpson_integration(lambda x : x*x,'wrong_input',2,3) + Traceback (most recent call last): + ... + AssertionError: a should be float or integer your input : wrong_input + + >>> simpson_integration(lambda x : x*x,1,'wrong_input',3) + Traceback (most recent call last): + ... + AssertionError: b should be float or integer your input : wrong_input + + >>> simpson_integration(lambda x : x*x,1,2,'wrong_input') + Traceback (most recent call last): + ... + AssertionError: precision should be positive integer your input : wrong_input + >>> simpson_integration('wrong_input',2,3,4) + Traceback (most recent call last): + ... + AssertionError: the function(object) passed should be callable your input : ... + + >>> simpson_integration(lambda x : x*x,3.45,3.2,1) + -2.8 + + >>> simpson_integration(lambda x : x*x,3.45,3.2,0) + Traceback (most recent call last): + ... + AssertionError: precision should be positive integer your input : 0 + + >>> simpson_integration(lambda x : x*x,3.45,3.2,-1) + Traceback (most recent call last): + ... + AssertionError: precision should be positive integer your input : -1 + + """ assert callable(function), ( f"the function(object) passed should be callable your input : {function}" ) @@ -51,4 +118,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/integration_by_simpson_approx.py
Write docstrings for backend logic
def harmonic_series(n_term: str) -> list: if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
--- +++ @@ -1,6 +1,37 @@+""" +This is a pure Python implementation of the Harmonic Series algorithm +https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) + +For doctests run following command: +python -m doctest -v harmonic_series.py +or +python3 -m doctest -v harmonic_series.py + +For manual testing run: +python3 harmonic_series.py +""" def harmonic_series(n_term: str) -> list: + """Pure Python implementation of Harmonic Series algorithm + + :param n_term: The last (nth) term of Harmonic Series + :return: The Harmonic Series starting from 1 to last (nth) term + + Examples: + >>> harmonic_series(5) + ['1', '1/2', '1/3', '1/4', '1/5'] + >>> harmonic_series(5.0) + ['1', '1/2', '1/3', '1/4', '1/5'] + >>> harmonic_series(5.1) + ['1', '1/2', '1/3', '1/4', '1/5'] + >>> harmonic_series(-5) + [] + >>> harmonic_series(0) + [] + >>> harmonic_series(1) + ['1'] + """ if n_term == "": return [] series: list = [] @@ -12,4 +43,4 @@ if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") - print(harmonic_series(nth_term))+ print(harmonic_series(nth_term))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/harmonic_series.py
Document functions with clear intent
from collections.abc import Callable import numpy as np def runge_kutta_fehlberg_45( func: Callable, x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros( (n + 1), ) x = np.zeros(n + 1) y[0] = y_initial x[0] = x_initial for i in range(n): k1 = step_size * func(x[i], y[i]) k2 = step_size * func(x[i] + step_size / 4, y[i] + k1 / 4) k3 = step_size * func( x[i] + (3 / 8) * step_size, y[i] + (3 / 32) * k1 + (9 / 32) * k2 ) k4 = step_size * func( x[i] + (12 / 13) * step_size, y[i] + (1932 / 2197) * k1 - (7200 / 2197) * k2 + (7296 / 2197) * k3, ) k5 = step_size * func( x[i] + step_size, y[i] + (439 / 216) * k1 - 8 * k2 + (3680 / 513) * k3 - (845 / 4104) * k4, ) k6 = step_size * func( x[i] + step_size / 2, y[i] - (8 / 27) * k1 + 2 * k2 - (3544 / 2565) * k3 + (1859 / 4104) * k4 - (11 / 40) * k5, ) y[i + 1] = ( y[i] + (16 / 135) * k1 + (6656 / 12825) * k3 + (28561 / 56430) * k4 - (9 / 50) * k5 + (2 / 55) * k6 ) x[i + 1] = step_size + x[i] return y if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,6 @@+""" +Use the Runge-Kutta-Fehlberg method to solve Ordinary Differential Equations. +""" from collections.abc import Callable @@ -11,6 +14,50 @@ step_size: float, x_final: float, ) -> np.ndarray: + """ + Solve an Ordinary Differential Equations using Runge-Kutta-Fehlberg Method (rkf45) + of order 5. + + https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method + + args: + func: An ordinary differential equation (ODE) as function of x and y. + x_initial: The initial value of x. + y_initial: The initial value of y. + step_size: The increment value of x. + x_final: The final value of x. + + Returns: + Solution of y at each nodal point + + # exact value of y[1] is tan(0.2) = 0.2027100937470787 + >>> def f(x, y): + ... return 1 + y**2 + >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, 1) + >>> float(y[1]) + 0.2027100937470787 + >>> def f(x,y): + ... return x + >>> y = runge_kutta_fehlberg_45(f, -1, 0, 0.2, 0) + >>> float(y[1]) + -0.18000000000000002 + >>> y = runge_kutta_fehlberg_45(5, 0, 0, 0.1, 1) + Traceback (most recent call last): + ... + TypeError: 'int' object is not callable + >>> def f(x, y): + ... return x + y + >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, -1) + Traceback (most recent call last): + ... + ValueError: The final value of x must be greater than initial value of x. + >>> def f(x, y): + ... return x + >>> y = runge_kutta_fehlberg_45(f, -1, 0, -0.2, 0) + Traceback (most recent call last): + ... + ValueError: Step size must be positive. + """ if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." @@ -64,4 +111,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/runge_kutta_fehlberg_45.py
Add docstrings to incomplete code
def equation(x: float) -> float: return 10 - x * x def bisection(a: float, b: float) -> float: # Bolzano theory in order to find if there is a root between a and b if equation(a) * equation(b) >= 0: raise ValueError("Wrong space!") c = a while (b - a) >= 0.01: # Find middle point c = (a + b) / 2 # Check if middle point is root if equation(c) == 0.0: break # Decide the side to repeat the steps if equation(c) * equation(a) < 0: b = c else: a = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
--- +++ @@ -1,10 +1,40 @@+""" +Given a function on floating number f(x) and two floating numbers `a` and `b` such that +f(a) * f(b) < 0 and f(x) is continuous in [a, b]. +Here f(x) represents algebraic or transcendental equation. +Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0) + +https://en.wikipedia.org/wiki/Bisection_method +""" def equation(x: float) -> float: + """ + >>> equation(5) + -15 + >>> equation(0) + 10 + >>> equation(-5) + -15 + >>> equation(0.1) + 9.99 + >>> equation(-0.1) + 9.99 + """ return 10 - x * x def bisection(a: float, b: float) -> float: + """ + >>> bisection(-2, 5) + 3.1611328125 + >>> bisection(0, 6) + 3.158203125 + >>> bisection(2, 3) + Traceback (most recent call last): + ... + ValueError: Wrong space! + """ # Bolzano theory in order to find if there is a root between a and b if equation(a) * equation(b) >= 0: raise ValueError("Wrong space!") @@ -30,4 +60,4 @@ doctest.testmod() print(bisection(-2, 5)) - print(bisection(0, 6))+ print(bisection(0, 6))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/bisection_2.py
Help me add docstrings to my project
def hexagonal_numbers(length: int) -> list[int]: if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
--- +++ @@ -1,12 +1,42 @@- - -def hexagonal_numbers(length: int) -> list[int]: - - if length <= 0 or not isinstance(length, int): - raise ValueError("Length must be a positive integer.") - return [n * (2 * n - 1) for n in range(length)] - - -if __name__ == "__main__": - print(hexagonal_numbers(length=5)) - print(hexagonal_numbers(length=10))+""" +A hexagonal number sequence is a sequence of figurate numbers +where the nth hexagonal number hₙ is the number of distinct dots +in a pattern of dots consisting of the outlines of regular +hexagons with sides up to n dots, when the hexagons are overlaid +so that they share one vertex. + + Calculates the hexagonal numbers sequence with a formula + hₙ = n(2n-1) + where: + hₙ --> is nth element of the sequence + n --> is the number of element in the sequence + reference-->"Hexagonal number" Wikipedia + <https://en.wikipedia.org/wiki/Hexagonal_number> +""" + + +def hexagonal_numbers(length: int) -> list[int]: + """ + :param len: max number of elements + :type len: int + :return: Hexagonal numbers as a list + + Tests: + >>> hexagonal_numbers(10) + [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] + >>> hexagonal_numbers(5) + [0, 1, 6, 15, 28] + >>> hexagonal_numbers(0) + Traceback (most recent call last): + ... + ValueError: Length must be a positive integer. + """ + + if length <= 0 or not isinstance(length, int): + raise ValueError("Length must be a positive integer.") + return [n * (2 * n - 1) for n in range(length)] + + +if __name__ == "__main__": + print(hexagonal_numbers(length=5)) + print(hexagonal_numbers(length=10))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/hexagonal_numbers.py
Help me add docstrings to my project
def is_arithmetic_series(series: list) -> bool: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,31 @@+""" +Arithmetic mean +Reference: https://en.wikipedia.org/wiki/Arithmetic_mean + +Arithmetic series +Reference: https://en.wikipedia.org/wiki/Arithmetic_series +(The URL above will redirect you to arithmetic progression) +""" def is_arithmetic_series(series: list) -> bool: + """ + checking whether the input series is arithmetic series or not + >>> is_arithmetic_series([2, 4, 6]) + True + >>> is_arithmetic_series([3, 6, 12, 24]) + False + >>> is_arithmetic_series([1, 2, 3]) + True + >>> is_arithmetic_series(4) + Traceback (most recent call last): + ... + ValueError: Input series is not valid, valid series - [2, 4, 6] + >>> is_arithmetic_series([]) + Traceback (most recent call last): + ... + ValueError: Input list must be a non empty list + """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: @@ -15,6 +40,27 @@ def arithmetic_mean(series: list) -> float: + """ + return the arithmetic mean of series + + >>> arithmetic_mean([2, 4, 6]) + 4.0 + >>> arithmetic_mean([3, 6, 9, 12]) + 7.5 + >>> arithmetic_mean(4) + Traceback (most recent call last): + ... + ValueError: Input series is not valid, valid series - [2, 4, 6] + >>> arithmetic_mean([4, 8, 1]) + 4.333333333333333 + >>> arithmetic_mean([1, 2, 3]) + 2.0 + >>> arithmetic_mean([]) + Traceback (most recent call last): + ... + ValueError: Input list must be a non empty list + + """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: @@ -28,4 +74,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/arithmetic.py
Add docstrings that explain purpose and usage
def signum(num: float) -> int: if num < 0: return -1 return 1 if num else 0 def test_signum() -> None: assert signum(5) == 1 assert signum(-5) == -1 assert signum(0) == 0 assert signum(10.5) == 1 assert signum(-10.5) == -1 assert signum(1e-6) == 1 assert signum(-1e-6) == -1 assert signum(123456789) == 1 assert signum(-123456789) == -1 if __name__ == "__main__": print(signum(12)) print(signum(-12)) print(signum(0))
--- +++ @@ -1,12 +1,46 @@+""" +Signum function -- https://en.wikipedia.org/wiki/Sign_function +""" def signum(num: float) -> int: + """ + Applies signum function on the number + + Custom test cases: + >>> signum(-10) + -1 + >>> signum(10) + 1 + >>> signum(0) + 0 + >>> signum(-20.5) + -1 + >>> signum(20.5) + 1 + >>> signum(-1e-6) + -1 + >>> signum(1e-6) + 1 + >>> signum("Hello") + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'str' and 'int' + >>> signum([]) + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'list' and 'int' + """ if num < 0: return -1 return 1 if num else 0 def test_signum() -> None: + """ + Tests the signum function + >>> test_signum() + """ assert signum(5) == 1 assert signum(-5) == -1 assert signum(0) == 0 @@ -21,4 +55,4 @@ if __name__ == "__main__": print(signum(12)) print(signum(-12)) - print(signum(0))+ print(signum(0))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/signum.py
Generate docstrings with parameter types
from collections.abc import Callable RealFunc = Callable[[float], float] def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: return (f(x + delta_x / 2) - f(x - delta_x / 2)) / delta_x def newton_raphson( f: RealFunc, x0: float = 0, max_iter: int = 100, step: float = 1e-6, max_error: float = 1e-6, log_steps: bool = False, ) -> tuple[float, float, list[float]]: def f_derivative(x: float) -> float: return calc_derivative(f, x, step) a = x0 # Set initial guess steps = [] for _ in range(max_iter): if log_steps: # Log intermediate steps steps.append(a) error = abs(f(a)) if error < max_error: return a, error, steps if f_derivative(a) == 0: raise ZeroDivisionError("No converging solution found, zero derivative") a -= f(a) / f_derivative(a) # Calculate next estimate raise ArithmeticError("No converging solution found, iteration limit reached") if __name__ == "__main__": import doctest from math import exp, tanh doctest.testmod() def func(x: float) -> float: return tanh(x) ** 2 - exp(3 * x) solution, err, steps = newton_raphson( func, x0=10, max_iter=100, step=1e-6, log_steps=True ) print(f"{solution=}, {err=}") print("\n".join(str(x) for x in steps))
--- +++ @@ -1,3 +1,14 @@+""" +The Newton-Raphson method (aka the Newton method) is a root-finding algorithm that +approximates a root of a given real-valued function f(x). It is an iterative method +given by the formula + +x_{n + 1} = x_n + f(x_n) / f'(x_n) + +with the precision of the approximation increasing as the number of iterations increase. + +Reference: https://en.wikipedia.org/wiki/Newton%27s_method +""" from collections.abc import Callable @@ -5,6 +16,19 @@ def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: + """ + Approximate the derivative of a function f(x) at a point x using the finite + difference method + + >>> import math + >>> tolerance = 1e-5 + >>> derivative = calc_derivative(lambda x: x**2, 2) + >>> math.isclose(derivative, 4, abs_tol=tolerance) + True + >>> derivative = calc_derivative(math.sin, 0) + >>> math.isclose(derivative, 1, abs_tol=tolerance) + True + """ return (f(x + delta_x / 2) - f(x - delta_x / 2)) / delta_x @@ -16,6 +40,44 @@ max_error: float = 1e-6, log_steps: bool = False, ) -> tuple[float, float, list[float]]: + """ + Find a root of the given function f using the Newton-Raphson method. + + :param f: A real-valued single-variable function + :param x0: Initial guess + :param max_iter: Maximum number of iterations + :param step: Step size of x, used to approximate f'(x) + :param max_error: Maximum approximation error + :param log_steps: bool denoting whether to log intermediate steps + + :return: A tuple containing the approximation, the error, and the intermediate + steps. If log_steps is False, then an empty list is returned for the third + element of the tuple. + + :raises ZeroDivisionError: The derivative approaches 0. + :raises ArithmeticError: No solution exists, or the solution isn't found before the + iteration limit is reached. + + >>> import math + >>> tolerance = 1e-15 + >>> root, *_ = newton_raphson(lambda x: x**2 - 5*x + 2, 0.4, max_error=tolerance) + >>> math.isclose(root, (5 - math.sqrt(17)) / 2, abs_tol=tolerance) + True + >>> root, *_ = newton_raphson(lambda x: math.log(x) - 1, 2, max_error=tolerance) + >>> math.isclose(root, math.e, abs_tol=tolerance) + True + >>> root, *_ = newton_raphson(math.sin, 1, max_error=tolerance) + >>> math.isclose(root, 0, abs_tol=tolerance) + True + >>> newton_raphson(math.cos, 0) + Traceback (most recent call last): + ... + ZeroDivisionError: No converging solution found, zero derivative + >>> newton_raphson(lambda x: x**2 + 1, 2) + Traceback (most recent call last): + ... + ArithmeticError: No converging solution found, iteration limit reached + """ def f_derivative(x: float) -> float: return calc_derivative(f, x, step) @@ -49,4 +111,4 @@ func, x0=10, max_iter=100, step=1e-6, log_steps=True ) print(f"{solution=}, {err=}") - print("\n".join(str(x) for x in steps))+ print("\n".join(str(x) for x in steps))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/newton_raphson.py
Help me comply with documentation standards
from __future__ import annotations import math def prime_sieve(num: int) -> list[int]: if num <= 0: msg = f"{num}: Invalid input, please enter a positive integer." raise ValueError(msg) sieve = [True] * (num + 1) prime = [] start = 2 end = int(math.sqrt(num)) while start <= end: # If start is a prime if sieve[start] is True: prime.append(start) # Set multiples of start be False for i in range(start * start, num + 1, start): if sieve[i] is True: sieve[i] = False start += 1 for j in range(end + 1, num + 1): if sieve[j] is True: prime.append(j) return prime if __name__ == "__main__": print(prime_sieve(int(input("Enter a positive integer: ").strip())))
--- +++ @@ -1,38 +1,66 @@- -from __future__ import annotations - -import math - - -def prime_sieve(num: int) -> list[int]: - - if num <= 0: - msg = f"{num}: Invalid input, please enter a positive integer." - raise ValueError(msg) - - sieve = [True] * (num + 1) - prime = [] - start = 2 - end = int(math.sqrt(num)) - - while start <= end: - # If start is a prime - if sieve[start] is True: - prime.append(start) - - # Set multiples of start be False - for i in range(start * start, num + 1, start): - if sieve[i] is True: - sieve[i] = False - - start += 1 - - for j in range(end + 1, num + 1): - if sieve[j] is True: - prime.append(j) - - return prime - - -if __name__ == "__main__": - print(prime_sieve(int(input("Enter a positive integer: ").strip())))+""" +Sieve of Eratosthones + +The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or +equal to a given value. +Illustration: +https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif +Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes + +doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich) +Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem +""" + +from __future__ import annotations + +import math + + +def prime_sieve(num: int) -> list[int]: + """ + Returns a list with all prime numbers up to n. + + >>> prime_sieve(50) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] + >>> prime_sieve(25) + [2, 3, 5, 7, 11, 13, 17, 19, 23] + >>> prime_sieve(10) + [2, 3, 5, 7] + >>> prime_sieve(9) + [2, 3, 5, 7] + >>> prime_sieve(2) + [2] + >>> prime_sieve(1) + [] + """ + + if num <= 0: + msg = f"{num}: Invalid input, please enter a positive integer." + raise ValueError(msg) + + sieve = [True] * (num + 1) + prime = [] + start = 2 + end = int(math.sqrt(num)) + + while start <= end: + # If start is a prime + if sieve[start] is True: + prime.append(start) + + # Set multiples of start be False + for i in range(start * start, num + 1, start): + if sieve[i] is True: + sieve[i] = False + + start += 1 + + for j in range(end + 1, num + 1): + if sieve[j] is True: + prime.append(j) + + return prime + + +if __name__ == "__main__": + print(prime_sieve(int(input("Enter a positive integer: ").strip())))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sieve_of_eratosthenes.py
Create structured documentation for my script
from collections.abc import Sequence def assign_ranks(data: Sequence[float]) -> list[int]: ranked_data = sorted((value, index) for index, value in enumerate(data)) ranks = [0] * len(data) for position, (_, index) in enumerate(ranked_data): ranks[index] = position + 1 return ranks def calculate_spearman_rank_correlation( variable_1: Sequence[float], variable_2: Sequence[float] ) -> float: n = len(variable_1) rank_var1 = assign_ranks(variable_1) rank_var2 = assign_ranks(variable_2) # Calculate differences of ranks d = [rx - ry for rx, ry in zip(rank_var1, rank_var2)] # Calculate the sum of squared differences d_squared = sum(di**2 for di in d) # Calculate the Spearman's rank correlation coefficient rho = 1 - (6 * d_squared) / (n * (n**2 - 1)) return rho if __name__ == "__main__": import doctest doctest.testmod() # Example usage: print( f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) = }" ) print(f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) = }") print(f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 1, 2, 9, 5]) = }")
--- +++ @@ -2,6 +2,19 @@ def assign_ranks(data: Sequence[float]) -> list[int]: + """ + Assigns ranks to elements in the array. + + :param data: List of floats. + :return: List of ints representing the ranks. + + Example: + >>> assign_ranks([3.2, 1.5, 4.0, 2.7, 5.1]) + [3, 1, 4, 2, 5] + + >>> assign_ranks([10.5, 8.1, 12.4, 9.3, 11.0]) + [3, 1, 5, 2, 4] + """ ranked_data = sorted((value, index) for index, value in enumerate(data)) ranks = [0] * len(data) @@ -14,6 +27,30 @@ def calculate_spearman_rank_correlation( variable_1: Sequence[float], variable_2: Sequence[float] ) -> float: + """ + Calculates Spearman's rank correlation coefficient. + + :param variable_1: List of floats representing the first variable. + :param variable_2: List of floats representing the second variable. + :return: Spearman's rank correlation coefficient. + + Example Usage: + + >>> x = [1, 2, 3, 4, 5] + >>> y = [5, 4, 3, 2, 1] + >>> calculate_spearman_rank_correlation(x, y) + -1.0 + + >>> x = [1, 2, 3, 4, 5] + >>> y = [2, 4, 6, 8, 10] + >>> calculate_spearman_rank_correlation(x, y) + 1.0 + + >>> x = [1, 2, 3, 4, 5] + >>> y = [5, 1, 2, 9, 5] + >>> calculate_spearman_rank_correlation(x, y) + 0.6 + """ n = len(variable_1) rank_var1 = assign_ranks(variable_1) rank_var2 = assign_ranks(variable_2) @@ -42,4 +79,4 @@ print(f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) = }") - print(f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 1, 2, 9, 5]) = }")+ print(f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 1, 2, 9, 5]) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/spearman_rank_correlation_coefficient.py
Fill in missing docstrings in my code
import numpy as np def softmax(vector): # Calculate e^x for each x in your vector where e is Euler's # number (approximately 2.718) exponent_vector = np.exp(vector) # Add up the all the exponentials sum_of_exponents = np.sum(exponent_vector) # Divide every exponent by the sum of all exponents softmax_vector = exponent_vector / sum_of_exponents return softmax_vector if __name__ == "__main__": print(softmax((0,)))
--- +++ @@ -1,8 +1,43 @@+""" +This script demonstrates the implementation of the Softmax function. + +Its a function that takes as input a vector of K real numbers, and normalizes +it into a probability distribution consisting of K probabilities proportional +to the exponentials of the input numbers. After softmax, the elements of the +vector always sum up to 1. + +Script inspired from its corresponding Wikipedia article +https://en.wikipedia.org/wiki/Softmax_function +""" import numpy as np def softmax(vector): + """ + Implements the softmax function + + Parameters: + vector (np.array,list,tuple): A numpy array of shape (1,n) + consisting of real values or a similar list,tuple + + + Returns: + softmax_vec (np.array): The input numpy array after applying + softmax. + + The softmax vector adds up to one. We need to ceil to mitigate for + precision + >>> float(np.ceil(np.sum(softmax([1,2,3,4])))) + 1.0 + + >>> vec = np.array([5,5]) + >>> softmax(vec) + array([0.5, 0.5]) + + >>> softmax([0]) + array([1.]) + """ # Calculate e^x for each x in your vector where e is Euler's # number (approximately 2.718) @@ -18,4 +53,4 @@ if __name__ == "__main__": - print(softmax((0,)))+ print(softmax((0,)))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/softmax.py
Add docstrings that explain inputs and outputs
from math import factorial, radians def sin( angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10 ) -> float: # Simplify the angle to be between 360 and -360 degrees. angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians angle_in_radians = radians(angle_in_degrees) result = angle_in_radians a = 3 b = -1 for _ in range(accuracy): result += (b * (angle_in_radians**a)) / factorial(a) b = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(result, rounded_values_count) if __name__ == "__main__": __import__("doctest").testmod()
--- +++ @@ -1,3 +1,15 @@+""" +Calculate sin function. + +It's not a perfect function so I am rounding the result to 10 decimal places by default. + +Formula: sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ... +Where: x = angle in randians. + +Source: + https://www.homeschoolmath.net/teaching/sine_calculator.php + +""" from math import factorial, radians @@ -5,6 +17,30 @@ def sin( angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10 ) -> float: + """ + Implement sin function. + + >>> sin(0.0) + 0.0 + >>> sin(90.0) + 1.0 + >>> sin(180.0) + 0.0 + >>> sin(270.0) + -1.0 + >>> sin(0.68) + 0.0118679603 + >>> sin(1.97) + 0.0343762121 + >>> sin(64.0) + 0.8987940463 + >>> sin(9999.0) + -0.9876883406 + >>> sin(-689.0) + 0.5150380749 + >>> sin(89.7) + 0.9999862922 + """ # Simplify the angle to be between 360 and -360 degrees. angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) @@ -25,4 +61,4 @@ if __name__ == "__main__": - __import__("doctest").testmod()+ __import__("doctest").testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sin.py
Write docstrings for utility functions
def simplify(current_set: list[list]) -> list[list]: # Divide each row by magnitude of first term --> creates 'unit' matrix duplicate_set = current_set.copy() for row_index, row in enumerate(duplicate_set): magnitude = row[0] for column_index, column in enumerate(row): if magnitude == 0: current_set[row_index][column_index] = column continue current_set[row_index][column_index] = column / magnitude # Subtract to cancel term first_row = current_set[0] final_set = [first_row] current_set = current_set[1::] for row in current_set: temp_row = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(row) continue for column_index in range(len(row)): temp_row.append(first_row[column_index] - row[column_index]) final_set.append(temp_row) # Create next recursion iteration set if len(final_set[0]) != 3: current_first_row = final_set[0] current_first_column = [] next_iteration = [] for row in final_set[1::]: current_first_column.append(row[0]) next_iteration.append(row[1::]) resultant = simplify(next_iteration) for i in range(len(resultant)): resultant[i].insert(0, current_first_column[i]) resultant.insert(0, current_first_row) final_set = resultant return final_set def solve_simultaneous(equations: list[list]) -> list: if len(equations) == 0: raise IndexError("solve_simultaneous() requires n lists of length n+1") _length = len(equations) + 1 if any(len(item) != _length for item in equations): raise IndexError("solve_simultaneous() requires n lists of length n+1") for row in equations: if any(not isinstance(column, (int, float)) for column in row): raise ValueError("solve_simultaneous() requires lists of integers") if len(equations) == 1: return [equations[0][-1] / equations[0][0]] data_set = equations.copy() if any(0 in row for row in data_set): temp_data = data_set.copy() full_row = [] for row_index, row in enumerate(temp_data): if 0 not in row: full_row = data_set.pop(row_index) break if not full_row: raise ValueError("solve_simultaneous() requires at least 1 full equation") data_set.insert(0, full_row) useable_form = data_set.copy() simplified = simplify(useable_form) simplified = simplified[::-1] solutions: list = [] for row in simplified: current_solution = row[-1] if not solutions: if row[-2] == 0: solutions.append(0) continue solutions.append(current_solution / row[-2]) continue temp_row = row.copy()[: len(row) - 1 :] while temp_row[0] == 0: temp_row.pop(0) if len(temp_row) == 0: solutions.append(0) continue temp_row = temp_row[1::] temp_row = temp_row[::-1] for column_index, column in enumerate(temp_row): current_solution -= column * solutions[column_index] solutions.append(current_solution) final = [] for item in solutions: final.append(float(round(item, 5))) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() eq = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
--- +++ @@ -1,105 +1,142 @@- - -def simplify(current_set: list[list]) -> list[list]: - # Divide each row by magnitude of first term --> creates 'unit' matrix - duplicate_set = current_set.copy() - for row_index, row in enumerate(duplicate_set): - magnitude = row[0] - for column_index, column in enumerate(row): - if magnitude == 0: - current_set[row_index][column_index] = column - continue - current_set[row_index][column_index] = column / magnitude - # Subtract to cancel term - first_row = current_set[0] - final_set = [first_row] - current_set = current_set[1::] - for row in current_set: - temp_row = [] - # If first term is 0, it is already in form we want, so we preserve it - if row[0] == 0: - final_set.append(row) - continue - for column_index in range(len(row)): - temp_row.append(first_row[column_index] - row[column_index]) - final_set.append(temp_row) - # Create next recursion iteration set - if len(final_set[0]) != 3: - current_first_row = final_set[0] - current_first_column = [] - next_iteration = [] - for row in final_set[1::]: - current_first_column.append(row[0]) - next_iteration.append(row[1::]) - resultant = simplify(next_iteration) - for i in range(len(resultant)): - resultant[i].insert(0, current_first_column[i]) - resultant.insert(0, current_first_row) - final_set = resultant - return final_set - - -def solve_simultaneous(equations: list[list]) -> list: - if len(equations) == 0: - raise IndexError("solve_simultaneous() requires n lists of length n+1") - _length = len(equations) + 1 - if any(len(item) != _length for item in equations): - raise IndexError("solve_simultaneous() requires n lists of length n+1") - for row in equations: - if any(not isinstance(column, (int, float)) for column in row): - raise ValueError("solve_simultaneous() requires lists of integers") - if len(equations) == 1: - return [equations[0][-1] / equations[0][0]] - data_set = equations.copy() - if any(0 in row for row in data_set): - temp_data = data_set.copy() - full_row = [] - for row_index, row in enumerate(temp_data): - if 0 not in row: - full_row = data_set.pop(row_index) - break - if not full_row: - raise ValueError("solve_simultaneous() requires at least 1 full equation") - data_set.insert(0, full_row) - useable_form = data_set.copy() - simplified = simplify(useable_form) - simplified = simplified[::-1] - solutions: list = [] - for row in simplified: - current_solution = row[-1] - if not solutions: - if row[-2] == 0: - solutions.append(0) - continue - solutions.append(current_solution / row[-2]) - continue - temp_row = row.copy()[: len(row) - 1 :] - while temp_row[0] == 0: - temp_row.pop(0) - if len(temp_row) == 0: - solutions.append(0) - continue - temp_row = temp_row[1::] - temp_row = temp_row[::-1] - for column_index, column in enumerate(temp_row): - current_solution -= column * solutions[column_index] - solutions.append(current_solution) - final = [] - for item in solutions: - final.append(float(round(item, 5))) - return final[::-1] - - -if __name__ == "__main__": - import doctest - - doctest.testmod() - eq = [ - [2, 1, 1, 1, 1, 4], - [1, 2, 1, 1, 1, 5], - [1, 1, 2, 1, 1, 6], - [1, 1, 1, 2, 1, 7], - [1, 1, 1, 1, 2, 8], - ] - print(solve_simultaneous(eq)) - print(solve_simultaneous([[4, 2]]))+""" +https://en.wikipedia.org/wiki/Augmented_matrix + +This algorithm solves simultaneous linear equations of the form +λa + λb + λc + λd + ... = y as [λ, λ, λ, λ, ..., y] +Where λ & y are individual coefficients, the no. of equations = no. of coefficients - 1 + +Note in order to work there must exist 1 equation where all instances of λ and y != 0 +""" + + +def simplify(current_set: list[list]) -> list[list]: + """ + >>> simplify([[1, 2, 3], [4, 5, 6]]) + [[1.0, 2.0, 3.0], [0.0, 0.75, 1.5]] + >>> simplify([[5, 2, 5], [5, 1, 10]]) + [[1.0, 0.4, 1.0], [0.0, 0.2, -1.0]] + """ + # Divide each row by magnitude of first term --> creates 'unit' matrix + duplicate_set = current_set.copy() + for row_index, row in enumerate(duplicate_set): + magnitude = row[0] + for column_index, column in enumerate(row): + if magnitude == 0: + current_set[row_index][column_index] = column + continue + current_set[row_index][column_index] = column / magnitude + # Subtract to cancel term + first_row = current_set[0] + final_set = [first_row] + current_set = current_set[1::] + for row in current_set: + temp_row = [] + # If first term is 0, it is already in form we want, so we preserve it + if row[0] == 0: + final_set.append(row) + continue + for column_index in range(len(row)): + temp_row.append(first_row[column_index] - row[column_index]) + final_set.append(temp_row) + # Create next recursion iteration set + if len(final_set[0]) != 3: + current_first_row = final_set[0] + current_first_column = [] + next_iteration = [] + for row in final_set[1::]: + current_first_column.append(row[0]) + next_iteration.append(row[1::]) + resultant = simplify(next_iteration) + for i in range(len(resultant)): + resultant[i].insert(0, current_first_column[i]) + resultant.insert(0, current_first_row) + final_set = resultant + return final_set + + +def solve_simultaneous(equations: list[list]) -> list: + """ + >>> solve_simultaneous([[1, 2, 3],[4, 5, 6]]) + [-1.0, 2.0] + >>> solve_simultaneous([[0, -3, 1, 7],[3, 2, -1, 11],[5, 1, -2, 12]]) + [6.4, 1.2, 10.6] + >>> solve_simultaneous([]) + Traceback (most recent call last): + ... + IndexError: solve_simultaneous() requires n lists of length n+1 + >>> solve_simultaneous([[1, 2, 3],[1, 2]]) + Traceback (most recent call last): + ... + IndexError: solve_simultaneous() requires n lists of length n+1 + >>> solve_simultaneous([[1, 2, 3],["a", 7, 8]]) + Traceback (most recent call last): + ... + ValueError: solve_simultaneous() requires lists of integers + >>> solve_simultaneous([[0, 2, 3],[4, 0, 6]]) + Traceback (most recent call last): + ... + ValueError: solve_simultaneous() requires at least 1 full equation + """ + if len(equations) == 0: + raise IndexError("solve_simultaneous() requires n lists of length n+1") + _length = len(equations) + 1 + if any(len(item) != _length for item in equations): + raise IndexError("solve_simultaneous() requires n lists of length n+1") + for row in equations: + if any(not isinstance(column, (int, float)) for column in row): + raise ValueError("solve_simultaneous() requires lists of integers") + if len(equations) == 1: + return [equations[0][-1] / equations[0][0]] + data_set = equations.copy() + if any(0 in row for row in data_set): + temp_data = data_set.copy() + full_row = [] + for row_index, row in enumerate(temp_data): + if 0 not in row: + full_row = data_set.pop(row_index) + break + if not full_row: + raise ValueError("solve_simultaneous() requires at least 1 full equation") + data_set.insert(0, full_row) + useable_form = data_set.copy() + simplified = simplify(useable_form) + simplified = simplified[::-1] + solutions: list = [] + for row in simplified: + current_solution = row[-1] + if not solutions: + if row[-2] == 0: + solutions.append(0) + continue + solutions.append(current_solution / row[-2]) + continue + temp_row = row.copy()[: len(row) - 1 :] + while temp_row[0] == 0: + temp_row.pop(0) + if len(temp_row) == 0: + solutions.append(0) + continue + temp_row = temp_row[1::] + temp_row = temp_row[::-1] + for column_index, column in enumerate(temp_row): + current_solution -= column * solutions[column_index] + solutions.append(current_solution) + final = [] + for item in solutions: + final.append(float(round(item, 5))) + return final[::-1] + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + eq = [ + [2, 1, 1, 1, 1, 4], + [1, 2, 1, 1, 1, 5], + [1, 1, 2, 1, 1, 6], + [1, 1, 1, 2, 1, 7], + [1, 1, 1, 1, 2, 8], + ] + print(solve_simultaneous(eq)) + print(solve_simultaneous([[4, 2]]))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/simultaneous_linear_equation_solver.py
Write reusable docstrings
from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 == 1: temp = (temp * x) % mod return temp def is_carmichael_number(n: int) -> bool: if n <= 0 or not isinstance(n, int): msg = f"Number {n} must instead be a positive integer" raise ValueError(msg) return all( power(b, n - 1, n) == 1 for b in range(2, n) if greatest_common_divisor(b, n) == 1 ) if __name__ == "__main__": import doctest doctest.testmod() number = int(input("Enter number: ").strip()) if is_carmichael_number(number): print(f"{number} is a Carmichael Number.") else: print(f"{number} is not a Carmichael Number.")
--- +++ @@ -1,8 +1,27 @@+""" +== Carmichael Numbers == +A number n is said to be a Carmichael number if it +satisfies the following modular arithmetic condition: + + power(b, n-1) MOD n = 1, + for all b ranging from 1 to n such that b and + n are relatively prime, i.e, gcd(b, n) = 1 + +Examples of Carmichael Numbers: 561, 1105, ... +https://en.wikipedia.org/wiki/Carmichael_number +""" from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: + """ + Examples: + >>> power(2, 15, 3) + 2 + >>> power(5, 1, 30) + 5 + """ if y == 0: return 1 @@ -14,6 +33,35 @@ def is_carmichael_number(n: int) -> bool: + """ + Examples: + >>> is_carmichael_number(4) + False + >>> is_carmichael_number(561) + True + >>> is_carmichael_number(562) + False + >>> is_carmichael_number(900) + False + >>> is_carmichael_number(1105) + True + >>> is_carmichael_number(8911) + True + >>> is_carmichael_number(5.1) + Traceback (most recent call last): + ... + ValueError: Number 5.1 must instead be a positive integer + + >>> is_carmichael_number(-7) + Traceback (most recent call last): + ... + ValueError: Number -7 must instead be a positive integer + + >>> is_carmichael_number(0) + Traceback (most recent call last): + ... + ValueError: Number 0 must instead be a positive integer + """ if n <= 0 or not isinstance(n, int): msg = f"Number {n} must instead be a positive integer" @@ -35,4 +83,4 @@ if is_carmichael_number(number): print(f"{number} is a Carmichael Number.") else: - print(f"{number} is not a Carmichael Number.")+ print(f"{number} is not a Carmichael Number.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/carmichael_number.py
Generate docstrings with examples
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0: return False number_square = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,9 +1,44 @@+""" +== Automorphic Numbers == +A number n is said to be a Automorphic number if +the square of n "ends" in the same digits as n itself. + +Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... +https://en.wikipedia.org/wiki/Automorphic_number +""" # Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: + """ + # doctest: +NORMALIZE_WHITESPACE + This functions takes an integer number as input. + returns True if the number is automorphic. + >>> is_automorphic_number(-1) + False + >>> is_automorphic_number(0) + True + >>> is_automorphic_number(5) + True + >>> is_automorphic_number(6) + True + >>> is_automorphic_number(7) + False + >>> is_automorphic_number(25) + True + >>> is_automorphic_number(259918212890625) + True + >>> is_automorphic_number(259918212890636) + False + >>> is_automorphic_number(740081787109376) + True + >>> is_automorphic_number(5.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=5.0] must be an integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) @@ -21,4 +56,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/automorphic_number.py
Write docstrings for utility functions
PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) def armstrong_number(n: int) -> bool: if not isinstance(n, int) or n < 1: return False # Initialization of sum and number of digits. total = 0 number_of_digits = 0 temp = n # Calculation of digits of the number number_of_digits = len(str(n)) # Dividing number into separate digits and find Armstrong number temp = n while temp > 0: rem = temp % 10 total += rem**number_of_digits temp //= 10 return n == total def pluperfect_number(n: int) -> bool: if not isinstance(n, int) or n < 1: return False # Init a "histogram" of the digits digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] digit_total = 0 total = 0 temp = n while temp > 0: temp, rem = divmod(temp, 10) digit_histogram[rem] += 1 digit_total += 1 for cnt, i in zip(digit_histogram, range(len(digit_histogram))): total += cnt * i**digit_total return n == total def narcissistic_number(n: int) -> bool: if not isinstance(n, int) or n < 1: return False expo = len(str(n)) # the power that all digits will be raised to # check if sum of each digit multiplied expo times is equal to number return n == sum(int(i) ** expo for i in str(n)) def main(): num = int(input("Enter an integer to see if it is an Armstrong number: ").strip()) print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if pluperfect_number(num) else 'not '}an Armstrong number.") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -1,9 +1,27 @@+""" +An Armstrong number is equal to the sum of its own digits each raised to the +power of the number of digits. + +For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. + +Armstrong numbers are also called Narcissistic numbers and Pluperfect numbers. + +On-Line Encyclopedia of Integer Sequences entry: https://oeis.org/A005188 +""" PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) def armstrong_number(n: int) -> bool: + """ + Return True if n is an Armstrong number or False if it is not. + + >>> all(armstrong_number(n) for n in PASSING) + True + >>> any(armstrong_number(n) for n in FAILING) + False + """ if not isinstance(n, int) or n < 1: return False @@ -23,6 +41,13 @@ def pluperfect_number(n: int) -> bool: + """Return True if n is a pluperfect number or False if it is not + + >>> all(pluperfect_number(n) for n in PASSING) + True + >>> any(pluperfect_number(n) for n in FAILING) + False + """ if not isinstance(n, int) or n < 1: return False @@ -43,6 +68,13 @@ def narcissistic_number(n: int) -> bool: + """Return True if n is a narcissistic number or False if it is not. + + >>> all(narcissistic_number(n) for n in PASSING) + True + >>> any(narcissistic_number(n) for n in FAILING) + False + """ if not isinstance(n, int) or n < 1: return False expo = len(str(n)) # the power that all digits will be raised to @@ -51,6 +83,9 @@ def main(): + """ + Request that user input an integer and tell them if it is Armstrong number. + """ num = int(input("Enter an integer to see if it is an Armstrong number: ").strip()) print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.") @@ -61,4 +96,4 @@ import doctest doctest.testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/armstrong_numbers.py
Help me document legacy Python code
def bell_numbers(max_set_length: int) -> list[int]: if max_set_length < 0: raise ValueError("max_set_length must be non-negative") bell = [0] * (max_set_length + 1) bell[0] = 1 for i in range(1, max_set_length + 1): for j in range(i): bell[i] += _binomial_coefficient(i - 1, j) * bell[j] return bell def _binomial_coefficient(total_elements: int, elements_to_choose: int) -> int: if elements_to_choose in {0, total_elements}: return 1 elements_to_choose = min(elements_to_choose, total_elements - elements_to_choose) coefficient = 1 for i in range(elements_to_choose): coefficient *= total_elements - i coefficient //= i + 1 return coefficient if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,37 @@+""" +Bell numbers represent the number of ways to partition a set into non-empty +subsets. This module provides functions to calculate Bell numbers for sets of +integers. In other words, the first (n + 1) Bell numbers. + +For more information about Bell numbers, refer to: +https://en.wikipedia.org/wiki/Bell_number +""" def bell_numbers(max_set_length: int) -> list[int]: + """ + Calculate Bell numbers for the sets of lengths from 0 to max_set_length. + In other words, calculate first (max_set_length + 1) Bell numbers. + + Args: + max_set_length (int): The maximum length of the sets for which + Bell numbers are calculated. + + Returns: + list: A list of Bell numbers for sets of lengths from 0 to max_set_length. + + Examples: + >>> bell_numbers(-2) + Traceback (most recent call last): + ... + ValueError: max_set_length must be non-negative + >>> bell_numbers(0) + [1] + >>> bell_numbers(1) + [1, 1] + >>> bell_numbers(5) + [1, 1, 2, 5, 15, 52] + """ if max_set_length < 0: raise ValueError("max_set_length must be non-negative") @@ -15,6 +46,22 @@ def _binomial_coefficient(total_elements: int, elements_to_choose: int) -> int: + """ + Calculate the binomial coefficient C(total_elements, elements_to_choose) + + Args: + total_elements (int): The total number of elements. + elements_to_choose (int): The number of elements to choose. + + Returns: + int: The binomial coefficient C(total_elements, elements_to_choose). + + Examples: + >>> _binomial_coefficient(5, 2) + 10 + >>> _binomial_coefficient(6, 3) + 20 + """ if elements_to_choose in {0, total_elements}: return 1 @@ -31,4 +78,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/bell_numbers.py
Write documentation strings for class attributes
def catalan(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) current_number = 1 for i in range(1, number): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,34 @@+""" + +Calculate the nth Catalan number + +Source: + https://en.wikipedia.org/wiki/Catalan_number + +""" def catalan(number: int) -> int: + """ + :param number: nth catalan number to calculate + :return: the nth catalan number + Note: A catalan number is only defined for positive integers + + >>> catalan(5) + 14 + >>> catalan(0) + Traceback (most recent call last): + ... + ValueError: Input value of [number=0] must be > 0 + >>> catalan(-1) + Traceback (most recent call last): + ... + ValueError: Input value of [number=-1] must be > 0 + >>> catalan(5.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=5.0] must be an integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" @@ -22,4 +50,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/catalan_number.py
Help me document legacy Python code
def hamming(n_element: int) -> list: n_element = int(n_element) if n_element < 1: my_error = ValueError("n_element should be a positive number") raise my_error hamming_list = [1] i, j, k = (0, 0, 0) index = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5) ) index += 1 return hamming_list if __name__ == "__main__": n = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") hamming_numbers = hamming(int(n)) print("-----------------------------------------------------") print(f"The list with nth numbers is: {hamming_numbers}") print("-----------------------------------------------------")
--- +++ @@ -1,6 +1,29 @@+""" +A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some +non-negative integers i, j, and k. They are often referred to as regular numbers. +More info at: https://en.wikipedia.org/wiki/Regular_number. +""" def hamming(n_element: int) -> list: + """ + This function creates an ordered list of n length as requested, and afterwards + returns the last value of the list. It must be given a positive integer. + + :param n_element: The number of elements on the list + :return: The nth element of the list + + >>> hamming(-5) + Traceback (most recent call last): + ... + ValueError: n_element should be a positive number + >>> hamming(5) + [1, 2, 3, 4, 5] + >>> hamming(10) + [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] + >>> hamming(15) + [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] + """ n_element = int(n_element) if n_element < 1: my_error = ValueError("n_element should be a positive number") @@ -29,4 +52,4 @@ hamming_numbers = hamming(int(n)) print("-----------------------------------------------------") print(f"The list with nth numbers is: {hamming_numbers}") - print("-----------------------------------------------------")+ print("-----------------------------------------------------")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/hamming_numbers.py
Write docstrings for this repository
def int_to_base(number: int, base: int) -> str: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" if number < 0: raise ValueError("number must be a positive integer") while number > 0: number, remainder = divmod(number, base) result = digits[remainder] + result if result == "": result = "0" return result def sum_of_digits(num: int, base: int) -> str: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") num_str = int_to_base(num, base) res = sum(int(char, base) for char in num_str) res_str = int_to_base(res, base) return res_str def harshad_numbers_in_base(limit: int, base: int) -> list[str]: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if limit < 0: return [] numbers = [ int_to_base(i, base) for i in range(1, limit) if i % int(sum_of_digits(i, base), base) == 0 ] return numbers def is_harshad_number_in_base(num: int, base: int) -> bool: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if num < 0: return False n = int_to_base(num, base) d = sum_of_digits(num, base) return int(n, base) % int(d, base) == 0 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,38 @@+""" +A harshad number (or more specifically an n-harshad number) is a number that's +divisible by the sum of its digits in some given base n. +Reference: https://en.wikipedia.org/wiki/Harshad_number +""" def int_to_base(number: int, base: int) -> str: + """ + Convert a given positive decimal integer to base 'base'. + Where 'base' ranges from 2 to 36. + + Examples: + >>> int_to_base(0, 21) + '0' + >>> int_to_base(23, 2) + '10111' + >>> int_to_base(58, 5) + '213' + >>> int_to_base(167, 16) + 'A7' + >>> # bases below 2 and beyond 36 will error + >>> int_to_base(98, 1) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + >>> int_to_base(98, 37) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + >>> int_to_base(-99, 16) + Traceback (most recent call last): + ... + ValueError: number must be a positive integer + """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") @@ -22,6 +54,28 @@ def sum_of_digits(num: int, base: int) -> str: + """ + Calculate the sum of digit values in a positive integer + converted to the given 'base'. + Where 'base' ranges from 2 to 36. + + Examples: + >>> sum_of_digits(103, 12) + '13' + >>> sum_of_digits(1275, 4) + '30' + >>> sum_of_digits(6645, 2) + '1001' + >>> # bases below 2 and beyond 36 will error + >>> sum_of_digits(543, 1) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + >>> sum_of_digits(543, 37) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") @@ -33,6 +87,29 @@ def harshad_numbers_in_base(limit: int, base: int) -> list[str]: + """ + Finds all Harshad numbers smaller than num in base 'base'. + Where 'base' ranges from 2 to 36. + + Examples: + >>> harshad_numbers_in_base(15, 2) + ['1', '10', '100', '110', '1000', '1010', '1100'] + >>> harshad_numbers_in_base(12, 34) + ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B'] + >>> harshad_numbers_in_base(12, 4) + ['1', '2', '3', '10', '12', '20', '21'] + >>> # bases below 2 and beyond 36 will error + >>> harshad_numbers_in_base(234, 37) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + >>> harshad_numbers_in_base(234, 1) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + >>> harshad_numbers_in_base(-12, 6) + [] + """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") @@ -50,6 +127,27 @@ def is_harshad_number_in_base(num: int, base: int) -> bool: + """ + Determines whether n in base 'base' is a harshad number. + Where 'base' ranges from 2 to 36. + + Examples: + >>> is_harshad_number_in_base(18, 10) + True + >>> is_harshad_number_in_base(21, 10) + True + >>> is_harshad_number_in_base(-21, 5) + False + >>> # bases below 2 and beyond 36 will error + >>> is_harshad_number_in_base(45, 37) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + >>> is_harshad_number_in_base(45, 1) + Traceback (most recent call last): + ... + ValueError: 'base' must be between 2 and 36 inclusive + """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") @@ -65,4 +163,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/harshad_numbers.py
Document classes and their methods
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def hexagonal(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise ValueError("Input must be a positive integer") return number * (2 * number - 1) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,40 @@+""" +== Hexagonal Number == +The nth hexagonal number hn is the number of distinct dots +in a pattern of dots consisting of the outlines of regular +hexagons with sides up to n dots, when the hexagons are +overlaid so that they share one vertex. + +https://en.wikipedia.org/wiki/Hexagonal_number +""" # Author : Akshay Dubey (https://github.com/itsAkshayDubey) def hexagonal(number: int) -> int: + """ + :param number: nth hexagonal number to calculate + :return: the nth hexagonal number + Note: A hexagonal number is only defined for positive integers + >>> hexagonal(4) + 28 + >>> hexagonal(11) + 231 + >>> hexagonal(22) + 946 + >>> hexagonal(0) + Traceback (most recent call last): + ... + ValueError: Input must be a positive integer + >>> hexagonal(-1) + Traceback (most recent call last): + ... + ValueError: Input must be a positive integer + >>> hexagonal(11.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=11.0] must be an integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) @@ -14,4 +46,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/hexagonal_number.py
Add docstrings following best practices
def factorial(digit: int) -> int: return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: fact_sum = 0 duplicate = number while duplicate > 0: duplicate, digit = divmod(duplicate, 10) fact_sum += factorial(digit) return fact_sum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") number = int(input("Enter number: ").strip()) print( f"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number." )
--- +++ @@ -1,11 +1,37 @@+""" + == Krishnamurthy Number == +It is also known as Peterson Number +A Krishnamurthy Number is a number whose sum of the +factorial of the digits equals to the original +number itself. + +For example: 145 = 1! + 4! + 5! + So, 145 is a Krishnamurthy Number +""" def factorial(digit: int) -> int: + """ + >>> factorial(3) + 6 + >>> factorial(0) + 1 + >>> factorial(5) + 120 + """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: + """ + >>> krishnamurthy(145) + True + >>> krishnamurthy(240) + False + >>> krishnamurthy(1) + True + """ fact_sum = 0 duplicate = number @@ -20,4 +46,4 @@ number = int(input("Enter number: ").strip()) print( f"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number." - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/krishnamurthy_number.py
Create docstrings for each class method
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def is_pronic(number: int) -> bool: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0 or number % 2 == 1: return False number_sqrt = int(number**0.5) return number == number_sqrt * (number_sqrt + 1) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,45 @@+""" +== Pronic Number == +A number n is said to be a Proic number if +there exists an integer m such that n = m * (m + 1) + +Examples of Proic Numbers: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110 ... +https://en.wikipedia.org/wiki/Pronic_number +""" # Author : Akshay Dubey (https://github.com/itsAkshayDubey) def is_pronic(number: int) -> bool: + """ + # doctest: +NORMALIZE_WHITESPACE + This functions takes an integer number as input. + returns True if the number is pronic. + >>> is_pronic(-1) + False + >>> is_pronic(0) + True + >>> is_pronic(2) + True + >>> is_pronic(5) + False + >>> is_pronic(6) + True + >>> is_pronic(8) + False + >>> is_pronic(30) + True + >>> is_pronic(32) + False + >>> is_pronic(2147441940) + True + >>> is_pronic(9223372033963249500) + True + >>> is_pronic(6.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=6.0] must be an integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) @@ -15,4 +52,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/pronic_number.py
Document this module using docstrings
def ugly_numbers(n: int) -> int: ugly_nums = [1] i2, i3, i5 = 0, 0, 0 next_2 = ugly_nums[i2] * 2 next_3 = ugly_nums[i3] * 3 next_5 = ugly_nums[i5] * 5 for _ in range(1, n): next_num = min(next_2, next_3, next_5) ugly_nums.append(next_num) if next_num == next_2: i2 += 1 next_2 = ugly_nums[i2] * 2 if next_num == next_3: i3 += 1 next_3 = ugly_nums[i3] * 3 if next_num == next_5: i5 += 1 next_5 = ugly_nums[i5] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(f"{ugly_numbers(200) = }")
--- +++ @@ -1,6 +1,30 @@+""" +Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence +1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, +1 is included. +Given an integer n, we have to find the nth ugly number. + +For more details, refer this article +https://www.geeksforgeeks.org/ugly-numbers/ +""" def ugly_numbers(n: int) -> int: + """ + Returns the nth ugly number. + >>> ugly_numbers(100) + 1536 + >>> ugly_numbers(0) + 1 + >>> ugly_numbers(20) + 36 + >>> ugly_numbers(-5) + 1 + >>> ugly_numbers(-5.5) + Traceback (most recent call last): + ... + TypeError: 'float' object cannot be interpreted as an integer + """ ugly_nums = [1] i2, i3, i5 = 0, 0, 0 @@ -27,4 +51,4 @@ from doctest import testmod testmod(verbose=True) - print(f"{ugly_numbers(200) = }")+ print(f"{ugly_numbers(200) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/ugly_numbers.py
Create simple docstrings for beginners
def triangular_number(position: int) -> int: if position < 0: raise ValueError("param `position` must be non-negative") return position * (position + 1) // 2 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,36 @@+""" +A triangular number or triangle number counts objects arranged in an +equilateral triangle. This module provides a function to generate n'th +triangular number. + +For more information about triangular numbers, refer to: +https://en.wikipedia.org/wiki/Triangular_number +""" def triangular_number(position: int) -> int: + """ + Generate the triangular number at the specified position. + + Args: + position (int): The position of the triangular number to generate. + + Returns: + int: The triangular number at the specified position. + + Raises: + ValueError: If `position` is negative. + + Examples: + >>> triangular_number(1) + 1 + >>> triangular_number(3) + 6 + >>> triangular_number(-1) + Traceback (most recent call last): + ... + ValueError: param `position` must be non-negative + """ if position < 0: raise ValueError("param `position` must be non-negative") @@ -10,4 +40,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/triangular_numbers.py