repo_name
stringclasses
25 values
repo_full_name
stringclasses
25 values
owner
stringclasses
25 values
stars
int64
117k
496k
license
stringclasses
7 values
repo_description
stringclasses
25 values
filepath
stringlengths
9
75
file_type
stringclasses
3 values
language
stringclasses
2 values
content
stringlengths
24
383k
size_bytes
int64
25
387k
num_lines
int64
2
4.44k
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\md5.py
python
Python
""" The MD5 algorithm is a hash function that's commonly used as a checksum to detect data corruption. The algorithm works by processing a given message in blocks of 512 bits, padding the message as needed. It uses the blocks to operate a 128-bit state and performs a total of 64 such operations. Note that all values ar...
11,845
445
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\README.md
readme
Markdown
# Hashes Hashing is the process of mapping any amount of data to a specified size using an algorithm. This is known as a hash value (or, if you're feeling fancy, a hash code, hash sums, or even a hash digest). Hashing is a one-way function, whereas encryption is a two-way function. While it is functionally conceivable ...
2,723
18
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\sdbm.py
python
Python
""" This algorithm was created for sdbm (a public-domain reimplementation of ndbm) database library. It was found to do well in scrambling bits, causing better distribution of the keys and fewer splits. It also happens to be a good general hashing function with good distribution. The actual function (pseudo code) is: ...
1,381
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\sha1.py
python
Python
""" Implementation of the SHA1 hash function and gives utilities to find hash of string or hash of text from a file. Also contains a Test class to verify that the generated hash matches what is returned by the hashlib library Usage: python sha1.py --string "Hello World!!" python sha1.py --file "hello_world.txt"...
6,489
169
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\sha256.py
python
Python
# Author: M. Yathurshan # Black Formatter: True """ Implementation of SHA256 Hash function in a Python class and provides utilities to find hash of string or hash of text from a file. Usage: python sha256.py --string "Hello World!!" python sha256.py --file "hello_world.txt" When run without any argument...
7,171
249
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
knapsack\greedy_knapsack.py
python
Python
# To get an insight into Greedy Algorithm through the Knapsack problem """ A shopkeeper has bags of wheat that each have different weights and different profits. eg. profit 5 8 7 1 12 3 4 weight 2 7 1 6 4 2 5 max_weight 100 Constraints: max_weight > 0 profit[i] >= 0 weight[i] >= 0 Calculate the maximum profit that ...
3,809
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
knapsack\knapsack.py
python
Python
"""A recursive implementation of 0-N Knapsack Problem https://en.wikipedia.org/wiki/Knapsack_problem """ from __future__ import annotations from functools import lru_cache def knapsack( capacity: int, weights: list[int], values: list[int], counter: int, allow_repetition=False, ) -> int: """ ...
2,217
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
knapsack\README.md
readme
Markdown
# A recursive implementation of 0-N Knapsack Problem This overview is taken from: https://en.wikipedia.org/wiki/Knapsack_problem --- ## Overview The knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in...
1,534
33
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
knapsack\recursive_approach_knapsack.py
python
Python
# To get an insight into naive recursive way to solve the Knapsack problem """ A shopkeeper has bags of wheat that each have different weights and different profits. eg. no_of_items 4 profit 5 4 8 6 weight 1 2 4 5 max_weight 5 Constraints: max_weight > 0 profit[i] >= 0 weight[i] >= 0 Calculate the maximum profit that...
1,474
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
knapsack\tests\test_greedy_knapsack.py
test
Python
import unittest import pytest from knapsack import greedy_knapsack as kp class TestClass(unittest.TestCase): """ Test cases for knapsack """ def test_sorted(self): """ kp.calc_profit takes the required argument (profit, weight, max_weight) and returns whether the answer matc...
2,420
78
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
knapsack\tests\test_knapsack.py
test
Python
""" Created on Fri Oct 16 09:31:07 2020 @author: Dr. Tobias Schröder @license: MIT-license This file contains the test-suite for the knapsack problem. """ import unittest from knapsack import knapsack as k class Test(unittest.TestCase): def test_base_case(self): """ test for the base case ...
1,358
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\gaussian_elimination.py
python
Python
""" | Gaussian elimination method for solving a system of linear equations. | Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination """ import numpy as np from numpy import float64 from numpy.typing import NDArray def retroactive_resolution( coefficients: NDArray[float64], vector: NDArray[flo...
2,738
96
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\jacobi_iteration_method.py
python
Python
""" Jacobi Iteration Method - https://en.wikipedia.org/wiki/Jacobi_method """ from __future__ import annotations import numpy as np from numpy import float64 from numpy.typing import NDArray # Method to find solution of system of linear equations def jacobi_iteration_method( coefficient_matrix: NDArray[float64]...
6,679
205
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\lu_decomposition.py
python
Python
""" Lower-upper (LU) decomposition factors a matrix as a product of a lower triangular matrix and an upper triangular matrix. A square matrix has an LU decomposition under the following conditions: - If the matrix is invertible, then it has an LU decomposition if and only if all of its leading principal mino...
4,058
115
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\matrix_inversion.py
python
Python
import numpy as np def invert_matrix(matrix: list[list[float]]) -> list[list[float]]: """ Returns the inverse of a square matrix using NumPy. Parameters: matrix (list[list[float]]): A square matrix. Returns: list[list[float]]: Inverted matrix if invertible, else raises error. >>> invert...
976
37
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\README.md
readme
Markdown
# Linear algebra library for Python This module contains classes and functions for doing linear algebra. --- ## Overview ### class Vector - - This class represents a vector of arbitrary size and related operations. **Overview of the methods:** - constructor(components) : init the vector - set(comp...
2,740
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\conjugate_gradient.py
python
Python
""" Resources: - https://en.wikipedia.org/wiki/Conjugate_gradient_method - https://en.wikipedia.org/wiki/Definite_symmetric_matrix """ from typing import Any import numpy as np def _is_matrix_spd(matrix: np.ndarray) -> bool: """ Returns True if input matrix is symmetric positive definite. Returns False ...
5,330
181
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\gaussian_elimination_pivoting.py
python
Python
import numpy as np def solve_linear_system(matrix: np.ndarray) -> np.ndarray: """ Solve a linear system of equations using Gaussian elimination with partial pivoting Args: - `matrix`: Coefficient matrix with the last column representing the constants. Returns: - Solution vector. Rai...
2,778
89
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\lib.py
python
Python
""" Created on Mon Feb 26 14:29:11 2018 @author: Christian Bender @license: MIT-license This module contains some useful classes and functions for dealing with linear algebra in python. Overview: - class Vector - function zero_vector(dimension) - function unit_basis_vector(dimension, pos) - function axpy(scalar, ve...
14,751
445
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\polynom_for_points.py
python
Python
def points_to_polynomial(coordinates: list[list[int]]) -> str: """ coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> points_to_polynomial([]) Traceback (most recent call last): ... ValueError: The program cannot work out a fitting polyno...
4,032
104
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\power_iteration.py
python
Python
import numpy as np def power_iteration( input_matrix: np.ndarray, vector: np.ndarray, error_tol: float = 1e-12, max_iterations: int = 100, ) -> tuple[float, np.ndarray]: """ Power Iteration. Find the largest eigenvalue and corresponding eigenvector of matrix input_matrix given a random...
4,647
129
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\rank_of_matrix.py
python
Python
""" 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: ...
2,477
94
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\rayleigh_quotient.py
python
Python
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ from typing import Any import numpy as np def is_hermitian(matrix: np.ndarray) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) ...
1,623
70
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\schur_complement.py
python
Python
import unittest import numpy as np import pytest def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray | None = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices `A`, `B` a...
2,929
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\test_linear_algebra.py
test
Python
""" Created on Mon Feb 26 15:40:07 2018 @author: Christian Bender @license: MIT-license This file contains the test-suite for the linear algebra library. """ import unittest import pytest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class ...
6,231
213
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_algebra\src\transformations_2d.py
python
Python
""" 2D Transformations are regularly used in Linear Algebra. I have added the codes for reflection, projection, scaling and rotation 2D matrices. .. code-block:: python scaling(5) = [[5.0, 0.0], [0.0, 5.0]] rotation(45) = [[0.5253219888177297, -0.8509035245341184], [0.8509035245341184, 0....
1,964
65
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
linear_programming\simplex.py
python
Python
""" Python implementation of the simplex algorithm for solving linear programs in tabular form with - `>=`, `<=`, and `=` constraints and - each variable `x1, x2, ...>= 0`. See https://gist.github.com/imengus/f9619a568f7da5bc74eaf20169a24d98 for how to convert linear programs to simplex tableaus, and the steps taken i...
12,175
340
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\apriori_algorithm.py
python
Python
""" Apriori Algorithm is a Association rule mining technique, also known as market basket analysis, aims to discover interesting relationships or associations among a set of items in a transactional or relational database. For example, Apriori Algorithm states: "If a customer buys item A and item B, then they are like...
4,233
120
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\astar.py
python
Python
""" The A* algorithm combines features of uniform-cost search and pure heuristic search to efficiently compute optimal solutions. The A* algorithm is a best-first search algorithm in which the cost associated with a node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the initial state to node n and h(n...
4,329
149
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\automatic_differentiation.py
python
Python
""" Demonstration of the Automatic Differentiation (Reverse mode). Reference: https://en.wikipedia.org/wiki/Automatic_differentiation Author: Poojan Smart Email: smrtpoojan@gmail.com """ from __future__ import annotations from collections import defaultdict from enum import Enum from types import TracebackType from...
10,635
329
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\data_transformations.py
python
Python
""" Normalization. Wikipedia: https://en.wikipedia.org/wiki/Normalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between [0, 1] or [-1, 1]. The equation for normalization is x_norm = (x - x_min)/(x_max - x_min) where x_norm is the normalized val...
2,921
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\decision_tree.py
python
Python
""" Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ import numpy as np class DecisionTree: def __init__(self, depth=5, min_leaf_size=5): sel...
7,415
204
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\dimensionality_reduction.py
python
Python
# Copyright (c) 2023 Diego Gasco (diego.gasco99@gmail.com), Diegomangasco on GitHub """ Requirements: - numpy version 1.21 - scipy version 1.3.3 Notes: - Each column of the features matrix corresponds to a class item """ import logging import numpy as np import pytest from scipy.linalg import eigh logging.ba...
7,341
199
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\forecasting\run.py
python
Python
""" this is code for forecasting but I modified it and used it for safety checker of data for ex: you have an online shop and for some reason some data are missing (the amount of data that u expected are not supposed to be) then we can use it *ps : 1. ofc we can use normal statistic method but in this case ...
6,052
163
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\frequent_pattern_growth.py
python
Python
""" The Frequent Pattern Growth algorithm (FP-Growth) is a widely used data mining technique for discovering frequent itemsets in large transaction databases. It overcomes some of the limitations of traditional methods such as Apriori by efficiently constructing the FP-Tree WIKI: https://athena.ecs.csus.edu/~mei/asso...
11,204
351
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\gradient_boosting_classifier.py
python
Python
import numpy as np from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor class GradientBoostingClassifier: def __init__(self, n_estimators: int = 100, learning_rate: float = 0.1) -> None...
4,393
119
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\gradient_descent.py
python
Python
""" Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. """ 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), (...
4,535
140
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\k_means_clust.py
python
Python
"""README, Author - Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - sklearn - numpy - matplotlib Python: - 3.5 Inputs: - X , a 2D numpy array of features. - k , number of clusters to create. - initial_centroids , initial centroid values generated by utility function(mentioned in usage)....
13,739
364
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\k_nearest_neighbours.py
python
Python
""" k-Nearest Neighbours (kNN) is a simple non-parametric supervised learning algorithm used for classification. Given some labelled training data, a given point is classified using its k nearest neighbours according to some distance metric. The most commonly occurring label among the neighbours becomes the label of th...
3,055
89
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\linear_discriminant_analysis.py
python
Python
""" Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : T...
17,263
404
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\linear_regression.py
python
Python
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set th...
4,957
148
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\local_weighted_learning\local_weighted_learning.py
python
Python
""" 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 m...
6,294
186
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\local_weighted_learning\README.md
readme
Markdown
# Locally Weighted Linear Regression It is a non-parametric ML algorithm that does not learn on a fixed set of parameters such as **linear regression**. \ So, here comes a question of what is *linear regression*? \ **Linear regression** is a supervised learning algorithm used for computing linear relationships between ...
2,978
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\logistic_regression.py
python
Python
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import n...
5,241
160
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\loss_functions.py
python
Python
import numpy as np 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 predic...
25,618
670
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\lstm\lstm_prediction.py
python
Python
""" Create a Long Short Term Memory (LSTM) network model An LSTM is a type of Recurrent Neural Network (RNN) as discussed at: * https://colah.github.io/posts/2015-08-Understanding-LSTMs * https://en.wikipedia.org/wiki/Long_short-term_memory """ import numpy as np import pandas as pd from keras.layers import LSTM, Dens...
2,309
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\mfcc.py
python
Python
""" Mel Frequency Cepstral Coefficients (MFCC) Calculation MFCC is an algorithm widely used in audio and speech processing to represent the short-term power spectrum of a sound signal in a more compact and discriminative way. It is particularly popular in speech and audio processing tasks such as speech recognition an...
15,284
480
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\multilayer_perceptron_classifier.py
python
Python
from sklearn.neural_network import MLPClassifier X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]] y = [0, 1, 0, 0] clf = MLPClassifier( solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1 ) clf.fit(X, y) test = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]] Y = clf.predict(test) def wrapper(y): ...
506
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\polynomial_regression.py
python
Python
""" 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 re...
8,035
214
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\principle_component_analysis.py
python
Python
""" Principal Component Analysis (PCA) is a dimensionality reduction technique used in machine learning. It transforms high-dimensional data into a lower-dimensional representation while retaining as much variance as possible. This implementation follows best practices, including: - Standardizing the dataset. - Comput...
2,453
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\scoring_functions.py
python
Python
import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots ca...
3,562
140
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\self_organizing_map.py
python
Python
""" https://en.wikipedia.org/wiki/Self-organizing_map """ import math class SelfOrganizingMap: def get_winner(self, weights: list[list[float]], sample: list[int]) -> int: """ Compute the winning vector by Euclidean distance >>> SelfOrganizingMap().get_winner([[1, 2, 3], [4, 5, 6]], [1, 2...
2,150
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\sequential_minimum_optimization.py
python
Python
""" 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...
20,785
623
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\similarity_search.py
python
Python
""" 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: ...
5,617
163
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\support_vector_machines.py
python
Python
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def norm_squared(vector: ndarray) -> float: """ Return the squared second norm of vector norm_squared(v) = sum(x * x for x in v) Args: vector (ndarray): input vector Returns: ...
6,280
207
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\t_stochastic_neighbour_embedding.py
python
Python
""" t-distributed stochastic neighbor embedding (t-SNE) For more details, see: https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding """ import doctest import numpy as np from numpy import ndarray from sklearn.datasets import load_iris def collect_dataset() -> tuple[ndarray, ndarray]: """ ...
5,376
179
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\word_frequency_functions.py
python
Python
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 L...
5,237
138
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\xgboost_classifier.py
python
Python
# 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 data...
2,755
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
machine_learning\xgboost_regressor.py
python
Python
# XGBoost Regressor Example import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def data_handling(data: dict) -> tuple: # Split dataset int...
2,349
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\abs.py
python
Python
"""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]...
1,983
95
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\addition_without_arithmetic.py
python
Python
""" 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 ...
790
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\aliquot_sum.py
python
Python
def aliquot_sum(input_num: int) -> int: """ Finds the aliquot sum of an input integer, where the aliquot sum of a number n is defined as the sum of all natural numbers less than n that divide n evenly. For example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is a simple O(n) implementation. ...
1,454
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\allocation_number.py
python
Python
""" 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...
1,761
51
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\arc_length.py
python
Python
from math import pi def arc_length(angle: int, radius: int) -> float: """ >>> arc_length(45, 5) 3.9269908169872414 >>> arc_length(120, 15) 31.415926535897928 >>> arc_length(90, 10) 15.707963267948966 """ return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(...
357
18
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\area.py
python
Python
""" 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.3600...
19,639
584
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\area_under_curve.py
python
Python
""" Approximates the area under the curve using the trapezoidal rule """ 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: """ Treats curve as a collection o...
1,724
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\average_absolute_deviation.py
python
Python
def average_absolute_deviation(nums: list[int]) -> float: """ Return the average absolute deviation of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation >>> average_absolute_deviation([0]) 0.0 >>> average_absolute_deviation([4, 1, 3, 2]) 1.0 >>> average_a...
888
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\average_mean.py
python
Python
from __future__ import annotations def mean(nums: list) -> float: """ Find mean of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Mean >>> mean([3, 6, 9, 12, 15, 18, 21]) 12.0 >>> mean([5, 10, 15, 20, 25, 30, 35]) 20.0 >>> mean([1, 2, 3, 4, 5, 6, 7, 8]) 4.5 >>> mean([]...
602
29
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\average_median.py
python
Python
from __future__ import annotations def median(nums: list) -> int | float: """ Find median of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Median >>> median([0]) 0 >>> median([4, 1, 3, 2]) 2.5 >>> median([2, 70, 6, 50, 20, 8, 4]) 8 Args: nums: List of nums ...
845
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\average_mode.py
python
Python
from typing import Any def mode(input_list: list) -> list[Any]: """This function returns the mode(Mode as in the measures of central tendency) of the input data. The input list may contain any Datastructure or any Datatype. >>> mode([2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2]) [2] >>> mode([3...
935
33
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\bailey_borwein_plouffe.py
python
Python
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%93Pl...
3,691
90
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\base_neg2_conversion.py
python
Python
def decimal_to_negative_base_2(num: int) -> int: """ This function returns the number negative base 2 of the decimal number of the input data. Args: int: The decimal number to convert. Returns: int: The negative base 2 number. Examples: >>> decimal_to_negative_base...
834
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\basic_maths.py
python
Python
"""Implementation of Basic Math in Python.""" import math def prime_factors(n: int) -> list: """Find Prime Factors. >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(0) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors >>> prime_facto...
3,110
123
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\binary_exponentiation.py
python
Python
""" 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 od...
5,371
197
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\binary_multiplication.py
python
Python
""" 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, c...
2,347
102
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\binomial_coefficient.py
python
Python
def binomial_coefficient(n: int, r: int) -> int: """ Find binomial coefficient using Pascal's triangle. Calculate C(n, r) using Pascal's triangle. :param n: The total number of items. :param r: The number of items to choose. :return: The binomial coefficient C(n, r). >>> binomial_coeffici...
1,747
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\binomial_distribution.py
python
Python
"""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 succes...
1,547
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\ceil.py
python
Python
""" 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...
509
25
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\chebyshev_distance.py
python
Python
def chebyshev_distance(point_a: list[float], point_b: list[float]) -> float: """ This function calculates the Chebyshev distance (also known as the Chessboard distance) between two n-dimensional points represented as lists. https://en.wikipedia.org/wiki/Chebyshev_distance >>> chebyshev_distance([1...
773
21
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\check_polygon.py
python
Python
from __future__ import annotations def check_polygon(nums: list[float]) -> bool: """ Takes list of possible side lengths and determines whether a two-dimensional polygon with such side lengths can exist. Returns a boolean value for the < comparison of the largest side length with sum of the rest....
1,412
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\chinese_remainder_theorem.py
python
Python
""" 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. ...
2,380
97
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\chudnovsky_algorithm.py
python
Python
from decimal import Decimal, getcontext from math import ceil, factorial def pi(precision: int) -> str: """ The Chudnovsky algorithm is a fast method for calculating the digits of PI, based on Ramanujan's PI formulae. https://en.wikipedia.org/wiki/Chudnovsky_algorithm PI = constant_term / ((mult...
2,110
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\collatz_sequence.py
python
Python
""" 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...
2,596
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\combinations.py
python
Python
""" 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(2...
1,524
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\continued_fraction.py
python
Python
""" 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 fou...
1,641
58
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\decimal_isolate.py
python
Python
""" 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 d...
1,257
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\decimal_to_fraction.py
python
Python
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]: """ Return a decimal number in its simplest fraction form >>> decimal_to_fraction(2) (2, 1) >>> decimal_to_fraction(89.) (89, 1) >>> decimal_to_fraction("67") (67, 1) >>> decimal_to_fraction("45.0") (45, 1) >>>...
2,030
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\dodecahedron.py
python
Python
# 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) ...
2,182
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\double_factorial.py
python
Python
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_...
2,134
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\dual_number_automatic_differentiation.py
python
Python
from math import factorial """ https://en.wikipedia.org/wiki/Automatic_differentiation#Automatic_differentiation_using_dual_numbers https://blog.jliszka.org/2013/10/24/exact-numeric-nth-derivatives.html Note this only works for basic functions, f(x) where the power of x is positive. """ class Dual: def __init__...
4,526
140
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\entropy.py
python
Python
#!/usr/bin/env python3 """ Implementation of entropy of information https://en.wikipedia.org/wiki/Entropy_(information_theory) """ from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def calculate_prob(text: str) -> None: """ This method takes p...
4,990
133
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\euclidean_distance.py
python
Python
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) -> Vec...
1,999
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\euler_method.py
python
Python
from collections.abc import Callable import numpy as np def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.or...
1,266
48
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\euler_modified.py
python
Python
from collections.abc import Callable import numpy as np def euler_modified( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """ Calculate solution at each step to an ODE using Euler's Modified Method The Euler Method is straightforward to implement, but can't...
1,502
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\eulers_totient.py
python
Python
# Eulers Totient function finds the number of relative primes of a number n from 1 to n def totient(n: int) -> list: """ >>> n = 10 >>> totient_calculation = totient(n) >>> for i in range(1, n): ... print(f"{i} has {totient_calculation[i]} relative primes.") 1 has 0 relative primes. 2 ha...
1,204
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\extended_euclidean_algorithm.py
python
Python
""" 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 # @Email: silentcat@protonmail.com # @Last ...
2,142
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\factorial.py
python
Python
""" 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...
1,987
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\factors.py
python
Python
from doctest import testmod from math import sqrt def factors_of_a_number(num: int) -> list: """ >>> factors_of_a_number(1) [1] >>> factors_of_a_number(5) [1, 5] >>> factors_of_a_number(24) [1, 2, 3, 4, 6, 8, 12, 24] >>> factors_of_a_number(-24) [] """ facs: list[int] = [] ...
879
35
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\fast_inverse_sqrt.py
python
Python
""" 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 squ...
1,744
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\fermat_little_theorem.py
python
Python
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals # a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_...
870
31