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
maths\fibonacci.py
python
Python
""" 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 mu...
9,356
333
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\find_max.py
python
Python
from __future__ import annotations 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...
2,628
85
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\find_min.py
python
Python
from __future__ import annotations 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(nu...
2,715
88
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\floor.py
python
Python
""" 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, ...
505
23
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\gamma.py
python
Python
""" 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 defin...
3,639
117
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\gaussian.py
python
Python
""" 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....
1,712
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\gcd_of_n_numbers.py
python
Python
""" Gcd of N Numbers Reference: https://en.wikipedia.org/wiki/Greatest_common_divisor """ from collections import Counter 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) ...
3,532
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\geometric_mean.py
python
Python
""" 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. ...
1,906
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\germain_primes.py
python
Python
""" 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...
1,970
73
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\greatest_common_divisor.py
python
Python
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common...
2,172
82
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\hardy_ramanujanalgo.py
python
Python
# This theorem states that the number of prime factors of n # will be approximately log(log(n)) for most natural numbers n import math def exact_prime_factor_count(n: int) -> int: """ >>> exact_prime_factor_count(51242183) 3 """ count = 0 if n % 2 == 0: count += 1 while n % 2 ...
1,088
46
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\integer_square_root.py
python
Python
""" 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_...
2,291
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\interquartile_range.py
python
Python
""" 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_...
1,961
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\is_int_palindrome.py
python
Python
def is_int_palindrome(num: int) -> bool: """ Returns whether `num` is a palindrome or not (see for reference https://en.wikipedia.org/wiki/Palindromic_number). >>> is_int_palindrome(-121) False >>> is_int_palindrome(0) True >>> is_int_palindrome(10) False >>> is_int_palindrome(1...
723
35
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\is_ip_v4_address_valid.py
python
Python
""" 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...
1,727
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\is_square_free.py
python
Python
""" 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. ...
946
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\jaccard_similarity.py
python
Python
""" 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 Wikip...
3,340
96
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\joint_probability_distribution.py
python
Python
""" Calculate joint probability distribution https://en.wikipedia.org/wiki/Joint_probability_distribution """ def joint_probability_distribution( x_values: list[int], y_values: list[int], x_probabilities: list[float], y_probabilities: list[float], ) -> dict: """ >>> joint_distribution = joint...
4,112
125
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\josephus_problem.py
python
Python
""" 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 ...
4,140
131
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\juggler_sequence.py
python
Python
""" == 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 """...
1,938
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\karatsuba.py
python
Python
"""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 m1 = max(len(str(a)), len(str(b))) m...
677
33
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\kth_lexicographic_permutation.py
python
Python
def kth_permutation(k, n): """ Finds k'th lexicographic permutation (in increasing order) of 0,1,2,...n-1 in O(n^2) time. Examples: First permutation is always 0,1,2,...n >>> kth_permutation(0,5) [0, 1, 2, 3, 4] The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], ...
1,088
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\largest_of_very_large_numbers.py
python
Python
# Author: Abhijeeth S import math def res(x, y): """ Reduces large number to a more manageable number >>> res(5, 7) 4.892790030352132 >>> res(0, 5) 0 >>> res(3, 0) 1 >>> res(-1, 5) Traceback (most recent call last): ... ValueError: expected a positive input """ ...
1,371
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\least_common_multiple.py
python
Python
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: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> ...
2,296
77
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\line_length.py
python
Python
from __future__ import annotations import math from collections.abc import Callable def line_length( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: """ Approximates the arc length of a line segment by treating the curve as a sequence of linear l...
1,727
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\liouville_lambda.py
python
Python
""" == 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/itsAkshayDub...
1,414
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\lucas_lehmer_primality_test.py
test
Python
""" In mathematics, the Lucas-Lehmer test (LLT) is a primality test for Mersenne numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test A Mersenne number is a number that is one less than a power of two. That is M_p = 2^p - 1 https://en.wikipedia.org/wiki/Mersenne_prime The Lucas-Lehmer test is t...
1,013
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\lucas_series.py
python
Python
""" 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 ...
1,910
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\maclaurin_series.py
python
Python
""" 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 ...
3,875
124
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\manhattan_distance.py
python
Python
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 ...
4,251
127
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\matrix_exponentiation.py
python
Python
"""Matrix Exponentiation""" 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: d...
3,515
129
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\max_sum_sliding_window.py
python
Python
""" 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 t...
1,451
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\minkowski_distance.py
python
Python
def minkowski_distance( point_a: list[float], point_b: list[float], order: int, ) -> float: """ This function calculates the Minkowski distance for a given order between two n-dimensional points represented as lists. For the case of order = 1, the Minkowski distance degenerates to the Manhat...
1,526
46
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\mobius_function.py
python
Python
""" 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 ...
972
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\modular_division.py
python
Python
from __future__ import annotations 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...
3,822
163
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\modular_exponential.py
python
Python
""" 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_expo...
906
46
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\monte_carlo.py
python
Python
""" @author: MatteoRaso """ from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean 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. Inscr...
4,708
132
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\monte_carlo_dice.py
python
Python
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): """Initialize a six sided dice""" self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def throw_dice(num_throws: int, num_dice: int = 2) ...
1,304
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\number_of_digits.py
python
Python
import math from timeit import timeit 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 TypeEr...
2,735
114
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\adams_bashforth.py
python
Python
""" 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 import numpy as np @dataclass class AdamsBashforth: """ args: func: An ordin...
7,330
232
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\bisection.py
python
Python
from collections.abc import Callable def bisection(function: Callable[[float], float], a: float, b: float) -> float: """ finds where function becomes 0 in [a,b] using bolzano >>> bisection(lambda x: x ** 3 - 1, -5, 5) 1.0000000149011612 >>> bisection(lambda x: x ** 3 - 1, 2, 1000) Traceback (m...
1,725
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\bisection_2.py
python
Python
""" 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/Bise...
1,478
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\integration_by_simpson_approx.py
python
Python
""" 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://c...
4,001
122
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\intersection.py
python
Python
import math from collections.abc import Callable 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 >>> int...
1,709
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\nevilles_method.py
python
Python
""" 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-...
1,880
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\newton_forward_interpolation.py
python
Python
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/ from __future__ import annotations import math # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ t...
1,368
58
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\newton_raphson.py
python
Python
""" 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. R...
3,866
115
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\numerical_integration.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,742
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\proper_fractions.py
python
Python
from math import gcd def proper_fractions(denominator: int) -> list[str]: """ this algorithm returns a list of proper fractions, in the range between 0 and 1, which can be formed with the given denominator https://en.wikipedia.org/wiki/Fraction#Proper_and_improper_fractions >>> proper_fractions(1...
1,189
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\runge_kutta.py
python
Python
import numpy as np def runge_kutta(f, y0, x0, h, x_end): """ Calculate the numeric solution at each step to the ODE f(x, y) using RK4 https://en.wikipedia.org/wiki/Runge-Kutta_methods Arguments: f -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value f...
1,065
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\runge_kutta_fehlberg_45.py
python
Python
""" Use the Runge-Kutta-Fehlberg method to solve Ordinary Differential Equations. """ 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: """ Solve an O...
3,326
115
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\runge_kutta_gills.py
python
Python
""" Use the Runge-Kutta-Gill's method of order 4 to solve Ordinary Differential Equations. https://www.geeksforgeeks.org/gills-4th-order-method-to-solve-differential-equations/ Author : Ravi Kumar """ from collections.abc import Callable from math import sqrt import numpy as np def runge_kutta_gills( func: Cal...
2,579
91
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\secant_method.py
python
Python
""" Implementing Secant method in Python Author: dimgrichr """ from math import exp def f(x: float) -> float: """ >>> f(5) 39.98652410600183 """ return 8 * x - 2 * exp(-x) def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float: """ >>> secant_method(1, 3, 2) ...
605
31
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\simpson_rule.py
python
Python
""" 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...
2,327
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\square_root.py
python
Python
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max...
1,315
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\numerical_analysis\weierstrass_method.py
python
Python
from collections.abc import Callable import numpy as np def weierstrass_method( polynomial: Callable[[np.ndarray], np.ndarray], degree: int, roots: np.ndarray | None = None, max_iter: int = 100, ) -> np.ndarray: """ Approximates all complex roots of a polynomial using the Weierstrass (Dur...
3,100
98
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\odd_sieve.py
python
Python
from itertools import compress, repeat from math import ceil, sqrt def odd_sieve(num: int) -> list[int]: """ Returns the prime numbers < `num`. The prime numbers are calculated using an odd sieve implementation of the Sieve of Eratosthenes algorithm (see for reference https://en.wikipedia.org/wiki/Sie...
1,076
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\perfect_cube.py
python
Python
def perfect_cube(n: int) -> bool: """ Check if a number is a perfect cube or not. >>> perfect_cube(27) True >>> perfect_cube(4) False """ val = n ** (1 / 3) return (val * val * val) == n def perfect_cube_binary_search(n: int) -> bool: """ Check if a number is a perfect cub...
1,410
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\perfect_number.py
python
Python
""" == Perfect Number == In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 ==> divisors[1, 2, 3, 6] Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: ...
2,520
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\perfect_square.py
python
Python
import math 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) T...
1,881
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\persistence.py
python
Python
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multi...
2,235
83
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\pi_generator.py
python
Python
def calculate_pi(limit: int) -> str: """ https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 Leibniz Formula for Pi The Leibniz formula is the special case arctan(1) = pi / 4. Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence (https://en.wikipedi...
2,491
88
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\pi_monte_carlo_estimation.py
python
Python
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: """ True, if the point lies in the unit circle False, otherwise """ return (self.x**2 + self.y**2) <= 1 @classmeth...
2,109
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\points_are_collinear_3d.py
python
Python
""" 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 t...
4,753
127
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\pollard_rho.py
python
Python
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, 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 factoriza...
5,734
149
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\polynomial_evaluation.py
python
Python
from collections.abc import Sequence def evaluate_poly(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial f(x) at specified point x and return the value. Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at whic...
1,727
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\polynomials\single_indeterminate_operations.py
python
Python
""" This module implements a single indeterminate polynomials class with some basic operations Reference: https://en.wikipedia.org/wiki/Polynomial """ from __future__ import annotations from collections.abc import MutableSequence class Polynomial: def __init__(self, degree: int, coefficients: MutableSequence...
6,021
189
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\power_using_recursion.py
python
Python
""" == Raise base to the power of exponent using recursion == Input --> Enter the base: 3 Enter the exponent: 4 Output --> 3 to the power of 4 is 81 Input --> Enter the base: 2 Enter the exponent: 0 Output --> 2 to the power of 0 is 1 """ def power(base...
1,754
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\prime_check.py
python
Python
"""Prime Check.""" import math import unittest import pytest def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True ...
2,351
91
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\prime_factors.py
python
Python
""" 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,191
94
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\prime_numbers.py
python
Python
import math from collections.abc import Generator 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, ...
3,133
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\prime_sieve_eratosthenes.py
python
Python
""" 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_eratos...
1,215
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\primelib.py
python
Python
""" Created on Thu Oct 5 16:44:23 2017 @author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: is_prime(number) sieve_er(N) get_prime_numbers(N) prime_factorization(number) greatest_prime_factor(number) smallest_prime_factor(number) get_p...
21,076
842
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\print_multiplication_table.py
python
Python
def multiplication_table(number: int, number_of_terms: int) -> str: """ Prints the multiplication table of a given number till the given number of terms >>> print(multiplication_table(3, 5)) 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 >>> print(multiplication_table(-4, 6)) ...
653
27
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\pythagoras.py
python
Python
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" 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: Poi...
741
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\qr_decomposition.py
python
Python
import numpy as np def qr_householder(a: np.ndarray): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the ma...
2,226
72
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\quadratic_equations_complex_numbers.py
python
Python
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -...
967
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\radians.py
python
Python
from math import pi def radians(degree: float) -> float: """ Converts the given angle from degrees to radians https://en.wikipedia.org/wiki/Radian >>> radians(180) 3.141592653589793 >>> radians(92) 1.6057029118347832 >>> radians(274) 4.782202150464463 >>> radians(109.82) 1...
621
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\radix2_fft.py
python
Python
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radi...
6,168
179
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\remove_digit.py
python
Python
def remove_digit(num: int) -> int: """ returns the biggest possible result that can be achieved by removing one digit from the given number >>> remove_digit(152) 52 >>> remove_digit(6385) 685 >>> remove_digit(-11) 1 >>> remove_digit(2222222) 222222 >>> remove_digit(...
1,069
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\segmented_sieve.py
python
Python
"""Segmented Sieve.""" import math def sieve(n: int) -> list[int]: """ Segmented Sieve. Examples: >>> sieve(8) [2, 3, 5, 7] >>> sieve(27) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> sieve(0) Traceback (most recent call last): ... ValueError: Number 0 must instead be a posi...
1,780
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\series\arithmetic.py
python
Python
""" 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 ar...
2,243
78
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\series\geometric.py
python
Python
""" Geometric Mean Reference : https://en.wikipedia.org/wiki/Geometric_mean Geometric series Reference: https://en.wikipedia.org/wiki/Geometric_series """ def is_geometric_series(series: list) -> bool: """ checking whether the input series is geometric series or not >>> is_geometric_series([2, 4, 8]) ...
2,398
84
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\series\geometric_series.py
python
Python
""" This is a pure Python implementation of the Geometric Series algorithm https://en.wikipedia.org/wiki/Geometric_series Run the doctests with the following command: python3 -m doctest -v geometric_series.py or python -m doctest -v geometric_series.py For manual testing run: python3 geometric_series.py """ from __fut...
2,415
75
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\series\harmonic.py
python
Python
""" 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/...
2,839
93
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\series\harmonic_series.py
python
Python
""" 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 har...
1,301
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\series\hexagonal_numbers.py
python
Python
""" 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 numb...
1,350
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\series\p_series.py
python
Python
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ from __future__ import annota...
1,452
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sieve_of_eratosthenes.py
python
Python
""" 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: Br...
1,717
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sigmoid.py
python
Python
""" 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.wikipedi...
987
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\signum.py
python
Python
""" 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 >>> si...
1,241
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\simultaneous_linear_equation_solver.py
python
Python
""" 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 ins...
5,281
143
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sin.py
python
Python
""" 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 d...
1,468
65
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sock_merchant.py
python
Python
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": i...
522
21
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\softmax.py
python
Python
""" 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...
1,514
57
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\solovay_strassen_primality_test.py
test
Python
""" This script implements the Solovay-Strassen Primality test. This probabilistic primality test is based on Euler's criterion. It is similar to the Fermat test but uses quadratic residues. It can quickly identify composite numbers but may occasionally classify composite numbers as prime. More details and concepts a...
2,908
107
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\spearman_rank_correlation_coefficient.py
python
Python
from collections.abc import Sequence 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] >>> ...
2,234
83
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\armstrong_numbers.py
python
Python
""" 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: ...
3,018
100
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\automorphic_number.py
python
Python
""" == 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/itsAksh...
1,635
60
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\bell_numbers.py
python
Python
""" 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 ...
2,275
82