repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/perfect_square.py
maths/perfect_square.py
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) 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: 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/floor.py
maths/floor.py
""" 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/pi_monte_carlo_estimation.py
maths/pi_monte_carlo_estimation.py
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 @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.") 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)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/gamma.py
maths/gamma.py
""" 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 from numpy import inf from scipy.integrate import quad 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") 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: """ 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: 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...")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/factors.py
maths/factors.py
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] = [] if num < 1: return facs facs.append(1) if num == 1: return facs facs.append(num) for i in range(2, int(sqrt(num)) + 1): if num % i == 0: # If i is a factor of num facs.append(i) d = num // i # num//i is the other factor of num if d != i: # If d and i are distinct facs.append(d) # we have found another factor facs.sort() return facs if __name__ == "__main__": testmod(name="factors_of_a_number", verbose=True)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/check_polygon.py
maths/check_polygon.py
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. Wiki: https://en.wikipedia.org/wiki/Triangle_inequality >>> check_polygon([6, 10, 5]) True >>> check_polygon([3, 7, 13, 2]) False >>> check_polygon([1, 4.3, 5.2, 12.2]) False >>> nums = [3, 7, 13, 2] >>> _ = check_polygon(nums) # Run function, do not show answer in output >>> nums # Check numbers are not reordered [3, 7, 13, 2] >>> check_polygon([]) Traceback (most recent call last): ... ValueError: Monogons and Digons are not polygons in the Euclidean space >>> check_polygon([-2, 5, 6]) Traceback (most recent call last): ... ValueError: All values must be greater than 0 """ if len(nums) < 2: raise ValueError("Monogons and Digons are not polygons in the Euclidean space") if any(i <= 0 for i in nums): raise ValueError("All values must be greater than 0") copy_nums = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1]) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/volume.py
maths/volume.py
""" Find the volume of various shapes. * https://en.wikipedia.org/wiki/Volume * https://en.wikipedia.org/wiki/Spherical_cap """ from __future__ import annotations from math import pi, pow # noqa: A004 def vol_cube(side_length: float) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1.0 >>> vol_cube(3) 27.0 >>> vol_cube(0) 0.0 >>> vol_cube(1.6) 4.096000000000001 >>> vol_cube(-1) Traceback (most recent call last): ... ValueError: vol_cube() only accepts non-negative values """ if side_length < 0: raise ValueError("vol_cube() only accepts non-negative values") return pow(side_length, 3) def vol_spherical_cap(height: float, radius: float) -> float: """ Calculate the volume of the spherical cap. >>> vol_spherical_cap(1, 2) 5.235987755982988 >>> vol_spherical_cap(1.6, 2.6) 16.621119532592402 >>> vol_spherical_cap(0, 0) 0.0 >>> vol_spherical_cap(-1, 2) Traceback (most recent call last): ... ValueError: vol_spherical_cap() only accepts non-negative values >>> vol_spherical_cap(1, -2) Traceback (most recent call last): ... ValueError: vol_spherical_cap() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_spherical_cap() only accepts non-negative values") # Volume is 1/3 pi * height squared * (3 * radius - height) return 1 / 3 * pi * pow(height, 2) * (3 * radius - height) def vol_spheres_intersect( radius_1: float, radius_2: float, centers_distance: float ) -> float: r""" Calculate the volume of the intersection of two spheres. The intersection is composed by two spherical caps and therefore its volume is the sum of the volumes of the spherical caps. First, it calculates the heights :math:`(h_1, h_2)` of the spherical caps, then the two volumes and it returns the sum. The height formulas are .. math:: h_1 = \frac{(radius_1 - radius_2 + centers\_distance) \cdot (radius_1 + radius_2 - centers\_distance)} {2 \cdot centers\_distance} h_2 = \frac{(radius_2 - radius_1 + centers\_distance) \cdot (radius_2 + radius_1 - centers\_distance)} {2 \cdot centers\_distance} if `centers_distance` is 0 then it returns the volume of the smallers sphere :return: ``vol_spherical_cap`` (:math:`h_1`, :math:`radius_2`) + ``vol_spherical_cap`` (:math:`h_2`, :math:`radius_1`) >>> vol_spheres_intersect(2, 2, 1) 21.205750411731103 >>> vol_spheres_intersect(2.6, 2.6, 1.6) 40.71504079052372 >>> vol_spheres_intersect(0, 0, 0) 0.0 >>> vol_spheres_intersect(-2, 2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values >>> vol_spheres_intersect(2, -2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values >>> vol_spheres_intersect(2, 2, -1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values """ if radius_1 < 0 or radius_2 < 0 or centers_distance < 0: raise ValueError("vol_spheres_intersect() only accepts non-negative values") if centers_distance == 0: return vol_sphere(min(radius_1, radius_2)) h1 = ( (radius_1 - radius_2 + centers_distance) * (radius_1 + radius_2 - centers_distance) / (2 * centers_distance) ) h2 = ( (radius_2 - radius_1 + centers_distance) * (radius_2 + radius_1 - centers_distance) / (2 * centers_distance) ) return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1) def vol_spheres_union( radius_1: float, radius_2: float, centers_distance: float ) -> float: r""" Calculate the volume of the union of two spheres that possibly intersect. It is the sum of sphere :math:`A` and sphere :math:`B` minus their intersection. First, it calculates the volumes :math:`(v_1, v_2)` of the spheres, then the volume of the intersection :math:`i` and it returns the sum :math:`v_1 + v_2 - i`. If `centers_distance` is 0 then it returns the volume of the larger sphere :return: ``vol_sphere`` (:math:`radius_1`) + ``vol_sphere`` (:math:`radius_2`) - ``vol_spheres_intersect`` (:math:`radius_1`, :math:`radius_2`, :math:`centers\_distance`) >>> vol_spheres_union(2, 2, 1) 45.814892864851146 >>> vol_spheres_union(1.56, 2.2, 1.4) 48.77802773671288 >>> vol_spheres_union(0, 2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_union() only accepts non-negative values, non-zero radius >>> vol_spheres_union('1.56', '2.2', '1.4') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'str' and 'int' >>> vol_spheres_union(1, None, 1) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'NoneType' and 'int' """ if radius_1 <= 0 or radius_2 <= 0 or centers_distance < 0: raise ValueError( "vol_spheres_union() only accepts non-negative values, non-zero radius" ) if centers_distance == 0: return vol_sphere(max(radius_1, radius_2)) return ( vol_sphere(radius_1) + vol_sphere(radius_2) - vol_spheres_intersect(radius_1, radius_2, centers_distance) ) def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return: multiple of `width`, `length` and `height` >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 >>> vol_cuboid(1.6, 2.6, 3.6) 14.976 >>> vol_cuboid(0, 0, 0) 0.0 >>> vol_cuboid(-1, 2, 3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values >>> vol_cuboid(1, -2, 3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values >>> vol_cuboid(1, 2, -3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values """ if width < 0 or height < 0 or length < 0: raise ValueError("vol_cuboid() only accepts non-negative values") return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: r""" | Calculate the Volume of a Cone. | Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return: :math:`\frac{1}{3} \cdot area\_of\_base \cdot height` >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 >>> vol_cone(1.6, 1.6) 0.8533333333333335 >>> vol_cone(0, 0) 0.0 >>> vol_cone(-1, 1) Traceback (most recent call last): ... ValueError: vol_cone() only accepts non-negative values >>> vol_cone(1, -1) Traceback (most recent call last): ... ValueError: vol_cone() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_cone() only accepts non-negative values") return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: r""" | Calculate the Volume of a Right Circular Cone. | Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return: :math:`\frac{1}{3} \cdot \pi \cdot radius^2 \cdot height` >>> vol_right_circ_cone(2, 3) 12.566370614359172 >>> vol_right_circ_cone(0, 0) 0.0 >>> vol_right_circ_cone(1.6, 1.6) 4.289321169701265 >>> vol_right_circ_cone(-1, 1) Traceback (most recent call last): ... ValueError: vol_right_circ_cone() only accepts non-negative values >>> vol_right_circ_cone(1, -1) Traceback (most recent call last): ... ValueError: vol_right_circ_cone() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_right_circ_cone() only accepts non-negative values") return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: r""" | Calculate the Volume of a Prism. | Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) :return: :math:`V = B \cdot h` >>> vol_prism(10, 2) 20.0 >>> vol_prism(11, 1) 11.0 >>> vol_prism(1.6, 1.6) 2.5600000000000005 >>> vol_prism(0, 0) 0.0 >>> vol_prism(-1, 1) Traceback (most recent call last): ... ValueError: vol_prism() only accepts non-negative values >>> vol_prism(1, -1) Traceback (most recent call last): ... ValueError: vol_prism() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_prism() only accepts non-negative values") return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: r""" | Calculate the Volume of a Pyramid. | Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return: :math:`\frac{1}{3} \cdot B \cdot h` >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 >>> vol_pyramid(1.6, 1.6) 0.8533333333333335 >>> vol_pyramid(0, 0) 0.0 >>> vol_pyramid(-1, 1) Traceback (most recent call last): ... ValueError: vol_pyramid() only accepts non-negative values >>> vol_pyramid(1, -1) Traceback (most recent call last): ... ValueError: vol_pyramid() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_pyramid() only accepts non-negative values") return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: r""" | Calculate the Volume of a Sphere. | Wikipedia reference: https://en.wikipedia.org/wiki/Sphere :return: :math:`\frac{4}{3} \cdot \pi \cdot r^3` >>> vol_sphere(5) 523.5987755982989 >>> vol_sphere(1) 4.1887902047863905 >>> vol_sphere(1.6) 17.15728467880506 >>> vol_sphere(0) 0.0 >>> vol_sphere(-1) Traceback (most recent call last): ... ValueError: vol_sphere() only accepts non-negative values """ if radius < 0: raise ValueError("vol_sphere() only accepts non-negative values") # Volume is 4/3 * pi * radius cubed return 4 / 3 * pi * pow(radius, 3) def vol_hemisphere(radius: float) -> float: r""" | Calculate the volume of a hemisphere | Wikipedia reference: https://en.wikipedia.org/wiki/Hemisphere | Other references: https://www.cuemath.com/geometry/hemisphere :return: :math:`\frac{2}{3} \cdot \pi \cdot radius^3` >>> vol_hemisphere(1) 2.0943951023931953 >>> vol_hemisphere(7) 718.377520120866 >>> vol_hemisphere(1.6) 8.57864233940253 >>> vol_hemisphere(0) 0.0 >>> vol_hemisphere(-1) Traceback (most recent call last): ... ValueError: vol_hemisphere() only accepts non-negative values """ if radius < 0: raise ValueError("vol_hemisphere() only accepts non-negative values") # Volume is radius cubed * pi * 2/3 return pow(radius, 3) * pi * 2 / 3 def vol_circular_cylinder(radius: float, height: float) -> float: r""" | Calculate the Volume of a Circular Cylinder. | Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder :return: :math:`\pi \cdot radius^2 \cdot height` >>> vol_circular_cylinder(1, 1) 3.141592653589793 >>> vol_circular_cylinder(4, 3) 150.79644737231007 >>> vol_circular_cylinder(1.6, 1.6) 12.867963509103795 >>> vol_circular_cylinder(0, 0) 0.0 >>> vol_circular_cylinder(-1, 1) Traceback (most recent call last): ... ValueError: vol_circular_cylinder() only accepts non-negative values >>> vol_circular_cylinder(1, -1) Traceback (most recent call last): ... ValueError: vol_circular_cylinder() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_circular_cylinder() only accepts non-negative values") # Volume is radius squared * height * pi return pow(radius, 2) * height * pi def vol_hollow_circular_cylinder( inner_radius: float, outer_radius: float, height: float ) -> float: """ Calculate the Volume of a Hollow Circular Cylinder. >>> vol_hollow_circular_cylinder(1, 2, 3) 28.274333882308138 >>> vol_hollow_circular_cylinder(1.6, 2.6, 3.6) 47.50088092227767 >>> vol_hollow_circular_cylinder(-1, 2, 3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(1, -2, 3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(1, 2, -3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(2, 1, 3) Traceback (most recent call last): ... ValueError: outer_radius must be greater than inner_radius >>> vol_hollow_circular_cylinder(0, 0, 0) Traceback (most recent call last): ... ValueError: outer_radius must be greater than inner_radius """ # Volume - (outer_radius squared - inner_radius squared) * pi * height if inner_radius < 0 or outer_radius < 0 or height < 0: raise ValueError( "vol_hollow_circular_cylinder() only accepts non-negative values" ) if outer_radius <= inner_radius: raise ValueError("outer_radius must be greater than inner_radius") return pi * (pow(outer_radius, 2) - pow(inner_radius, 2)) * height def vol_conical_frustum(height: float, radius_1: float, radius_2: float) -> float: """ | Calculate the Volume of a Conical Frustum. | Wikipedia reference: https://en.wikipedia.org/wiki/Frustum >>> vol_conical_frustum(45, 7, 28) 48490.482608158454 >>> vol_conical_frustum(1, 1, 2) 7.330382858376184 >>> vol_conical_frustum(1.6, 2.6, 3.6) 48.7240076620753 >>> vol_conical_frustum(0, 0, 0) 0.0 >>> vol_conical_frustum(-2, 2, 1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values >>> vol_conical_frustum(2, -2, 1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values >>> vol_conical_frustum(2, 2, -1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values """ # Volume is 1/3 * pi * height * # (radius_1 squared + radius_2 squared + radius_1 * radius_2) if radius_1 < 0 or radius_2 < 0 or height < 0: raise ValueError("vol_conical_frustum() only accepts non-negative values") return ( 1 / 3 * pi * height * (pow(radius_1, 2) + pow(radius_2, 2) + radius_1 * radius_2) ) def vol_torus(torus_radius: float, tube_radius: float) -> float: r""" | Calculate the Volume of a Torus. | Wikipedia reference: https://en.wikipedia.org/wiki/Torus :return: :math:`2 \pi^2 \cdot torus\_radius \cdot tube\_radius^2` >>> vol_torus(1, 1) 19.739208802178716 >>> vol_torus(4, 3) 710.6115168784338 >>> vol_torus(3, 4) 947.4820225045784 >>> vol_torus(1.6, 1.6) 80.85179925372404 >>> vol_torus(0, 0) 0.0 >>> vol_torus(-1, 1) Traceback (most recent call last): ... ValueError: vol_torus() only accepts non-negative values >>> vol_torus(1, -1) Traceback (most recent call last): ... ValueError: vol_torus() only accepts non-negative values """ if torus_radius < 0 or tube_radius < 0: raise ValueError("vol_torus() only accepts non-negative values") return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2) def vol_icosahedron(tri_side: float) -> float: """ | Calculate the Volume of an Icosahedron. | Wikipedia reference: https://en.wikipedia.org/wiki/Regular_icosahedron >>> from math import isclose >>> isclose(vol_icosahedron(2.5), 34.088984228514256) True >>> isclose(vol_icosahedron(10), 2181.694990624912374) True >>> isclose(vol_icosahedron(5), 272.711873828114047) True >>> isclose(vol_icosahedron(3.49), 92.740688412033628) True >>> vol_icosahedron(0) 0.0 >>> vol_icosahedron(-1) Traceback (most recent call last): ... ValueError: vol_icosahedron() only accepts non-negative values >>> vol_icosahedron(-0.2) Traceback (most recent call last): ... ValueError: vol_icosahedron() only accepts non-negative values """ if tri_side < 0: raise ValueError("vol_icosahedron() only accepts non-negative values") return tri_side**3 * (3 + 5**0.5) * 5 / 12 def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print(f"Cube: {vol_cube(2) = }") # = 8 print(f"Cuboid: {vol_cuboid(2, 2, 2) = }") # = 8 print(f"Cone: {vol_cone(2, 2) = }") # ~= 1.33 print(f"Right Circular Cone: {vol_right_circ_cone(2, 2) = }") # ~= 8.38 print(f"Prism: {vol_prism(2, 2) = }") # = 4 print(f"Pyramid: {vol_pyramid(2, 2) = }") # ~= 1.33 print(f"Sphere: {vol_sphere(2) = }") # ~= 33.5 print(f"Hemisphere: {vol_hemisphere(2) = }") # ~= 16.75 print(f"Circular Cylinder: {vol_circular_cylinder(2, 2) = }") # ~= 25.1 print(f"Torus: {vol_torus(2, 2) = }") # ~= 157.9 print(f"Conical Frustum: {vol_conical_frustum(2, 2, 4) = }") # ~= 58.6 print(f"Spherical cap: {vol_spherical_cap(1, 2) = }") # ~= 5.24 print(f"Spheres intersection: {vol_spheres_intersect(2, 2, 1) = }") # ~= 21.21 print(f"Spheres union: {vol_spheres_union(2, 2, 1) = }") # ~= 45.81 print( f"Hollow Circular Cylinder: {vol_hollow_circular_cylinder(1, 2, 3) = }" ) # ~= 28.3 print(f"Icosahedron: {vol_icosahedron(2.5) = }") # ~=34.09 if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/triplet_sum.py
maths/triplet_sum.py
""" Given an array of integers and another integer target, we are required to find a triplet from the array such that it's sum is equal to the target. """ from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def make_dataset() -> tuple[list[int], int]: arr = [randint(-1000, 1000) for i in range(10)] r = randint(-5000, 5000) return (arr, r) dataset = make_dataset() def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]: """ Returns a triplet in the array with sum equal to target, else (0, 0, 0). >>> triplet_sum1([13, 29, 7, 23, 5], 35) (5, 7, 23) >>> triplet_sum1([37, 9, 19, 50, 44], 65) (9, 19, 37) >>> arr = [6, 47, 27, 1, 15] >>> target = 11 >>> triplet_sum1(arr, target) (0, 0, 0) """ for triplet in permutations(arr, 3): if sum(triplet) == target: return tuple(sorted(triplet)) return (0, 0, 0) def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]: """ Returns a triplet in the array with sum equal to target, else (0, 0, 0). >>> triplet_sum2([13, 29, 7, 23, 5], 35) (5, 7, 23) >>> triplet_sum2([37, 9, 19, 50, 44], 65) (9, 19, 37) >>> arr = [6, 47, 27, 1, 15] >>> target = 11 >>> triplet_sum2(arr, target) (0, 0, 0) """ arr.sort() n = len(arr) for i in range(n - 1): left, right = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def solution_times() -> tuple[float, float]: setup_code = """ from __main__ import dataset, triplet_sum1, triplet_sum2 """ test_code1 = """ triplet_sum1(*dataset) """ test_code2 = """ triplet_sum2(*dataset) """ times1 = repeat(setup=setup_code, stmt=test_code1, repeat=5, number=10000) times2 = repeat(setup=setup_code, stmt=test_code2, repeat=5, number=10000) return (min(times1), min(times2)) if __name__ == "__main__": from doctest import testmod testmod() times = solution_times() print(f"The time for naive implementation is {times[0]}.") print(f"The time for optimized implementation is {times[1]}.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/euler_modified.py
maths/euler_modified.py
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 give accurate solutions. So, some changes were proposed to improve accuracy. https://en.wikipedia.org/wiki/Euler_method Arguments: ode_func -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x stepsize -- the increment value for x x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f1(x, y): ... return -2*x*(y**2) >>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0) >>> float(y[-1]) 0.503338255442106 >>> import math >>> def f2(x, y): ... return -2*y + (x**3)*math.exp(-2*x) >>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3) >>> float(y[-1]) 0.5525976431951775 """ n = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): y_get = y[k] + step_size * ode_func(x, y[k]) y[k + 1] = y[k] + ( (step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get)) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/perfect_cube.py
maths/perfect_cube.py
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 cube or not using binary search. Time complexity : O(Log(n)) Space complexity: O(1) >>> perfect_cube_binary_search(27) True >>> perfect_cube_binary_search(64) True >>> perfect_cube_binary_search(4) False >>> perfect_cube_binary_search("a") Traceback (most recent call last): ... TypeError: perfect_cube_binary_search() only accepts integers >>> perfect_cube_binary_search(0.1) Traceback (most recent call last): ... TypeError: perfect_cube_binary_search() only accepts integers """ if not isinstance(n, int): raise TypeError("perfect_cube_binary_search() only accepts integers") if n < 0: n = -n left = 0 right = n while left <= right: mid = left + (right - left) // 2 if mid * mid * mid == n: return True elif mid * mid * mid < n: left = mid + 1 else: right = mid - 1 return False if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/trapezoidal_rule.py
maths/trapezoidal_rule.py
""" Numerical integration or quadrature for a smooth function f with known values at x_i """ def trapezoidal_rule(boundary, steps): """ Implements the extended trapezoidal rule for numerical integration. The function f(x) is provided below. :param boundary: List containing the lower and upper bounds of integration [a, b] :param steps: The number of steps (intervals) used in the approximation :return: The numerical approximation of the integral >>> abs(trapezoidal_rule([0, 1], 10) - 0.33333) < 0.01 True >>> abs(trapezoidal_rule([0, 1], 100) - 0.33333) < 0.01 True >>> abs(trapezoidal_rule([0, 2], 1000) - 2.66667) < 0.01 True >>> abs(trapezoidal_rule([1, 2], 1000) - 2.33333) < 0.01 True """ h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 2.0) * f(a) for i in x_i: y += h * f(i) y += (h / 2.0) * f(b) return y def make_points(a, b, h): """ Generates points between a and b with step size h for trapezoidal integration. :param a: The lower bound of integration :param b: The upper bound of integration :param h: The step size :yield: The next x-value in the range (a, b) >>> list(make_points(0, 1, 0.1)) # doctest: +NORMALIZE_WHITESPACE [0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, \ 0.8999999999999999] >>> list(make_points(0, 10, 2.5)) [2.5, 5.0, 7.5] >>> list(make_points(0, 10, 2)) [2, 4, 6, 8] >>> list(make_points(1, 21, 5)) [6, 11, 16] >>> list(make_points(1, 5, 2)) [3] >>> list(make_points(1, 4, 3)) [] """ x = a + h while x <= (b - h): yield x x += h def f(x): """ This is the function to integrate, f(x) = (x - 0)^2 = x^2. :param x: The input value :return: The value of f(x) >>> f(0) 0 >>> f(1) 1 >>> f(0.5) 0.25 """ return x**2 def main(): """ Main function to test the trapezoidal rule. :a: Lower bound of integration :b: Upper bound of integration :steps: define number of steps or resolution :boundary: define boundary of integration >>> main() y = 0.3349999999999999 """ a = 0.0 b = 1.0 steps = 10.0 boundary = [a, b] y = trapezoidal_rule(boundary, steps) print(f"y = {y}") if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/geometric_mean.py
maths/geometric_mean.py
""" 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): 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))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/prime_check.py
maths/prime_check.py
"""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 >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False >>> is_prime(16.1) Traceback (most recent call last): ... ValueError: is_prime() only accepts positive integers >>> is_prime(-4) Traceback (most recent call last): ... ValueError: is_prime() only accepts positive integers """ # precondition if not isinstance(number, int) or not number >= 0: raise ValueError("is_prime() only accepts positive integers") if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True class Test(unittest.TestCase): def test_primes(self): assert is_prime(2) assert is_prime(3) assert is_prime(5) assert is_prime(7) assert is_prime(11) assert is_prime(13) assert is_prime(17) assert is_prime(19) assert is_prime(23) assert is_prime(29) def test_not_primes(self): with pytest.raises(ValueError): is_prime(-19) assert not is_prime(0), ( "Zero doesn't have any positive factors, primes must have exactly two." ) assert not is_prime(1), ( "One only has 1 positive factor, primes must have exactly two." ) assert not is_prime(2 * 2) assert not is_prime(2 * 3) assert not is_prime(3 * 3) assert not is_prime(3 * 5) assert not is_prime(3 * 5 * 7) if __name__ == "__main__": unittest.main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/matrix_exponentiation.py
maths/matrix_exponentiation.py
"""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: def __init__(self, arg): 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(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, b): 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, f1, f2): """ 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 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, f1, f2): """ 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 elif n == 2: return f2 n -= 2 while n > 0: f2, f1 = f1 + f2, f2 n -= 1 return f2 def matrix_exponentiation_time(): 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(): 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(): matrix_exponentiation_time() simple_fibonacci_time() if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/entropy.py
maths/entropy.py
#!/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 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. 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]: """ 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 # 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/hardy_ramanujanalgo.py
maths/hardy_ramanujanalgo.py
# 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 == 0: n = int(n / 2) # the n input value must be odd so that # we can skip one element (ie i += 2) i = 3 while i <= int(math.sqrt(n)): if n % i == 0: count += 1 while n % i == 0: n = int(n / i) i = i + 2 # this condition checks the prime # number n is greater than 2 if n > 2: count += 1 return count if __name__ == "__main__": n = 51242183 print(f"The number of distinct prime factors is/are {exact_prime_factor_count(n)}") print(f"The value of log(log(n)) is {math.log(math.log(n)):.4f}") """ The number of distinct prime factors is/are 3 The value of log(log(n)) is 2.8765 """
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/euler_method.py
maths/euler_method.py
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.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The initial value for y. x0 (float): The initial value for x. step_size (float): The increment value for x. x_end (float): The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> float(y[-1]) 144.77277243257308 """ n = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/prime_sieve_eratosthenes.py
maths/prime_sieve_eratosthenes.py
""" 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") 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))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/solovay_strassen_primality_test.py
maths/solovay_strassen_primality_test.py
""" 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 about this can be found on: https://en.wikipedia.org/wiki/Solovay%E2%80%93Strassen_primality_test """ import random def jacobi_symbol(random_a: int, number: int) -> int: """ Calculate the Jacobi symbol. The Jacobi symbol is a generalization of the Legendre symbol, which can be used to simplify computations involving quadratic residues. The Jacobi symbol is used in primality tests, like the Solovay-Strassen test, because it helps determine if an integer is a quadratic residue modulo a given modulus, providing valuable information about the number's potential primality or compositeness. Parameters: random_a: A randomly chosen integer from 2 to n-2 (inclusive) number: The number that is tested for primality Returns: jacobi_symbol: The Jacobi symbol is a mathematical function used to determine whether an integer is a quadratic residue modulo another integer (usually prime) or not. >>> jacobi_symbol(2, 13) -1 >>> jacobi_symbol(5, 19) 1 >>> jacobi_symbol(7, 14) 0 """ if random_a in (0, 1): return random_a random_a %= number t = 1 while random_a != 0: while random_a % 2 == 0: random_a //= 2 r = number % 8 if r in (3, 5): t = -t random_a, number = number, random_a if random_a % 4 == number % 4 == 3: t = -t random_a %= number return t if number == 1 else 0 def solovay_strassen(number: int, iterations: int) -> bool: """ Check whether the input number is prime or not using the Solovay-Strassen Primality test Parameters: number: The number that is tested for primality iterations: The number of times that the test is run which effects the accuracy Returns: result: True if number is probably prime and false if not >>> random.seed(10) >>> solovay_strassen(13, 5) True >>> solovay_strassen(9, 10) False >>> solovay_strassen(17, 15) True """ if number <= 1: return False if number <= 3: return True for _ in range(iterations): a = random.randint(2, number - 2) x = jacobi_symbol(a, number) y = pow(a, (number - 1) // 2, number) if x == 0 or y != x % number: return False return True if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/perfect_number.py
maths/perfect_number.py
""" == 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: 28, 486, ... https://en.wikipedia.org/wiki/Perfect_number """ def perfect(number: int) -> bool: """ Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Args: number: The number to be checked. Returns: True if the number is a perfect number otherwise, False. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False >>> perfect(6) True >>> perfect(12) False >>> perfect(496) True >>> perfect(8128) True >>> perfect(0) False >>> perfect(-1) False >>> perfect(33550336) # Large perfect number True >>> perfect(33550337) # Just above a large perfect number False >>> perfect(1) # Edge case: 1 is not a perfect number False >>> perfect("123") # String representation of a number Traceback (most recent call last): ... ValueError: number must be an integer >>> perfect(12.34) Traceback (most recent call last): ... ValueError: number must be an integer >>> perfect("Hello") Traceback (most recent call last): ... ValueError: number must be an integer """ if not isinstance(number, int): raise ValueError("number must be an integer") if number <= 0: return False return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": from doctest import testmod testmod() print("Program to check whether a number is a Perfect number or not...") try: number = int(input("Enter a positive integer: ").strip()) except ValueError: msg = "number must be an integer" raise ValueError(msg) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/binary_multiplication.py
maths/binary_multiplication.py
""" 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: res += a a += a b >>= 1 return res 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: res = ((res % modulus) + (a % modulus)) % modulus a += a b >>= 1 return res if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sum_of_harmonic_series.py
maths/sum_of_harmonic_series.py
def sum_of_harmonic_progression( first_term: float, common_difference: float, number_of_terms: int ) -> float: """ https://en.wikipedia.org/wiki/Harmonic_progression_(mathematics) Find the sum of n terms in an harmonic progression. The calculation starts with the first_term and loops adding the common difference of Arithmetic Progression by which the given Harmonic Progression is linked. >>> sum_of_harmonic_progression(1 / 2, 2, 2) 0.75 >>> sum_of_harmonic_progression(1 / 5, 5, 5) 0.45666666666666667 """ arithmetic_progression = [1 / first_term] first_term = 1 / first_term for _ in range(number_of_terms - 1): first_term += common_difference arithmetic_progression.append(first_term) harmonic_series = [1 / step for step in arithmetic_progression] return sum(harmonic_series) if __name__ == "__main__": import doctest doctest.testmod() print(sum_of_harmonic_progression(1 / 2, 2, 2))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/jaccard_similarity.py
maths/jaccard_similarity.py
""" 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( set_a: set[str] | list[str] | tuple[str], 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)) 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))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/dual_number_automatic_differentiation.py
maths/dual_number_automatic_differentiation.py
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__(self, real, rank): self.real = real if isinstance(rank, int): self.duals = [1] * rank else: self.duals = rank def __repr__(self): s = "+".join(f"{dual}E{n}" for n, dual in enumerate(self.duals, 1)) return f"{self.real}+{s}" def reduce(self): cur = self.duals.copy() while cur[-1] == 0: cur.pop(-1) return Dual(self.real, cur) def __add__(self, other): if not isinstance(other, Dual): return Dual(self.real + other, self.duals) s_dual = self.duals.copy() o_dual = other.duals.copy() if len(s_dual) > len(o_dual): o_dual.extend([1] * (len(s_dual) - len(o_dual))) elif len(s_dual) < len(o_dual): s_dual.extend([1] * (len(o_dual) - len(s_dual))) new_duals = [] for i in range(len(s_dual)): new_duals.append(s_dual[i] + o_dual[i]) return Dual(self.real + other.real, new_duals) __radd__ = __add__ def __sub__(self, other): return self + other * -1 def __mul__(self, other): if not isinstance(other, Dual): new_duals = [] for i in self.duals: new_duals.append(i * other) return Dual(self.real * other, new_duals) new_duals = [0] * (len(self.duals) + len(other.duals) + 1) for i, item in enumerate(self.duals): for j, jtem in enumerate(other.duals): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals)): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals)): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real, new_duals) __rmul__ = __mul__ def __truediv__(self, other): if not isinstance(other, Dual): new_duals = [] for i in self.duals: new_duals.append(i / other) return Dual(self.real / other, new_duals) raise ValueError def __floordiv__(self, other): if not isinstance(other, Dual): new_duals = [] for i in self.duals: new_duals.append(i // other) return Dual(self.real // other, new_duals) raise ValueError def __pow__(self, n): if n < 0 or isinstance(n, float): raise ValueError("power must be a positive integer") if n == 0: return 1 if n == 1: return self x = self for _ in range(n - 1): x *= self return x def differentiate(func, position, order): """ >>> differentiate(lambda x: x**2, 2, 2) 2 >>> differentiate(lambda x: x**2 * x**4, 9, 2) 196830 >>> differentiate(lambda y: 0.5 * (y + 3) ** 6, 3.5, 4) 7605.0 >>> differentiate(lambda y: y ** 2, 4, 3) 0 >>> differentiate(8, 8, 8) Traceback (most recent call last): ... ValueError: differentiate() requires a function as input for func >>> differentiate(lambda x: x **2, "", 1) Traceback (most recent call last): ... ValueError: differentiate() requires a float as input for position >>> differentiate(lambda x: x**2, 3, "") Traceback (most recent call last): ... ValueError: differentiate() requires an int as input for order """ if not callable(func): raise ValueError("differentiate() requires a function as input for func") if not isinstance(position, (float, int)): raise ValueError("differentiate() requires a float as input for position") if not isinstance(order, int): raise ValueError("differentiate() requires an int as input for order") d = Dual(position, 1) result = func(d) if order == 0: return result.real return result.duals[order - 1] * factorial(order) if __name__ == "__main__": import doctest doctest.testmod() def f(y): return y**2 * y**4 print(differentiate(f, 9, 2))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/power_using_recursion.py
maths/power_using_recursion.py
""" == 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: int, exponent: int) -> float: """ Calculate the power of a base raised to an exponent. >>> power(3, 4) 81 >>> power(2, 0) 1 >>> all(power(base, exponent) == pow(base, exponent) ... for base in range(-10, 10) for exponent in range(10)) True >>> power('a', 1) 'a' >>> power('a', 2) Traceback (most recent call last): ... TypeError: can't multiply sequence by non-int of type 'str' >>> power('a', 'b') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'int' >>> power(2, -1) Traceback (most recent call last): ... RecursionError: maximum recursion depth exceeded >>> power(0, 0) 1 >>> power(0, 1) 0 >>> power(5,6) 15625 >>> power(23, 12) 21914624432020321 """ return base * power(base, (exponent - 1)) if exponent else 1 if __name__ == "__main__": from doctest import testmod testmod() print("Raise base to the power of exponent using recursion...") base = int(input("Enter the base: ").strip()) exponent = int(input("Enter the exponent: ").strip()) result = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents result = 1 / result print(f"{base} to the power of {exponent} is {result}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/interquartile_range.py
maths/interquartile_range.py
""" 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] return (nums[div] + nums[(div) - 1]) / 2 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() 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/number_of_digits.py
maths/number_of_digits.py
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 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") 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: """ 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") return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) 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") return len(str(abs(n))) 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: 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/test_factorial.py
maths/test_factorial.py
# /// script # requires-python = ">=3.13" # dependencies = [ # "pytest", # ] # /// import pytest from maths.factorial import factorial, factorial_recursive @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_zero(function): assert function(0) == 1 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_positive_integers(function): assert function(1) == 1 assert function(5) == 120 assert function(7) == 5040 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_large_number(function): assert function(10) == 3628800 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_negative_number(function): with pytest.raises(ValueError): function(-3) @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_float_number(function): with pytest.raises(ValueError): function(1.5) if __name__ == "__main__": pytest.main(["-v", __file__])
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sigmoid.py
maths/sigmoid.py
""" 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/binary_exponentiation.py
maths/binary_exponentiation.py
""" 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") 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: """ 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") 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: """ 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: 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: """ 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: 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, ) )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/polynomial_evaluation.py
maths/polynomial_evaluation.py
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 which to evaluate the polynomial >>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ return sum(c * (x**i) for i, c in enumerate(poly)) def horner(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial at specified point using Horner's method. In terms of computational complexity, Horner's method is an efficient method of evaluating a polynomial. It avoids the use of expensive exponentiation, and instead uses only multiplication and addition to evaluate the polynomial in O(n), where n is the degree of the polynomial. https://en.wikipedia.org/wiki/Horner's_method Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at which to evaluate the polynomial >>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ result = 0.0 for coeff in reversed(poly): result = result * x + coeff return result if __name__ == "__main__": """ Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2 >>> x = -13.0 >>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9 >>> evaluate_poly(poly, x) 180339.9 """ poly = (0.0, 0.0, 5.0, 9.3, 7.0) x = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/pythagoras.py
maths/pythagoras.py
"""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: 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/fibonacci.py
maths/fibonacci.py
""" 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 from math import sqrt from time import time import numpy as np from numpy import ndarray def time_func(func, *args, **kwargs): """ Times the execution of a function with parameters """ 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]: """ 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 yield a for _ in range(n): yield b a, b = b, a + b 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: 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]: """ Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> 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 """ 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): ... Exception: n is negative """ 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]: """ Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> 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 """ @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: 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]: """ 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_iterative(-1) Traceback (most recent call last): ... ValueError: n is negative """ 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]: """ 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: 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: """ 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 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: """ 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: 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
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/euclidean_distance.py
maths/euclidean_distance.py
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: """ 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") 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/points_are_collinear_3d.py
maths/points_are_collinear_3d.py
""" 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] return (x, y, z) 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 return (x, y, z) 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)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/continued_fraction.py
maths/continued_fraction.py
""" 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: 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")))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/line_length.py
maths/line_length.py
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 lines and summing their lengths :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 accuracy :return: a float representing the length of the curve >>> def f(x): ... return x >>> f"{line_length(f, 0, 1, 10):.6f}" '1.414214' >>> def f(x): ... return 1 >>> f"{line_length(f, -5.5, 4.5):.6f}" '10.000000' >>> def f(x): ... return math.sin(5 * x) + math.cos(10 * x) + x * x/10 >>> f"{line_length(f, 0.0, 10.0, 10000):.6f}" '69.534930' """ x1 = x_start fx1 = fnc(x_start) length = 0.0 for _ in range(steps): # Approximates curve as a sequence of linear lines and sums their length x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) length += math.hypot(x2 - x1, fx2 - fx1) # Increment step x1 = x2 fx1 = fx2 return length if __name__ == "__main__": def f(x): return math.sin(10 * x) print("f(x) = sin(10 * x)") print("The length of the curve from x = -10 to x = 10 is:") i = 10 while i <= 100000: print(f"With {i} steps: {line_length(f, -10, 10, i)}") i *= 10
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/softmax.py
maths/softmax.py
""" 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) 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,)))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/germain_primes.py
maths/germain_primes.py
""" 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) return is_prime(number) and is_prime(2 * number + 1) 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) return (number - 1) % 2 == 0 and is_prime(number) and is_prime((number - 1) // 2) if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/minkowski_distance.py
maths/minkowski_distance.py
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 Manhattan distance. For order = 2, the usual Euclidean distance is obtained. https://en.wikipedia.org/wiki/Minkowski_distance Note: due to floating point calculation errors the output of this function may be inaccurate. >>> minkowski_distance([1.0, 1.0], [2.0, 2.0], 1) 2.0 >>> minkowski_distance([1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], 2) 8.0 >>> import numpy as np >>> bool(np.isclose(5.0, minkowski_distance([5.0], [0.0], 3))) True >>> minkowski_distance([1.0], [2.0], -1) Traceback (most recent call last): ... ValueError: The order must be greater than or equal to 1. >>> minkowski_distance([1.0], [1.0, 2.0], 1) Traceback (most recent call last): ... ValueError: Both points must have the same dimension. """ if order < 1: raise ValueError("The order must be greater than or equal to 1.") if len(point_a) != len(point_b): raise ValueError("Both points must have the same dimension.") return sum(abs(a - b) ** order for a, b in zip(point_a, point_b)) ** (1 / order) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/basic_maths.py
maths/basic_maths.py
"""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_factors(-10) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors """ if n <= 0: raise ValueError("Only positive integers have prime factors") pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) n = int(n / i) if n > 2: pf.append(n) return pf def number_of_divisors(n: int) -> int: """Calculate Number of Divisors of an Integer. >>> number_of_divisors(100) 9 >>> number_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> number_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") div = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) div *= temp for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) div *= temp if n > 1: div *= 2 return div def sum_of_divisors(n: int) -> int: """Calculate Sum of Divisors. >>> sum_of_divisors(100) 217 >>> sum_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> sum_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") s = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) if temp > 1: s *= (2**temp - 1) / (2 - 1) for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) if temp > 1: s *= (i**temp - 1) / (i - 1) return int(s) def euler_phi(n: int) -> int: """Calculate Euler's Phi Function. >>> euler_phi(100) 40 >>> euler_phi(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> euler_phi(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") s = n for x in set(prime_factors(n)): s *= (x - 1) / x return int(s) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sum_of_geometric_progression.py
maths/sum_of_geometric_progression.py
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0 >>> sum_of_geometric_progression(1, 2, 0) -0.0 >>> sum_of_geometric_progression(-1, 2, 10) -1023.0 >>> sum_of_geometric_progression(1, -2, 10) -341.0 >>> sum_of_geometric_progression(1, 2, -10) -0.9990234375 """ if common_ratio == 1: # Formula for sum if common ratio is 1 return num_of_terms * first_term # Formula for finding sum of n terms of a GeometricProgression return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/prime_numbers.py
maths/prime_numbers.py
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, 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): if (i % j) == 0: break else: yield i 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) 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]: """ 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: 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(): """ Let's benchmark our functions side-by-side... """ 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/segmented_sieve.py
maths/segmented_sieve.py
"""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 positive integer >>> sieve(-1) Traceback (most recent call last): ... ValueError: Number -1 must instead be a positive integer >>> sieve(22.2) Traceback (most recent call last): ... ValueError: Number 22.2 must instead be a positive integer """ if n <= 0 or isinstance(n, float): msg = f"Number {n} must instead be a positive integer" raise ValueError(msg) in_prime = [] start = 2 end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] while start <= end: if temp[start] is True: in_prime.append(start) for i in range(start * start, end + 1, start): temp[i] = False start += 1 prime += in_prime low = end + 1 high = min(2 * end, n) while low <= n: temp = [True] * (high - low + 1) for each in in_prime: t = math.floor(low / each) * each if t < low: t += each for j in range(t, high + 1, each): temp[j - low] = False for j in range(len(temp)): if temp[j] is True: prime.append(j + low) low = high + 1 high = min(high + end, n) return prime if __name__ == "__main__": import doctest doctest.testmod() print(f"{sieve(10**6) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/print_multiplication_table.py
maths/print_multiplication_table.py
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)) -4 * 1 = -4 -4 * 2 = -8 -4 * 3 = -12 -4 * 4 = -16 -4 * 5 = -20 -4 * 6 = -24 """ return "\n".join( f"{number} * {i} = {number * i}" for i in range(1, number_of_terms + 1) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/fermat_little_theorem.py
maths/fermat_little_theorem.py
# 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_theorem def binary_exponentiation(a: int, n: float, mod: int) -> int: if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/area.py
maths/area.py
""" 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)) 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) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/extended_euclidean_algorithm.py
maths/extended_euclidean_algorithm.py
""" 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 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]: """ 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 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(): """Call Extended Euclidean Algorithm.""" 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/dodecahedron.py
maths/dodecahedron.py
# 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.") return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) 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.") return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/tanh.py
maths/tanh.py
""" This script demonstrates the implementation of the tangent hyperbolic or tanh function. The function takes a vector of K real numbers as input and then (e^x - e^(-x))/(e^x + e^(-x)). After through tanh, the element of the vector mostly -1 between 1. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Activation_function """ import numpy as np def tangent_hyperbolic(vector: np.ndarray) -> np.ndarray: """ Implements the tanh function Parameters: vector: np.ndarray Returns: tanh (np.array): The input numpy array after applying tanh. mathematically (e^x - e^(-x))/(e^x + e^(-x)) can be written as (2/(1+e^(-2x))-1 Examples: >>> tangent_hyperbolic(np.array([1,5,6,-0.67])) array([ 0.76159416, 0.9999092 , 0.99998771, -0.58497988]) >>> tangent_hyperbolic(np.array([8,10,2,-0.98,13])) array([ 0.99999977, 1. , 0.96402758, -0.7530659 , 1. ]) """ return (2 / (1 + np.exp(-2 * vector))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/three_sum.py
maths/three_sum.py
""" https://en.wikipedia.org/wiki/3SUM """ def three_sum(nums: list[int]) -> list[list[int]]: """ Find all unique triplets in a sorted array of integers that sum up to zero. Args: nums: A sorted list of integers. Returns: A list of lists containing unique triplets that sum up to zero. >>> three_sum([-1, 0, 1, 2, -1, -4]) [[-1, -1, 2], [-1, 0, 1]] >>> three_sum([1, 2, 3, 4]) [] """ nums.sort() ans = [] for i in range(len(nums) - 2): if i == 0 or (nums[i] != nums[i - 1]): low, high, c = i + 1, len(nums) - 1, 0 - nums[i] while low < high: if nums[low] + nums[high] == c: ans.append([nums[i], nums[low], nums[high]]) while low < high and nums[low] == nums[low + 1]: low += 1 while low < high and nums[high] == nums[high - 1]: high -= 1 low += 1 high -= 1 elif nums[low] + nums[high] < c: low += 1 else: high -= 1 return ans if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/simultaneous_linear_equation_solver.py
maths/simultaneous_linear_equation_solver.py
""" 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]]))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/monte_carlo.py
maths/monte_carlo.py
""" @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. 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: 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: """ 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) ) * (max_value - min_value) 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( 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: """ 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( 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/qr_decomposition.py
maths/qr_decomposition.py
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 matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity O(n^3). https://en.wikipedia.org/wiki/QR_decomposition#Using_Householder_reflections Arguments: A -- a numpy.ndarray of shape (m, n) Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. >>> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=float) >>> Q, R = qr_householder(A) >>> # check that the decomposition is correct >>> np.allclose(Q@R, A) True >>> # check that Q is orthogonal >>> np.allclose(Q@Q.T, np.eye(A.shape[0])) True >>> np.allclose(Q.T@Q, np.eye(A.shape[0])) True >>> # check that R is upper triangular >>> np.allclose(np.triu(R), R) True """ m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): # select a column of modified matrix A': x = r[k:, [k]] # construct first basis vector e1 = np.zeros_like(x) e1[0] = 1.0 # determine scaling factor alpha = np.linalg.norm(x) # construct vector v for Householder reflection v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) # construct the Householder matrix q_k = np.eye(m - k) - 2.0 * v @ v.T # pad with ones and zeros as necessary q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]]) q = q @ q_k.T r = q_k @ r return q, r if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/joint_probability_distribution.py
maths/joint_probability_distribution.py
""" 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_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) for y, y_prob in zip(y_values, y_probabilities) } # 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)) # Function to calculate the covariance def covariance( x_values: list[int], y_values: list[int], 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( (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: """ >>> standard_deviation(0.21) 0.458257569495584 """ 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)) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/is_square_free.py
maths/is_square_free.py
""" 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/monte_carlo_dice.py
maths/monte_carlo_dice.py
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) -> list[float]: """ Return probability list of all possible sums when throwing dice. >>> random.seed(0) >>> throw_dice(10, 1) [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] >>> throw_dice(100, 1) [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] >>> throw_dice(1000, 1) [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] >>> throw_dice(10000, 1) [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] >>> throw_dice(10000, 2) [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) for _ in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sum_of_digits.py
maths/sum_of_digits.py
def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = abs(n) res = 0 while n > 0: res += n % 10 n //= 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = abs(n) return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark multiple functions, with three different length int values. """ from collections.abc import Callable from timeit import timeit 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:56} = {func(value)} -- {timing:.4f} seconds") for value in (262144, 1125899906842624, 1267650600228229401496703205376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/twin_prime.py
maths/twin_prime.py
""" == Twin Prime == A number n+2 is said to be a Twin prime of number n if both n and n+2 are prime. Examples of Twin pairs: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), ... https://en.wikipedia.org/wiki/Twin_prime """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_check import is_prime def twin_prime(number: int) -> int: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns n+2 if n and n+2 are prime numbers and -1 otherwise. >>> twin_prime(3) 5 >>> twin_prime(4) -1 >>> twin_prime(5) 7 >>> twin_prime(17) 19 >>> twin_prime(0) -1 >>> twin_prime(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) if is_prime(number) and is_prime(number + 2): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/integer_square_root.py
maths/integer_square_root.py
""" 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") 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/liouville_lambda.py
maths/liouville_lambda.py
""" == 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) 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/josephus_problem.py
maths/josephus_problem.py
""" 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) 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: """ 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 while len(circle) > 1: current = (current + step_size - 1) % len(circle) circle.pop(current) return circle[0] if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/two_sum.py
maths/two_sum.py
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: """ >>> two_sum([2, 7, 11, 15], 9) [0, 1] >>> two_sum([15, 2, 11, 7], 13) [1, 2] >>> two_sum([2, 7, 11, 15], 17) [0, 3] >>> two_sum([7, 15, 11, 2], 18) [0, 2] >>> two_sum([2, 7, 11, 15], 26) [2, 3] >>> two_sum([2, 7, 11, 15], 8) [] >>> two_sum([3 * i for i in range(10)], 19) [] """ chk_map: dict[int, int] = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: return [chk_map[compl], index] chk_map[val] = index return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_sum([2, 7, 11, 15], 9) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/eulers_totient.py
maths/eulers_totient.py
# 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 has 1 relative primes. 3 has 2 relative primes. 4 has 2 relative primes. 5 has 4 relative primes. 6 has 2 relative primes. 7 has 6 relative primes. 8 has 4 relative primes. 9 has 6 relative primes. """ is_prime = [True for i in range(n + 1)] totients = [i - 1 for i in range(n + 1)] primes = [] for i in range(2, n + 1): if is_prime[i]: primes.append(i) for j in range(len(primes)): if i * primes[j] >= n: break is_prime[i * primes[j]] = False if i % primes[j] == 0: totients[i * primes[j]] = totients[i] * primes[j] break totients[i * primes[j]] = totients[i] * (primes[j] - 1) return totients if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/odd_sieve.py
maths/odd_sieve.py
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/Sieve_of_Eratosthenes). >>> odd_sieve(2) [] >>> odd_sieve(3) [2] >>> odd_sieve(10) [2, 3, 5, 7] >>> odd_sieve(20) [2, 3, 5, 7, 11, 13, 17, 19] """ if num <= 2: return [] if num == 3: return [2] # Odd sieve for numbers in range [3, num - 1] sieve = bytearray(b"\x01") * ((num >> 1) - 1) for i in range(3, int(sqrt(num)) + 1, 2): if sieve[(i >> 1) - 1]: i_squared = i**2 sieve[(i_squared >> 1) - 1 :: i] = repeat( 0, ceil((num - i_squared) / (i << 1)) ) return [2, *list(compress(range(3, num, 2), sieve))] if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/bailey_borwein_plouffe.py
maths/bailey_borwein_plouffe.py
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): 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 """ 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 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/least_common_multiple.py
maths/least_common_multiple.py
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 >>> 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): common_mult += max_num return common_mult 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 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/mobius_function.py
maths/mobius_function.py
""" 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/ceil.py
maths/ceil.py
""" 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/base_neg2_conversion.py
maths/base_neg2_conversion.py
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_2(0) 0 >>> decimal_to_negative_base_2(-19) 111101 >>> decimal_to_negative_base_2(4) 100 >>> decimal_to_negative_base_2(7) 11011 """ if num == 0: return 0 ans = "" while num != 0: num, rem = divmod(num, -2) if rem < 0: rem += 2 num += 1 ans = str(rem) + ans return int(ans) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/gcd_of_n_numbers.py
maths/gcd_of_n_numbers.py
""" 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) 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: 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: """ 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: 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
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/factorial.py
maths/factorial.py
""" 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: 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: """ Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> 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 """ if not isinstance(n, int): raise ValueError("factorial() only accepts integral values") if n < 0: raise ValueError("factorial() 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)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/find_max.py
maths/find_max.py
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]) 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] 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: """ 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 ( 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)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/area_under_curve.py
maths/area_under_curve.py
""" 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 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 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
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/spearman_rank_correlation_coefficient.py
maths/spearman_rank_correlation_coefficient.py
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] >>> 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) 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: """ 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) # 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]) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/manhattan_distance.py
maths/manhattan_distance.py
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) 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: """ >>> _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: 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: """ 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) 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/remove_digit.py
maths/remove_digit.py
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("2222222") Traceback (most recent call last): TypeError: only integers accepted as input >>> remove_digit("string input") Traceback (most recent call last): TypeError: only integers accepted as input """ if not isinstance(num, int): raise TypeError("only integers accepted as input") else: num_str = str(abs(num)) num_transpositions = [list(num_str) for char in range(len(num_str))] for index in range(len(num_str)): num_transpositions[index].pop(index) return max( int("".join(list(transposition))) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sumset.py
maths/sumset.py
""" Calculates the SumSet of two sets of numbers (A and B) Source: https://en.wikipedia.org/wiki/Sumset """ def sumset(set_a: set, set_b: set) -> set: """ :param first set: a set of numbers :param second set: a set of numbers :return: the nth number in Sylvester's sequence >>> sumset({1, 2, 3}, {4, 5, 6}) {5, 6, 7, 8, 9} >>> sumset({1, 2, 3}, {4, 5, 6, 7}) {5, 6, 7, 8, 9, 10} >>> sumset({1, 2, 3, 4}, 3) Traceback (most recent call last): ... AssertionError: The input value of [set_b=3] is not a set """ assert isinstance(set_a, set), f"The input value of [set_a={set_a}] is not a set" assert isinstance(set_b, set), f"The input value of [set_b={set_b}] is not a set" return {a + b for a in set_a for b in set_b} if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sieve_of_eratosthenes.py
maths/sieve_of_eratosthenes.py
""" 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())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/binomial_distribution.py
maths/binomial_distribution.py
"""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))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/average_median.py
maths/average_median.py
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 Returns: Median. """ # The sorted function returns list[SupportsRichComparisonT@sorted] # which does not support `+` sorted_list: list[int] = sorted(nums) length = len(sorted_list) mid_index = length >> 1 return ( (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 if length % 2 == 0 else sorted_list[mid_index] ) def main(): import doctest doctest.testmod() if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/find_min.py
maths/find_min.py
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(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] 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: """ 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 ( 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)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/gaussian.py
maths/gaussian.py
""" 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/kth_lexicographic_permutation.py
maths/kth_lexicographic_permutation.py
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], [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], [1,2,3,0], [1,3,0,2] >>> kth_permutation(10,4) [1, 3, 0, 2] """ # Factorails from 1! to (n-1)! factorials = [1] for i in range(2, n): factorials.append(factorials[-1] * i) assert 0 <= k < factorials[-1] * n, "k out of bounds" permutation = [] elements = list(range(n)) # Find permutation while factorials: factorial = factorials.pop() number, k = divmod(k, factorial) permutation.append(elements[number]) elements.remove(elements[number]) permutation.append(elements[0]) return permutation if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/primelib.py
maths/primelib.py
""" 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_prime(n) get_primes_between(pNumber1, pNumber2) ---- is_even(number) is_odd(number) kg_v(number1, number2) // least common multiple get_divisors(number) // all divisors of 'number' inclusive 1, number is_perfect_number(number) NEW-FUNCTIONS simplify_fraction(numerator, denominator) factorial (n) // n! fib (n) // calculate the n-th fibonacci term. ----- goldbach(number) // Goldbach's assumption """ from math import sqrt from maths.greatest_common_divisor import gcd_by_iterative def is_prime(number: int) -> bool: """ input: positive integer 'number' returns true if 'number' is prime otherwise false. >>> is_prime(3) True >>> is_prime(10) False >>> is_prime(97) True >>> is_prime(9991) False >>> is_prime(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive >>> is_prime("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive """ # precondition assert isinstance(number, int) and (number >= 0), ( "'number' must been an int and positive" ) status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2, round(sqrt(number)) + 1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status, bool), "'status' must been from type bool" return status # ------------------------------------------ def sieve_er(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. >>> sieve_er(8) [2, 3, 5, 7] >>> sieve_er(-1) Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 >>> sieve_er("test") Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(begin_list)): for j in range(i + 1, len(begin_list)): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 # filters actual prime numbers. ans = [x for x in begin_list if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def get_prime_numbers(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' >>> get_prime_numbers(8) [2, 3, 5, 7] >>> get_prime_numbers(-1) Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 >>> get_prime_numbers("test") Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1): if is_prime(number): ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def prime_factorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' >>> prime_factorization(0) [0] >>> prime_factorization(8) [2, 2, 2] >>> prime_factorization(287) [7, 41] >>> prime_factorization(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 >>> prime_factorization("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 """ # precondition assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number in {0, 1}: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(number): while quotient != 1: if is_prime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def greatest_prime_factor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' >>> greatest_prime_factor(0) 0 >>> greatest_prime_factor(8) 2 >>> greatest_prime_factor(287) 41 >>> greatest_prime_factor(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 >>> greatest_prime_factor("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 """ # precondition assert isinstance(number, int) and (number >= 0), ( "'number' must been an int and >= 0" ) ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = max(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallest_prime_factor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' >>> smallest_prime_factor(0) 0 >>> smallest_prime_factor(8) 2 >>> smallest_prime_factor(287) 7 >>> smallest_prime_factor(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 >>> smallest_prime_factor("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 """ # precondition assert isinstance(number, int) and (number >= 0), ( "'number' must been an int and >= 0" ) ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = min(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def is_even(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. >>> is_even(0) True >>> is_even(8) True >>> is_even(287) False >>> is_even(-1) False >>> is_even("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare must been from type bool" return number % 2 == 0 # ------------------------ def is_odd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. >>> is_odd(0) False >>> is_odd(8) False >>> is_odd(287) True >>> is_odd(-1) True >>> is_odd("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare must been from type bool" return number % 2 != 0 # ------------------------ def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' >>> goldbach(8) [3, 5] >>> goldbach(824) [3, 821] >>> goldbach(0) Traceback (most recent call last): ... AssertionError: 'number' must been an int, even and > 2 >>> goldbach(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int, even and > 2 >>> goldbach("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int, even and > 2 """ # precondition assert isinstance(number, int) and (number > 2) and is_even(number), ( "'number' must been an int, even and > 2" ) ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < len_pn and loop: j = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) ans.append(prime_numbers[j]) j += 1 i += 1 # precondition assert ( isinstance(ans, list) and (len(ans) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0]) and is_prime(ans[1]) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- def kg_v(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' >>> kg_v(8,10) 40 >>> kg_v(824,67) 55208 >>> kg_v(1, 10) 10 >>> kg_v(0) Traceback (most recent call last): ... TypeError: kg_v() missing 1 required positional argument: 'number2' >>> kg_v(10,-1) Traceback (most recent call last): ... AssertionError: 'number1' and 'number2' must been positive integer. >>> kg_v("test","test2") Traceback (most recent call last): ... AssertionError: 'number1' and 'number2' must been positive integer. """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_1: if n not in done: if n in prime_fac_2: count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) for _ in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in prime_fac_2: if n not in done: count2 = prime_fac_2.count(n) for _ in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans, int) and (ans >= 0), ( "'ans' must been from type int and positive" ) return ans # ---------------------------------- def get_prime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 >>> get_prime(0) 2 >>> get_prime(8) 23 >>> get_prime(824) 6337 >>> get_prime(-1) Traceback (most recent call last): ... AssertionError: 'number' must been a positive int >>> get_prime("test") Traceback (most recent call last): ... AssertionError: 'number' must been a positive int """ # precondition assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(ans): ans += 1 # precondition assert isinstance(ans, int) and is_prime(ans), ( "'ans' must been a prime number and from type int" ) return ans # --------------------------------------------------- def get_primes_between(p_number_1, p_number_2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusive) and 'pNumber2' (exclusive) >>> get_primes_between(3, 67) [5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61] >>> get_primes_between(0) Traceback (most recent call last): ... TypeError: get_primes_between() missing 1 required positional argument: 'p_number_2' >>> get_primes_between(0, 1) Traceback (most recent call last): ... AssertionError: The arguments must been prime numbers and 'pNumber1' < 'pNumber2' >>> get_primes_between(-1, 3) Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive >>> get_primes_between("test","test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive """ # precondition assert ( is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = p_number_1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(number): number += 1 while number < p_number_2: ans.append(number) number += 1 # fetch the next prime number. while not is_prime(number): number += 1 # precondition assert ( isinstance(ans, list) and ans[0] != p_number_1 and ans[len(ans) - 1] != p_number_2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def get_divisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') >>> get_divisors(8) [1, 2, 4, 8] >>> get_divisors(824) [1, 2, 4, 8, 103, 206, 412, 824] >>> get_divisors(-1) Traceback (most recent call last): ... AssertionError: 'n' must been int and >= 1 >>> get_divisors("test") Traceback (most recent call last): ... AssertionError: 'n' must been int and >= 1 """ # precondition assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) # precondition assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans # ---------------------------------------------------- def is_perfect_number(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. >>> is_perfect_number(28) True >>> is_perfect_number(824) False >>> is_perfect_number(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 1 >>> is_perfect_number("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 1 """ # precondition assert isinstance(number, int) and (number > 1), ( "'number' must been an int and >= 1" ) divisors = get_divisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ def simplify_fraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. >>> simplify_fraction(10, 20) (1, 2) >>> simplify_fraction(10, -1) (10, -1) >>> simplify_fraction("test","test") Traceback (most recent call last): ... AssertionError: The arguments must been from type int and 'denominator' != 0 """ # precondition assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcd_of_fraction = gcd_by_iterative(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcd_of_fraction, int) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd_by_iterative(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) # ----------------------------------------------------------------- def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) >>> factorial(0) 1 >>> factorial(20) 2432902008176640000 >>> factorial(-1) Traceback (most recent call last): ... AssertionError: 'n' must been a int and >= 0 >>> factorial("test") Traceback (most recent call last): ... AssertionError: 'n' must been a int and >= 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1, n + 1): ans *= factor return ans # ------------------------------------------------------------------- def fib(n: int) -> int: """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 >>> fib(0) 1 >>> fib(5) 8 >>> fib(20) 10946 >>> fib(99) 354224848179261915075 >>> fib(-1) Traceback (most recent call last): ... AssertionError: 'n' must been an int and >= 0 >>> fib("test") Traceback (most recent call last): ... AssertionError: 'n' must been an int and >= 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for _ in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/persistence.py
maths/persistence.py
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: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/average_mode.py
maths/average_mode.py
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, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2]) [2] >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2]) [2, 4] >>> mode(["x", "y", "y", "z"]) ['y'] >>> mode(["x", "x" , "y", "y", "z"]) ['x', 'y'] """ if not input_list: return [] result = [input_list.count(value) for value in input_list] y = max(result) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(result) if value == y}) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/collatz_sequence.py
maths/collatz_sequence.py
""" 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 from collections.abc import Generator 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") 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/average_absolute_deviation.py
maths/average_absolute_deviation.py
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_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0]) 20.0 >>> average_absolute_deviation([-20, 0, 30, 15]) 16.25 >>> average_absolute_deviation([]) Traceback (most recent call last): ... ValueError: List is empty """ if not nums: # Makes sure that the list is not empty raise ValueError("List is empty") average = sum(nums) / len(nums) # Calculate the average return sum(abs(x - average) for x in nums) / len(nums) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/is_int_palindrome.py
maths/is_int_palindrome.py
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(11) True >>> is_int_palindrome(101) True >>> is_int_palindrome(120) False """ if num < 0: return False num_copy: int = num rev_num: int = 0 while num > 0: rev_num = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/zellers_congruence.py
maths/zellers_congruence.py
import argparse import datetime def zeller(date_input: str) -> str: """ | Zellers Congruence Algorithm | Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month: >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of `date_input`: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/prime_factors.py
maths/prime_factors.py
""" 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: 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]: """ 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: 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/signum.py
maths/signum.py
""" 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 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))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/average_mean.py
maths/average_mean.py
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([]) Traceback (most recent call last): ... ValueError: List is empty """ if not nums: raise ValueError("List is empty") return sum(nums) / len(nums) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/modular_division.py
maths/modular_division.py
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 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 """ assert n > 1 assert a > 0 assert greatest_common_divisor(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: """ 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 return b # ------------------ Finding Modular division using invert_modulo ------------------- 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 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]: """ 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) k = a // b return (y, x - k * y) 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 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)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sylvester_sequence.py
maths/sylvester_sequence.py
""" Calculates the nth number in Sylvester's sequence Source: https://en.wikipedia.org/wiki/Sylvester%27s_sequence """ def sylvester(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Sylvester's sequence >>> sylvester(8) 113423713055421844361000443 >>> sylvester(-1) Traceback (most recent call last): ... ValueError: The input value of [n=-1] has to be > 0 >>> sylvester(8.0) Traceback (most recent call last): ... AssertionError: The input value of [n=8.0] is not an integer """ assert isinstance(number, int), f"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: msg = f"The input value of [n={number}] has to be > 0" raise ValueError(msg) else: num = sylvester(number - 1) lower = num - 1 upper = num return lower * upper + 1 if __name__ == "__main__": print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/modular_exponential.py
maths/modular_exponential.py
""" 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 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(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/lucas_lehmer_primality_test.py
maths/lucas_lehmer_primality_test.py
""" 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 the primality test used by the Great Internet Mersenne Prime Search (GIMPS) to locate large primes. """ # Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 m = (1 << p) - 1 for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/largest_of_very_large_numbers.py
maths/largest_of_very_large_numbers.py
# 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 """ if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.log10(x) elif x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen") if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. prompt = "Enter the base and the power separated by a comma: " x1, y1 = map(int, input(prompt).split(",")) x2, y2 = map(int, input(prompt).split(",")) # We find the log of each number, using the function res(), which takes two # arguments. res1 = res(x1, y1) res2 = res(x2, y2) # We check for the largest number if res1 > res2: print("Largest number is", x1, "^", y1) elif res2 > res1: print("Largest number is", x2, "^", y2) else: print("Both are equal")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/chudnovsky_algorithm.py
maths/chudnovsky_algorithm.py
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 / ((multinomial_term * linear_term) / exponential_term) where constant_term = 426880 * sqrt(10005) The linear_term and the exponential_term can be defined iteratively as follows: L_k+1 = L_k + 545140134 where L_0 = 13591409 X_k+1 = X_k * -262537412640768000 where X_0 = 1 The multinomial_term is defined as follows: 6k! / ((3k)! * (k!) ^ 3) where k is the k_th iteration. This algorithm correctly calculates around 14 digits of PI per iteration >>> pi(10) '3.14159265' >>> pi(100) '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706' >>> pi('hello') Traceback (most recent call last): ... TypeError: Undefined for non-integers >>> pi(-1) Traceback (most recent call last): ... ValueError: Undefined for non-natural numbers """ if not isinstance(precision, int): raise TypeError("Undefined for non-integers") elif precision < 1: raise ValueError("Undefined for non-natural numbers") getcontext().prec = precision num_iterations = ceil(precision / 14) constant_term = 426880 * Decimal(10005).sqrt() exponential_term = 1 linear_term = 13591409 partial_sum = Decimal(linear_term) for k in range(1, num_iterations): multinomial_term = factorial(6 * k) // (factorial(3 * k) * factorial(k) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term) / exponential_term return str(constant_term / partial_sum)[:-1] if __name__ == "__main__": n = 50 print(f"The first {n} digits of pi is: {pi(n)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false