Description
stringlengths
18
161k
Code
stringlengths
15
300k
references https en wikipedia orgwikimc3b6biusfunction references wikipedia square free number psfblack true ruff true mobius function mobius24 0 mobius1 1 mobius asd traceback most recent call last typeerror not supported between instances of int and str mobius10400 0 mobius10400 1 mobius1424 1 mobius1 2 2 0 traceback most recent call last typeerror not supported between instances of int and list 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
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def mobius(n: int) -> int: factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
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 gcda n1 and n1 the algorithm should return an integer x such that 0xn1 and baxmodn that is baxmodn theorem a has a multiplicative inverse modulo n iff gcda n 1 this find x ba1 mod n uses extendedeuclid to find the inverse of a modulardivision4 8 5 2 modulardivision3 8 5 1 modulardivision4 11 5 4 this function find the inverses of a i e a1 invertmodulo2 5 3 invertmodulo8 7 1 finding modular division using invertmodulo this function used the above inversion of a to find x ba1mod n modulardivision24 8 5 2 modulardivision23 8 5 1 modulardivision24 11 5 4 extended euclid s algorithm if d divides a and b and d ax by for integers x and y then d gcda b extendedgcd10 6 2 1 2 extendedgcd7 5 1 2 3 extendedgcd function is used when d gcda b is required in output extended euclid extendedeuclid10 6 1 2 extendedeuclid7 5 2 3 euclid s lemma d divides a and b if and only if d divides ab and b euclid s algorithm greatestcommondivisor7 5 1 note in number theory two integers a and b are said to be relatively prime mutually prime or coprime if the only positive integer factor that divides both of them is 1 i e gcda b 1 greatestcommondivisor121 11 11 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 implemented below this function find the inverses of a i e a 1 invert_modulo 2 5 3 invert_modulo 8 7 1 implemented below finding modular division using invert_modulo 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 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 extended euclid extended_euclid 10 6 1 2 extended_euclid 7 5 2 3 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
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: assert n > 1 assert a > 0 assert greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: (b, x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b def modular_division2(a: int, b: int, n: int) -> int: s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> tuple[int, int, int]: assert a >= 0 assert b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 assert b % d == 0 assert d == a * x + b * y return (d, x, y) def extended_euclid(a: int, b: int) -> tuple[int, int]: if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) def greatest_common_divisor(a: int, b: int) -> int: if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
modular exponential modular exponentiation is a type of exponentiation performed over a modulus for more explanation please check https en wikipedia orgwikimodularexponentiation calculate modular exponential def modularexponentialbase int power int mod int if power 0 return 1 base mod result 1 while power 0 if power 1 result result base mod power power 1 base base base mod return result def main calculate modular exponential modular_exponential 5 0 10 1 modular_exponential 2 8 7 4 modular_exponential 3 2 9 1 call modular exponential function
def modular_exponential(base: int, power: int, mod: int): if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
matteoraso 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 our circle has a radius of 1 so a distance greater than 1 would land outside the circle the proportion of guesses that landed in the circle the ratio of the area for circle to square is pi4 an implementation of the monte carlo method to find area under a single variable nonnegative realvalued continuous function say fx where x lies within a continuous bounded interval say minvalue maxvalue where minvalue and maxvalue are finite numbers 1 let x be a uniformly distributed random variable between minvalue to maxvalue 2 expected value of fx integrate fx from minvalue to maxvaluemaxvalue minvalue 3 finding expected value of fx a repeatedly draw x from uniform distribution b evaluate fx at each of the drawn x values c expected value average of the function evaluations 4 estimated value of integral expected value maxvalue minvalue 5 returns estimated value checks estimation error for areaundercurveestimator function for fx x where x lies within minvalue to maxvalue 1 calls areaundercurveestimator function 2 compares with the expected value 3 prints estimated expected and error value represents identity function functiontointegratex for x in 2 0 1 0 0 0 1 0 2 0 2 0 1 0 0 0 1 0 2 0 area under curve y sqrt4 x2 where x lies in 0 to 2 is equal to pi represents semicircle with radius 2 functiontointegratex for x in 2 0 0 0 2 0 0 0 2 0 0 0 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 our circle has a radius of 1 so a distance greater than 1 would land outside the circle the proportion of guesses that landed in the circle the ratio of the area for circle to square is pi 4 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 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 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 area under curve y sqrt 4 x 2 where x lies in 0 to 2 is equal to pi 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
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def pi_estimator(iterations: int): def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x**2) + (y**2)) return distance_from_centre <= 1 proportion = mean( int(is_in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0))) for _ in range(iterations) ) pi_estimate = proportion * 4 print(f"The estimated value of pi is {pi_estimate}") print(f"The numpy value of pi is {pi}") print(f"The total error is {abs(pi - pi_estimate)}") def area_under_curve_estimator( iterations: int, function_to_integrate: Callable[[float], float], min_value: float = 0.0, max_value: float = 1.0, ) -> float: return mean( function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations) ) * (max_value - min_value) def area_under_line_estimator_check( iterations: int, min_value: float = 0.0, max_value: float = 1.0 ) -> None: def identity_function(x: float) -> float: return x estimated_value = area_under_curve_estimator( iterations, identity_function, min_value, max_value ) expected_value = (max_value * max_value - min_value * min_value) / 2 print("******************") print(f"Estimating area under y=x where x varies from {min_value} to {max_value}") print(f"Estimated value is {estimated_value}") print(f"Expected value is {expected_value}") print(f"Total error is {abs(estimated_value - expected_value)}") print("******************") def pi_estimator_using_area_under_curve(iterations: int) -> None: def function_to_integrate(x: float) -> float: return sqrt(4.0 - x * x) estimated_value = area_under_curve_estimator( iterations, function_to_integrate, 0.0, 2.0 ) print("******************") print("Estimating pi using area_under_curve_estimator") print(f"Estimated value is {estimated_value}") print(f"Expected value is {pi}") print(f"Total error is {abs(estimated_value - pi)}") print("******************") if __name__ == "__main__": import doctest doctest.testmod()
initialize a six sided dice self sides listrange1 dice numsides 1 def rollself return random choiceself sides def throwdicenumthrows int numdice int 2 listfloat dices dice for i in rangenumdice countofsum 0 lendices dice numsides 1 for in rangenumthrows countofsumsumdice roll for dice in dices 1 probability roundcount 100 numthrows 2 for count in countofsum return probabilitynumdice remove probability of sums that never appear if name main import doctest doctest testmod initialize a six sided dice 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 remove probability of sums that never appear
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): 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]: 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:] if __name__ == "__main__": import doctest doctest.testmod()
find the number of digits in a number numdigits12345 5 numdigits123 3 numdigits0 1 numdigits1 1 numdigits123456 6 numdigits 123 raises a typeerror for noninteger input traceback most recent call last typeerror input must be an integer find the number of digits in a number abs is used as logarithm for negative numbers is not defined numdigitsfast12345 5 numdigitsfast123 3 numdigitsfast0 1 numdigitsfast1 1 numdigitsfast123456 6 numdigits 123 raises a typeerror for noninteger input traceback most recent call last typeerror input must be an integer find the number of digits in a number abs is used for negative numbers numdigitsfaster12345 5 numdigitsfaster123 3 numdigitsfaster0 1 numdigitsfaster1 1 numdigitsfaster123456 6 numdigits 123 raises a typeerror for noninteger input traceback most recent call last typeerror input must be an integer benchmark multiple functions with three different length int values 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 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 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 benchmark multiple functions with three different length int values
import math from timeit import timeit def num_digits(n: int) -> int: if not isinstance(n, int): raise TypeError("Input must be an integer") digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: if not isinstance(n, int): raise TypeError("Input must be an integer") return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: if not isinstance(n, int): raise TypeError("Input must be an integer") return len(str(abs(n))) def benchmark() -> None: from collections.abc import Callable def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") print(f"{call}: {func(value)} -- {timing} seconds") for value in (262144, 1125899906842624, 1267650600228229401496703205376): for func in (num_digits, num_digits_fast, num_digits_faster): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
use the adamsbashforth methods to solve ordinary differential equations https en wikipedia orgwikilinearmultistepmethod ravi kumar args func an ordinary differential equation ode as function of x and y xinitials list containing initial required values of x yinitials list containing initial required values of y stepsize the increment value of x xfinal the final value of x returns solution of y at each nodal point def fx y return x y adamsbashforthf 0 0 2 0 4 0 0 2 1 0 2 1 doctest ellipsis adamsbashforthfunc xinitials0 0 2 0 4 yinitials0 0 2 1 step adamsbashforthf 0 0 2 1 0 0 0 04 0 2 1 step2 traceback most recent call last valueerror the final value of x must be greater than the initial values of x adamsbashforthf 0 0 2 0 3 0 0 0 04 0 2 1 step3 traceback most recent call last valueerror xvalues must be equally spaced according to step size adamsbashforthf 0 0 2 0 4 0 6 0 8 0 0 0 04 0 128 0 307 0 2 1 step5 traceback most recent call last valueerror step size must be positive def fx y return x adamsbashforthf 0 0 2 0 0 0 2 1 step2 array0 0 0 06 0 16 0 3 0 48 adamsbashforthf 0 0 2 0 4 0 0 0 04 0 2 1 step2 traceback most recent call last valueerror insufficient initial points information def fx y return x y y adamsbashforthf 0 0 2 0 4 0 0 0 04 0 2 1 step3 y3 0 15533333333333332 adamsbashforthf 0 0 2 0 0 0 2 1 step3 traceback most recent call last valueerror insufficient initial points information def fx y return x y y adamsbashforth f 0 0 2 0 4 0 6 0 0 0 04 0 128 0 2 1 step4 y4 0 30699999999999994 y5 0 5771083333333333 adamsbashforthf 0 0 2 0 4 0 0 0 04 0 2 1 step4 traceback most recent call last valueerror insufficient initial points information def fx y return x y y adamsbashforth f 0 0 2 0 4 0 6 0 8 0 0 02140 0 02140 0 22211 0 42536 0 2 1 step5 y1 0 05436839444444452 adamsbashforthf 0 0 2 0 4 0 0 0 04 0 2 1 step5 traceback most recent call last valueerror insufficient initial points information args func an ordinary differential equation ode as function of x and y x_initials list containing initial required values of x y_initials list containing initial required values of y step_size the increment value of x x_final the final value of x returns solution of y at each nodal point def f x y return x y adamsbashforth f 0 0 2 0 4 0 0 2 1 0 2 1 doctest ellipsis adamsbashforth func x_initials 0 0 2 0 4 y_initials 0 0 2 1 step adamsbashforth f 0 0 2 1 0 0 0 04 0 2 1 step_2 traceback most recent call last valueerror the final value of x must be greater than the initial values of x adamsbashforth f 0 0 2 0 3 0 0 0 04 0 2 1 step_3 traceback most recent call last valueerror x values must be equally spaced according to step size adamsbashforth f 0 0 2 0 4 0 6 0 8 0 0 0 04 0 128 0 307 0 2 1 step_5 traceback most recent call last valueerror step size must be positive def f x y return x adamsbashforth f 0 0 2 0 0 0 2 1 step_2 array 0 0 0 06 0 16 0 3 0 48 adamsbashforth f 0 0 2 0 4 0 0 0 04 0 2 1 step_2 traceback most recent call last valueerror insufficient initial points information def f x y return x y y adamsbashforth f 0 0 2 0 4 0 0 0 04 0 2 1 step_3 y 3 0 15533333333333332 adamsbashforth f 0 0 2 0 0 0 2 1 step_3 traceback most recent call last valueerror insufficient initial points information def f x y return x y y adamsbashforth f 0 0 2 0 4 0 6 0 0 0 04 0 128 0 2 1 step_4 y 4 0 30699999999999994 y 5 0 5771083333333333 adamsbashforth f 0 0 2 0 4 0 0 0 04 0 2 1 step_4 traceback most recent call last valueerror insufficient initial points information def f x y return x y y adamsbashforth f 0 0 2 0 4 0 6 0 8 0 0 02140 0 02140 0 22211 0 42536 0 2 1 step_5 y 1 0 05436839444444452 adamsbashforth f 0 0 2 0 4 0 0 0 04 0 2 1 step_5 traceback most recent call last valueerror insufficient initial points information
from collections.abc import Callable from dataclasses import dataclass import numpy as np @dataclass class AdamsBashforth: func: Callable[[float, float], float] x_initials: list[float] y_initials: list[float] step_size: float x_final: float def __post_init__(self) -> None: if self.x_initials[-1] >= self.x_final: raise ValueError( "The final value of x must be greater than the initial values of x." ) if self.step_size <= 0: raise ValueError("Step size must be positive.") if not all( round(x1 - x0, 10) == self.step_size for x0, x1 in zip(self.x_initials, self.x_initials[1:]) ): raise ValueError("x-values must be equally spaced according to step size.") def step_2(self) -> np.ndarray: if len(self.x_initials) != 2 or len(self.y_initials) != 2: raise ValueError("Insufficient initial points information.") x_0, x_1 = self.x_initials[:2] y_0, y_1 = self.y_initials[:2] n = int((self.x_final - x_1) / self.step_size) y = np.zeros(n + 2) y[0] = y_0 y[1] = y_1 for i in range(n): y[i + 2] = y[i + 1] + (self.step_size / 2) * ( 3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i]) ) x_0 = x_1 x_1 += self.step_size return y def step_3(self) -> np.ndarray: if len(self.x_initials) != 3 or len(self.y_initials) != 3: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2 = self.x_initials[:3] y_0, y_1, y_2 = self.y_initials[:3] n = int((self.x_final - x_2) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 for i in range(n + 1): y[i + 3] = y[i + 2] + (self.step_size / 12) * ( 23 * self.func(x_2, y[i + 2]) - 16 * self.func(x_1, y[i + 1]) + 5 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 += self.step_size return y def step_4(self) -> np.ndarray: if len(self.x_initials) != 4 or len(self.y_initials) != 4: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3 = self.x_initials[:4] y_0, y_1, y_2, y_3 = self.y_initials[:4] n = int((self.x_final - x_3) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 for i in range(n): y[i + 4] = y[i + 3] + (self.step_size / 24) * ( 55 * self.func(x_3, y[i + 3]) - 59 * self.func(x_2, y[i + 2]) + 37 * self.func(x_1, y[i + 1]) - 9 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 += self.step_size return y def step_5(self) -> np.ndarray: if len(self.x_initials) != 5 or len(self.y_initials) != 5: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5] y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5] n = int((self.x_final - x_4) / self.step_size) y = np.zeros(n + 6) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 y[4] = y_4 for i in range(n + 1): y[i + 5] = y[i + 4] + (self.step_size / 720) * ( 1901 * self.func(x_4, y[i + 4]) - 2774 * self.func(x_3, y[i + 3]) - 2616 * self.func(x_2, y[i + 2]) - 1274 * self.func(x_1, y[i + 1]) + 251 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 = x_4 x_4 += self.step_size return y if __name__ == "__main__": import doctest doctest.testmod()
finds where function becomes 0 in a b using bolzano bisectionlambda x x 3 1 5 5 1 0000000149011612 bisectionlambda x x 3 1 2 1000 traceback most recent call last valueerror could not find root in given interval bisectionlambda x x 2 4 x 3 0 2 1 0 bisectionlambda x x 2 4 x 3 2 4 3 0 bisectionlambda x x 2 4 x 3 4 1000 traceback most recent call last valueerror could not find root in given interval then this algorithm can t find the root finds where function becomes 0 in a b using bolzano bisection lambda x x 3 1 5 5 1 0000000149011612 bisection lambda x x 3 1 2 1000 traceback most recent call last valueerror could not find root in given interval bisection lambda x x 2 4 x 3 0 2 1 0 bisection lambda x x 2 4 x 3 2 4 3 0 bisection lambda x x 2 4 x 3 4 1000 traceback most recent call last valueerror could not find root in given interval one of the a or b is a root for the function if none of these are root and they are both positive or negative then this algorithm can t find the root until precisely equals to 10 7
from collections.abc import Callable def bisection(function: Callable[[float], float], a: float, b: float) -> float: start: float = a end: float = b if function(a) == 0: return a elif function(b) == 0: return b elif ( function(a) * function(b) > 0 ): raise ValueError("could not find root in given interval.") else: mid: float = start + (end - start) / 2.0 while abs(start - mid) > 10**-7: if function(mid) == 0: return mid elif function(mid) * function(start) < 0: end = mid else: start = mid mid = start + (end - start) / 2.0 return mid def f(x: float) -> float: return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
given a function on floating number fx and two floating numbers a and b such that fa fb 0 and fx is continuous in a b here fx represents algebraic or transcendental equation find root of function in interval a b or find a value of x such that fx is 0 https en wikipedia orgwikibisectionmethod equation5 15 equation0 10 equation5 15 equation0 1 9 99 equation0 1 9 99 bisection2 5 3 1611328125 bisection0 6 3 158203125 bisection2 3 traceback most recent call last valueerror wrong space bolzano theory in order to find if there is a root between a and b find middle point check if middle point is root decide the side to repeat the steps equation 5 15 equation 0 10 equation 5 15 equation 0 1 9 99 equation 0 1 9 99 bisection 2 5 3 1611328125 bisection 0 6 3 158203125 bisection 2 3 traceback most recent call last valueerror wrong space bolzano theory in order to find if there is a root between a and b find middle point check if middle point is root decide the side to repeat the steps
def equation(x: float) -> float: return 10 - x * x def bisection(a: float, b: float) -> float: if equation(a) * equation(b) >= 0: raise ValueError("Wrong space!") c = a while (b - a) >= 0.01: c = (a + b) / 2 if equation(c) == 0.0: break if equation(c) * equation(a) < 0: b = c else: a = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
syed faizan 3rd year iiit pune github faizan2700 purpose you have one function fx which takes float integer and returns float you have to integrate the function in limits a to b the approximation proposed by thomas simpsons in 1743 is one way to calculate integration read article https cpalgorithms comnummethodssimpsonintegration html simpsonintegration takes function lowerlimita upperlimitb precision and returns the integration of function in given limit constants the more the number of steps the more accurate summary of simpson approximation by simpsons integration 1 integration of fxdx with limit a to b is fx0 4 fx1 2 fx2 4 fx3 2 fx4 fxn where x0 a xi a i h xn b args function the function which s integration is desired a the lower limit of integration b upper limit of integration precision precision of the result error required default is 4 returns result the value of the approximated integration of function in range a to b raises assertionerror function is not callable assertionerror a is not float or integer assertionerror function should return float or integer assertionerror b is not float or integer assertionerror precision is not positive integer simpsonintegrationlambda x xx 1 2 3 2 333 simpsonintegrationlambda x xx wronginput 2 3 traceback most recent call last assertionerror a should be float or integer your input wronginput simpsonintegrationlambda x xx 1 wronginput 3 traceback most recent call last assertionerror b should be float or integer your input wronginput simpsonintegrationlambda x xx 1 2 wronginput traceback most recent call last assertionerror precision should be positive integer your input wronginput simpsonintegration wronginput 2 3 4 traceback most recent call last assertionerror the functionobject passed should be callable your input simpsonintegrationlambda x xx 3 45 3 2 1 2 8 simpsonintegrationlambda x xx 3 45 3 2 0 traceback most recent call last assertionerror precision should be positive integer your input 0 simpsonintegrationlambda x xx 3 45 3 2 1 traceback most recent call last assertionerror precision should be positive integer your input 1 just applying the formula of simpson for approximate integration written in mentioned article in first comment of this file and above this function constants the more the number of steps the more accurate summary of simpson approximation by simpsons integration 1 integration of fxdx with limit a to b is f x0 4 f x1 2 f x2 4 f x3 2 f x4 f xn where x0 a xi a i h xn b args function the function which s integration is desired a the lower limit of integration b upper limit of integration precision precision of the result error required default is 4 returns result the value of the approximated integration of function in range a to b raises assertionerror function is not callable assertionerror a is not float or integer assertionerror function should return float or integer assertionerror b is not float or integer assertionerror precision is not positive integer simpson_integration lambda x x x 1 2 3 2 333 simpson_integration lambda x x x wrong_input 2 3 traceback most recent call last assertionerror a should be float or integer your input wrong_input simpson_integration lambda x x x 1 wrong_input 3 traceback most recent call last assertionerror b should be float or integer your input wrong_input simpson_integration lambda x x x 1 2 wrong_input traceback most recent call last assertionerror precision should be positive integer your input wrong_input simpson_integration wrong_input 2 3 4 traceback most recent call last assertionerror the function object passed should be callable your input simpson_integration lambda x x x 3 45 3 2 1 2 8 simpson_integration lambda x x x 3 45 3 2 0 traceback most recent call last assertionerror precision should be positive integer your input 0 simpson_integration lambda x x x 3 45 3 2 1 traceback most recent call last assertionerror precision should be positive integer your input 1 just applying the formula of simpson for approximate integration written in mentioned article in first comment of this file and above this function
N_STEPS = 1000 def f(x: float) -> float: return x * x def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: assert callable( function ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" assert ( isinstance(precision, int) and precision > 0 ), f"precision should be positive integer your input : {precision}" h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
function is the f we want to find its root x0 and x1 are two random starting points intersectionlambda x x 3 1 5 5 0 9999999999954654 intersectionlambda x x 3 1 5 5 traceback most recent call last zerodivisionerror float division by zero could not find root intersectionlambda x x 3 1 100 200 1 0000000000003888 intersectionlambda x x 2 4 x 3 0 2 0 9999999998088019 intersectionlambda x x 2 4 x 3 2 4 2 9999999998088023 intersectionlambda x x 2 4 x 3 4 1000 3 0000000001786042 intersectionmath sin math pi math pi 0 0 intersectionmath cos math pi math pi traceback most recent call last zerodivisionerror float division by zero could not find root function is the f we want to find its root x0 and x1 are two random starting points intersection lambda x x 3 1 5 5 0 9999999999954654 intersection lambda x x 3 1 5 5 traceback most recent call last zerodivisionerror float division by zero could not find root intersection lambda x x 3 1 100 200 1 0000000000003888 intersection lambda x x 2 4 x 3 0 2 0 9999999998088019 intersection lambda x x 2 4 x 3 2 4 2 9999999998088023 intersection lambda x x 2 4 x 3 4 1000 3 0000000001786042 intersection math sin math pi math pi 0 0 intersection math cos math pi math pi traceback most recent call last zerodivisionerror float division by zero could not find root
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: x_n: float = x0 x_n1: float = x1 while True: if x_n == x_n1 or function(x_n1) == function(x_n): raise ZeroDivisionError("float division by zero, could not find root") x_n2: float = x_n1 - ( function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n)) ) if abs(x_n2 - x_n1) < 10**-5: return x_n2 x_n = x_n1 x_n1 = x_n2 def f(x: float) -> float: return math.pow(x, 3) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
python program to show how to interpolate and evaluate a polynomial using neville s method nevilles method evaluates a polynomial that passes through a given set of x and y points for a particular x value x0 using the newton polynomial form reference https rpubs comaaronsc32nevillesmethodpolynomialinterpolation interpolate and evaluate a polynomial using neville s method arguments xpoints ypoints iterables of x and corresponding y points through which the polynomial passes x0 the value of x to evaluate the polynomial for return value a list of the approximated value and the neville iterations table respectively import pprint nevilleinterpolate1 2 3 4 6 6 7 8 9 11 50 10 0 pprint pprintnevilleinterpolate1 2 3 4 6 6 7 8 9 11 991 0 6 0 0 0 0 7 0 0 0 0 8 104 0 0 0 0 9 104 0 104 0 0 0 11 104 0 104 0 104 0 nevilleinterpolate1 2 3 4 6 6 7 8 9 11 990 104 0 nevilleinterpolate1 2 3 4 6 6 7 8 9 11 traceback most recent call last typeerror unsupported operand types for str and int interpolate and evaluate a polynomial using neville s method arguments x_points y_points iterables of x and corresponding y points through which the polynomial passes x0 the value of x to evaluate the polynomial for return value a list of the approximated value and the neville iterations table respectively import pprint neville_interpolate 1 2 3 4 6 6 7 8 9 11 5 0 10 0 pprint pprint neville_interpolate 1 2 3 4 6 6 7 8 9 11 99 1 0 6 0 0 0 0 7 0 0 0 0 8 104 0 0 0 0 9 104 0 104 0 0 0 11 104 0 104 0 104 0 neville_interpolate 1 2 3 4 6 6 7 8 9 11 99 0 104 0 neville_interpolate 1 2 3 4 6 6 7 8 9 11 traceback most recent call last typeerror unsupported operand type s for str and int
def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): q[i][1] = y_points[i] for i in range(2, n): for j in range(i, n): q[j][i] = ( (x0 - x_points[j - i + 1]) * q[j][i - 1] - (x0 - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
https www geeksforgeeks orgnewtonforwardbackwardinterpolation for calculating u value ucal1 2 0 ucal1 1 2 0 11000000000000011 ucal1 2 2 0 23999999999999994 for calculating forward difference table https www geeksforgeeks org newton forward backward interpolation for calculating u value ucal 1 2 0 ucal 1 1 2 0 11000000000000011 ucal 1 2 2 0 23999999999999994 for calculating forward difference table
from __future__ import annotations import math def ucal(u: float, p: int) -> float: temp = u for i in range(1, p): temp = temp * (u - i) return temp def main() -> None: n = int(input("enter the numbers of values: ")) y: list[list[float]] = [] for _ in range(n): y.append([]) for i in range(n): for j in range(n): y[i].append(j) y[i][j] = 0 print("enter the values of parameters in a list: ") x = list(map(int, input().split())) print("enter the values of corresponding parameters: ") for i in range(n): y[i][0] = float(input()) value = int(input("enter the value to interpolate: ")) u = (value - x[0]) / (x[1] - x[0]) for i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1] summ = y[0][0] for i in range(1, n): summ += (ucal(u, i) * y[0][i]) / math.factorial(i) print(f"the value at {value} is {summ}") if __name__ == "__main__": main()
the newtonraphson method aka the newton method is a rootfinding algorithm that approximates a root of a given realvalued function fx it is an iterative method given by the formula xn 1 xn fxn f xn with the precision of the approximation increasing as the number of iterations increase reference https en wikipedia orgwikinewton27smethod approximate the derivative of a function fx at a point x using the finite difference method import math tolerance 1e5 derivative calcderivativelambda x x2 2 math isclosederivative 4 abstoltolerance true derivative calcderivativemath sin 0 math isclosederivative 1 abstoltolerance true find a root of the given function f using the newtonraphson method param f a realvalued singlevariable function param x0 initial guess param maxiter maximum number of iterations param step step size of x used to approximate f x param maxerror maximum approximation error param logsteps bool denoting whether to log intermediate steps return a tuple containing the approximation the error and the intermediate steps if logsteps is false then an empty list is returned for the third element of the tuple raises zerodivisionerror the derivative approaches 0 raises arithmeticerror no solution exists or the solution isn t found before the iteration limit is reached import math tolerance 1e15 root newtonraphsonlambda x x2 5x 2 0 4 maxerrortolerance math iscloseroot 5 math sqrt17 2 abstoltolerance true root newtonraphsonlambda x math logx 1 2 maxerrortolerance math iscloseroot math e abstoltolerance true root newtonraphsonmath sin 1 maxerrortolerance math iscloseroot 0 abstoltolerance true newtonraphsonmath cos 0 traceback most recent call last zerodivisionerror no converging solution found zero derivative newtonraphsonlambda x x2 1 2 traceback most recent call last arithmeticerror no converging solution found iteration limit reached approximate the derivative of a function f x at a point x using the finite difference method import math tolerance 1e 5 derivative calc_derivative lambda x x 2 2 math isclose derivative 4 abs_tol tolerance true derivative calc_derivative math sin 0 math isclose derivative 1 abs_tol tolerance true find a root of the given function f using the newton raphson method param f a real valued single variable function param x0 initial guess param max_iter maximum number of iterations param step step size of x used to approximate f x param max_error maximum approximation error param log_steps bool denoting whether to log intermediate steps return a tuple containing the approximation the error and the intermediate steps if log_steps is false then an empty list is returned for the third element of the tuple raises zerodivisionerror the derivative approaches 0 raises arithmeticerror no solution exists or the solution isn t found before the iteration limit is reached import math tolerance 1e 15 root _ newton_raphson lambda x x 2 5 x 2 0 4 max_error tolerance math isclose root 5 math sqrt 17 2 abs_tol tolerance true root _ newton_raphson lambda x math log x 1 2 max_error tolerance math isclose root math e abs_tol tolerance true root _ newton_raphson math sin 1 max_error tolerance math isclose root 0 abs_tol tolerance true newton_raphson math cos 0 traceback most recent call last zerodivisionerror no converging solution found zero derivative newton_raphson lambda x x 2 1 2 traceback most recent call last arithmeticerror no converging solution found iteration limit reached set initial guess log intermediate steps calculate next estimate
from collections.abc import Callable RealFunc = Callable[[float], float] def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: return (f(x + delta_x / 2) - f(x - delta_x / 2)) / delta_x def newton_raphson( f: RealFunc, x0: float = 0, max_iter: int = 100, step: float = 1e-6, max_error: float = 1e-6, log_steps: bool = False, ) -> tuple[float, float, list[float]]: def f_derivative(x: float) -> float: return calc_derivative(f, x, step) a = x0 steps = [] for _ in range(max_iter): if log_steps: steps.append(a) error = abs(f(a)) if error < max_error: return a, error, steps if f_derivative(a) == 0: raise ZeroDivisionError("No converging solution found, zero derivative") a -= f(a) / f_derivative(a) raise ArithmeticError("No converging solution found, iteration limit reached") if __name__ == "__main__": import doctest from math import exp, tanh doctest.testmod() def func(x: float) -> float: return tanh(x) ** 2 - exp(3 * x) solution, err, steps = newton_raphson( func, x0=10, max_iter=100, step=1e-6, log_steps=True ) print(f"{solution=}, {err=}") print("\n".join(str(x) for x in steps))
approximates the area under the curve using the trapezoidal rule 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 xstart left end point to indicate the start of line segment param xend 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 fx return 5 3f trapezoidalareaf 12 0 14 0 1000 10 000 def fx return 9x2 4f trapezoidalareaf 4 0 0 10000 192 0000 4f trapezoidalareaf 4 0 4 0 10000 384 0000 approximates small segments of curve as linear and solve for trapezoidal area increment step 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 3f trapezoidal_area f 12 0 14 0 1000 10 000 def f x return 9 x 2 4f trapezoidal_area f 4 0 0 10000 192 0000 4f trapezoidal_area f 4 0 4 0 10000 384 0000 approximates small segments of curve as linear and solve for trapezoidal area increment step
from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x**3 print("f(x) = x^3") print("The area between the curve, x = -10, x = 10 and the x axis is:") i = 10 while i <= 100000: area = trapezoidal_area(f, -5, 5, i) print(f"with {i} steps: {area}") i *= 10
calculate the numeric solution at each step to the ode fx y using rk4 https en wikipedia orgwikirungekuttamethods arguments f the ode as a function of x and y y0 the initial value for y x0 the initial value for x h the stepsize xend the end value for x the exact solution is math expx def fx y return y y0 1 y rungekuttaf y0 0 0 0 01 5 y1 148 41315904125113 calculate the numeric solution at each step to the ode f x y using rk4 https en wikipedia org wiki runge kutta_methods arguments f the ode as a function of x and y y0 the initial value for y x0 the initial value for x h the stepsize x_end the end value for x the exact solution is math exp x def f x y return y y0 1 y runge_kutta f y0 0 0 0 01 5 y 1 148 41315904125113
import numpy as np def runge_kutta(f, y0, x0, h, x_end): n = int(np.ceil((x_end - x0) / h)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): k1 = f(x, y[k]) k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1) k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2) k4 = f(x + h, y[k] + h * k3) y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
use the rungekuttafehlberg method to solve ordinary differential equations solve an ordinary differential equations using rungekuttafehlberg method rkf45 of order 5 https en wikipedia orgwikirungee28093kuttae28093fehlbergmethod args func an ordinary differential equation ode as function of x and y xinitial the initial value of x yinitial the initial value of y stepsize the increment value of x xfinal the final value of x returns solution of y at each nodal point exact value of y1 is tan0 2 0 2027100937470787 def fx y return 1 y2 y rungekuttafehlberg45f 0 0 0 2 1 y1 0 2027100937470787 def fx y return x y rungekuttafehlberg45f 1 0 0 2 0 y1 0 18000000000000002 y rungekuttafehlberg455 0 0 0 1 1 traceback most recent call last typeerror int object is not callable def fx y return x y y rungekuttafehlberg45f 0 0 0 2 1 traceback most recent call last valueerror the final value of x must be greater than initial value of x def fx y return x y rungekuttafehlberg45f 1 0 0 2 0 traceback most recent call last valueerror step size must be positive solve an ordinary differential equations using runge kutta fehlberg method rkf45 of order 5 https en wikipedia org wiki runge e2 80 93kutta e2 80 93fehlberg_method args func an ordinary differential equation ode as function of x and y x_initial the initial value of x y_initial the initial value of y step_size the increment value of x x_final the final value of x returns solution of y at each nodal point exact value of y 1 is tan 0 2 0 2027100937470787 def f x y return 1 y 2 y runge_kutta_fehlberg_45 f 0 0 0 2 1 y 1 0 2027100937470787 def f x y return x y runge_kutta_fehlberg_45 f 1 0 0 2 0 y 1 0 18000000000000002 y runge_kutta_fehlberg_45 5 0 0 0 1 1 traceback most recent call last typeerror int object is not callable def f x y return x y y runge_kutta_fehlberg_45 f 0 0 0 2 1 traceback most recent call last valueerror the final value of x must be greater than initial value of x def f x y return x y runge_kutta_fehlberg_45 f 1 0 0 2 0 traceback most recent call last valueerror step size must be positive
from collections.abc import Callable import numpy as np def runge_kutta_fehlberg_45( func: Callable, x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros( (n + 1), ) x = np.zeros(n + 1) y[0] = y_initial x[0] = x_initial for i in range(n): k1 = step_size * func(x[i], y[i]) k2 = step_size * func(x[i] + step_size / 4, y[i] + k1 / 4) k3 = step_size * func( x[i] + (3 / 8) * step_size, y[i] + (3 / 32) * k1 + (9 / 32) * k2 ) k4 = step_size * func( x[i] + (12 / 13) * step_size, y[i] + (1932 / 2197) * k1 - (7200 / 2197) * k2 + (7296 / 2197) * k3, ) k5 = step_size * func( x[i] + step_size, y[i] + (439 / 216) * k1 - 8 * k2 + (3680 / 513) * k3 - (845 / 4104) * k4, ) k6 = step_size * func( x[i] + step_size / 2, y[i] - (8 / 27) * k1 + 2 * k2 - (3544 / 2565) * k3 + (1859 / 4104) * k4 - (11 / 40) * k5, ) y[i + 1] = ( y[i] + (16 / 135) * k1 + (6656 / 12825) * k3 + (28561 / 56430) * k4 - (9 / 50) * k5 + (2 / 55) * k6 ) x[i + 1] = step_size + x[i] return y if __name__ == "__main__": import doctest doctest.testmod()
use the rungekuttagill s method of order 4 to solve ordinary differential equations https www geeksforgeeks orggills4thordermethodtosolvedifferentialequations ravi kumar solve an ordinary differential equations using rungekuttagills method of order 4 args func an ordinary differential equation ode as function of x and y xinitial the initial value of x yinitial the initial value of y stepsize the increment value of x xfinal the final value of x returns solution of y at each nodal point def fx y return xy2 y rungekuttagillsf 0 3 0 2 5 y1 3 4104259225717537 def fx y return x y rungekuttagillsf 1 0 0 2 0 y array 0 0 18 0 32 0 42 0 48 0 5 def fx y return x y y rungekuttagillsf 0 0 0 2 1 traceback most recent call last valueerror the final value of x must be greater than initial value of x def fx y return x y rungekuttagillsf 1 0 0 2 0 traceback most recent call last valueerror step size must be positive solve an ordinary differential equations using runge kutta gills method of order 4 args func an ordinary differential equation ode as function of x and y x_initial the initial value of x y_initial the initial value of y step_size the increment value of x x_final the final value of x returns solution of y at each nodal point def f x y return x y 2 y runge_kutta_gills f 0 3 0 2 5 y 1 3 4104259225717537 def f x y return x y runge_kutta_gills f 1 0 0 2 0 y array 0 0 18 0 32 0 42 0 48 0 5 def f x y return x y y runge_kutta_gills f 0 0 0 2 1 traceback most recent call last valueerror the final value of x must be greater than initial value of x def f x y return x y runge_kutta_gills f 1 0 0 2 0 traceback most recent call last valueerror step size must be positive
from collections.abc import Callable from math import sqrt import numpy as np def runge_kutta_gills( func: Callable[[float, float], float], x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros(n + 1) y[0] = y_initial for i in range(n): k1 = step_size * func(x_initial, y[i]) k2 = step_size * func(x_initial + step_size / 2, y[i] + k1 / 2) k3 = step_size * func( x_initial + step_size / 2, y[i] + (-0.5 + 1 / sqrt(2)) * k1 + (1 - 1 / sqrt(2)) * k2, ) k4 = step_size * func( x_initial + step_size, y[i] - (1 / sqrt(2)) * k2 + (1 + 1 / sqrt(2)) * k3 ) y[i + 1] = y[i] + (k1 + (2 - sqrt(2)) * k2 + (2 + sqrt(2)) * k3 + k4) / 6 x_initial += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
implementing secant method in python dimgrichr f5 39 98652410600183 secantmethod1 3 2 0 2139409276214589 f 5 39 98652410600183 secant_method 1 3 2 0 2139409276214589
from math import exp def f(x: float) -> float: return 8 * x - 2 * exp(-x) def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float: x0 = lower_bound x1 = upper_bound for _ in range(repeats): x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)) return x1 if __name__ == "__main__": print(f"Example: {secant_method(1, 3, 2)}")
numerical integration or quadrature for a smooth function f with known values at xi this method is the classical approach of summing equally spaced abscissas method 2 simpson rule simpson rule intf deltax2 ba3f1 4f2 2f3 fn calculate the definite integral of a function using simpson s rule param boundary a list containing the lower and upper bounds of integration param steps the number of steps or resolution for the integration return the approximate integral value roundmethod20 2 4 10 10 2 6666666667 roundmethod22 0 10 10 0 2666666667 roundmethod22 1 10 10 2 172 roundmethod20 1 10 10 0 3333333333 roundmethod20 2 10 10 2 6666666667 roundmethod20 2 100 10 2 5621226667 roundmethod20 1 1000 10 0 3320026653 roundmethod20 2 0 10 traceback most recent call last zerodivisionerror number of steps must be greater than zero roundmethod20 2 10 10 traceback most recent call last zerodivisionerror number of steps must be greater than zero simpson rule int f delta_x 2 b a 3 f1 4f2 2f_3 fn calculate the definite integral of a function using simpson s rule param boundary a list containing the lower and upper bounds of integration param steps the number of steps or resolution for the integration return the approximate integral value round method_2 0 2 4 10 10 2 6666666667 round method_2 2 0 10 10 0 2666666667 round method_2 2 1 10 10 2 172 round method_2 0 1 10 10 0 3333333333 round method_2 0 2 10 10 2 6666666667 round method_2 0 2 100 10 2 5621226667 round method_2 0 1 1000 10 0 3320026653 round method_2 0 2 0 10 traceback most recent call last zerodivisionerror number of steps must be greater than zero round method_2 0 2 10 10 traceback most recent call last zerodivisionerror number of steps must be greater than zero enter your function here lower bound of integration upper bound of integration number of steps or resolution boundary of integration
def method_2(boundary: list[int], steps: int) -> float: if steps <= 0: raise ZeroDivisionError("Number of steps must be greater than zero") h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): y = (x - 0) * (x - 0) return y def main(): a = 0.0 b = 1.0 steps = 10.0 boundary = [a, b] y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": import doctest doctest.testmod() main()
square root approximated using newton s method https en wikipedia orgwikinewton27smethod allabssquarerootiterativei math sqrti 1e14 for i in range500 true squarerootiterative1 traceback most recent call last valueerror math domain error squarerootiterative4 2 0 squarerootiterative3 2 1 788854381999832 squarerootiterative140 11 832159566199232 square root approximated using newton s method https en wikipedia org wiki newton 27s_method all abs square_root_iterative i math sqrt i 1e 14 for i in range 500 true square_root_iterative 1 traceback most recent call last valueerror math domain error square_root_iterative 4 2 0 square_root_iterative 3 2 1 788854381999832 square_root_iterative 140 11 832159566199232
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max_iter: int = 9999, tolerance: float = 1e-14 ) -> float: if a < 0: raise ValueError("math domain error") value = get_initial_point(a) for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
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 orgwikisieveoferatosthenes oddsieve2 oddsieve3 2 oddsieve10 2 3 5 7 oddsieve20 2 3 5 7 11 13 17 19 odd sieve for numbers in range 3 num 1 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 odd sieve for numbers in range 3 num 1
from itertools import compress, repeat from math import ceil, sqrt def odd_sieve(num: int) -> list[int]: if num <= 2: return [] if num == 3: return [2] 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()
check if a number is a perfect cube or not perfectcube27 true perfectcube4 false check if a number is a perfect cube or not using binary search time complexity ologn space complexity o1 perfectcubebinarysearch27 true perfectcubebinarysearch64 true perfectcubebinarysearch4 false perfectcubebinarysearcha traceback most recent call last typeerror perfectcubebinarysearch only accepts integers perfectcubebinarysearch0 1 traceback most recent call last typeerror perfectcubebinarysearch only accepts integers check if a number is a perfect cube or not perfect_cube 27 true perfect_cube 4 false 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
def perfect_cube(n: int) -> bool: val = n ** (1 / 3) return (val * val * val) == n def perfect_cube_binary_search(n: int) -> bool: 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()
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 divisors1 2 3 6 excluding 6 the sumdivisors is 1 2 3 6 so 6 is a perfect number other examples of perfect numbers 28 486 https en wikipedia orgwikiperfectnumber 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 perfect27 false perfect28 true perfect29 false perfect6 true perfect12 false perfect496 true perfect8128 true perfect0 false perfect1 false perfect12 34 traceback most recent call last valueerror number must an integer perfecthello traceback most recent call last valueerror number must an integer 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 12 34 traceback most recent call last valueerror number must an integer perfect hello traceback most recent call last valueerror number must an integer
def perfect(number: int) -> bool: if not isinstance(number, int): raise ValueError("number must 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 an integer" print(msg) raise ValueError(msg) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
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 perfectsquare9 true perfectsquare16 true perfectsquare1 true perfectsquare0 true perfectsquare10 false check if a number is perfect square using binary search time complexity ologn space complexity o1 perfectsquarebinarysearch9 true perfectsquarebinarysearch16 true perfectsquarebinarysearch1 true perfectsquarebinarysearch0 true perfectsquarebinarysearch10 false perfectsquarebinarysearch1 false perfectsquarebinarysearch1 1 false perfectsquarebinarysearcha traceback most recent call last typeerror not supported between instances of int and str perfectsquarebinarysearchnone traceback most recent call last typeerror not supported between instances of int and nonetype perfectsquarebinarysearch traceback most recent call last typeerror not supported between instances of int and list 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 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
import math def perfect_square(num: int) -> bool: return math.sqrt(num) * math.sqrt(num) == num def perfect_square_binary_search(n: int) -> bool: left = 0 right = n while left <= right: mid = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: right = mid - 1 else: left = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
return the persistence of a given number https en wikipedia orgwikipersistenceofanumber multiplicativepersistence217 2 multiplicativepersistence1 traceback most recent call last valueerror multiplicativepersistence does not accept negative values multiplicativepersistencelong number traceback most recent call last valueerror multiplicativepersistence only accepts integral values return the persistence of a given number https en wikipedia orgwikipersistenceofanumber additivepersistence199 3 additivepersistence1 traceback most recent call last valueerror additivepersistence does not accept negative values additivepersistencelong number traceback most recent call last valueerror additivepersistence only accepts integral values 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 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
def multiplicative_persistence(num: int) -> int: 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: 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()
https en wikipedia orgwikileibnizformulaforcf80 leibniz formula for pi the leibniz formula is the special case arctan1 pi 4 leibniz s formula converges extremely slowly it exhibits sublinear convergence convergence https en wikipedia orgwikileibnizformulaforcf80convergence we cannot try to prove against an interrupted uncompleted generation https en wikipedia orgwikileibnizformulaforcf80unusualbehaviour the errors can in fact be predicted but those calculations also approach infinity for accuracy our output will be a string so that we can definitely store all digits import math floatcalculatepi15 math pi true since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity or interrupt any alternating series we ll need math isclose math isclosefloatcalculatepi50 math pi true math isclosefloatcalculatepi100 math pi true since math pi contains only 16 digits here are some tests with known values calculatepi50 3 14159265358979323846264338327950288419716939937510 calculatepi80 3 14159265358979323846264338327950288419716939937510582097494459230781640628620899 variables used for the iteration process we can t compare against anything if we make a generator so we ll stick with plain return logic https en wikipedia org wiki leibniz_formula_for_ cf 80 leibniz formula for pi the leibniz formula is the special case arctan 1 pi 4 leibniz s formula converges extremely slowly it exhibits sublinear convergence convergence https en wikipedia org wiki leibniz_formula_for_ cf 80 convergence we cannot try to prove against an interrupted uncompleted generation https en wikipedia org wiki leibniz_formula_for_ cf 80 unusual_behaviour the errors can in fact be predicted but those calculations also approach infinity for accuracy our output will be a string so that we can definitely store all digits import math float calculate_pi 15 math pi true since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity or interrupt any alternating series we ll need math isclose math isclose float calculate_pi 50 math pi true math isclose float calculate_pi 100 math pi true since math pi contains only 16 digits here are some tests with known values calculate_pi 50 3 14159265358979323846264338327950288419716939937510 calculate_pi 80 3 14159265358979323846264338327950288419716939937510582097494459230781640628620899 variables used for the iteration process we can t compare against anything if we make a generator so we ll stick with plain return logic
def calculate_pi(limit: int) -> str: q = 1 r = 0 t = 1 k = 1 n = 3 l = 3 decimal = limit counter = 0 result = "" while counter != decimal + 1: if 4 * q + r - t < n * t: result += str(n) if counter == 0: result += "." if decimal == counter: break counter += 1 nr = 10 * (r - n * t) n = ((10 * (3 * q + r)) // t) - 10 * n q *= 10 r = nr else: nr = (2 * q + r) * l nn = (q * (7 * k) + 2 + (r * l)) // (t * l) q *= k t *= l l += 2 k += 1 n = nn r = nr return result def main() -> None: print(f"{calculate_pi(50) = }") import doctest doctest.testmod() if __name__ == "__main__": main()
true if the point lies in the unit circle false otherwise generates a point randomly drawn from the unit square 0 1 x 0 1 generates an estimate of the mathematical constant pi see https en wikipedia orgwikimontecarlomethodoverview 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 pu in unit circle 14 pi and therefore pi 4 pu in unit circle we can get an estimate of the probability pu in unit circle see https en wikipedia orgwikiempiricalprobability 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 pu in unit circle is mn import doctest doctest testmod true if the point lies in the unit circle false otherwise generates a point randomly drawn from the unit square 0 1 x 0 1 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 import doctest doctest testmod
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 for _ in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): number_in_unit_circle += 1 return 4 * number_in_unit_circle / number_of_simulations if __name__ == "__main__": 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)}")
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 crossproduct 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 coma1951650 pass two points to get the vector from them in the form x y z createvector0 0 0 1 1 1 1 1 1 createvector45 70 24 47 32 1 2 38 23 createvector14 1 8 7 6 4 7 7 12 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 orgwikicrossproduct https en wikipedia orgwikideterminant get3dvectorscross3 4 7 4 9 2 55 22 11 get3dvectorscross1 1 1 1 1 1 0 0 0 get3dvectorscross4 3 0 3 9 12 36 48 27 get3dvectorscross17 67 4 7 6 78 9 5 4 78 19 33 123 2594 277 15110000000004 129 11260000000001 check if vector is equal to 0 0 0 of not sine 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 iszerovector0 0 0 accuracy10 true iszerovector15 74 32 accuracy10 false iszerovector15 74 32 accuracy10 false check if three points are collinear or not 1 create tow vectors ab and ac 2 get the cross vector of the tow vectors 3 calcolate 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 iszerovector docstring arecollinear4 802293498137402 3 536233125455244 0 2 186788107953106 9 24561398001649 7 141509524846482 1 530169574640268 2 447927606600034 3 343487096469054 true arecollinear6 2 6 6 200213806439997 4 930157614926678 4 482371908289856 4 085171149525941 2 459889509029438 4 354787180795383 true arecollinear2 399001826862445 2 452009976680793 4 464656666157666 3 682816335934376 5 753788986533145 9 490993909044244 1 962903518985307 3 741415730125627 7 false arecollinear1 875375340689544 7 268426006071538 7 358196269835993 3 546599383667157 4 630005261513976 3 208784032924246 2 564606140206386 3 937845170672183 7 false 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 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 i j k check if vector is equal to 0 0 0 of not sine 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 check if three points are collinear or not 1 create tow vectors ab and ac 2 get the cross vector of the tow vectors 3 calcolate 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
Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: x = end_point2[0] - end_point1[0] y = end_point2[1] - end_point1[1] z = end_point2[2] - end_point1[2] return (x, y, z) def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d: x = ab[1] * ac[2] - ab[2] * ac[1] y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 z = ab[0] * ac[1] - ab[1] * ac[0] return (x, y, z) def is_zero_vector(vector: Vector3d, accuracy: int) -> bool: return tuple(round(x, accuracy) for x in vector) == (0, 0, 0) def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool: ab = create_vector(a, b) ac = create_vector(a, c) return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
use pollard s rho algorithm to return a nontrivial factor of num the returned factor may be composite and require further factorization if the algorithm will return none if it fails to find a factor within the specified number of attempts or within the specified number of steps if num is prime this algorithm is guaranteed to return none https en wikipedia orgwikipollard27srhoalgorithm pollardrho18446744073709551617 274177 pollardrho97546105601219326301 9876543191 pollardrho100 2 pollardrho17 pollardrho173 17 pollardrho173 attempts1 pollardrho357 21 pollardrho1 traceback most recent call last valueerror the input value cannot be less than 2 a value less than 2 can cause an infinite loop in the algorithm because of the relationship between ffx and fx this algorithm struggles to find factors that are divisible by two as a workaround we specifically check for two and even inputs see https math stackexchange coma2856214165820 pollard s rho algorithm requires a function that returns pseudorandom values between 0 x num it doesn t need to be random in the sense that the output value is cryptographically secure or difficult to calculate it only needs to be random in the sense that all output values should be equally likely to appear for this reason pollard suggested using fx x2 1 num however the success of pollard s algorithm isn t guaranteed and is determined in part by the initial seed and the chosen random function to make retries easier we will instead use fx x2 c num where c is a value that we can modify between each attempt returns a pseudorandom value modulo modulus based on the input value and attemptspecific step size randfn0 0 0 traceback most recent call last zerodivisionerror integer division or modulo by zero randfn1 2 3 0 randfn0 10 7 3 randfn1234 1 17 16 these track the position within the cycle detection logic at each iteration the tortoise moves one step and the hare moves two at some point both the tortoise and the hare will enter a cycle whose length p is a divisor of num once in that cycle at some point the tortoise and hare will end up on the same value modulo p we can detect when this happens because the position difference between the tortoise and the hare will share a common divisor with num no common divisor yet just keep searching we found a common divisor unfortunately the divisor is num itself and is useless the divisor is a nontrivial factor of num if we made it here then this attempt failed we need to pick a new starting seed for the tortoise and hare in addition to a new step value for the random function to keep this example implementation deterministic the new values will be generated based on currently available values instead of using something like random randint we can use the hare s position as the new seed this is actually what richard brent s the optimized variant does the new step value for the random function can just be incremented at first the results will be similar to what the old function would have produced but the value will quickly diverge after a bit we haven t found a divisor within the requested number of attempts we were unlucky or num itself is actually prime use pollard s rho algorithm to return a nontrivial factor of num the returned factor may be composite and require further factorization if the algorithm will return none if it fails to find a factor within the specified number of attempts or within the specified number of steps if num is prime this algorithm is guaranteed to return none https en wikipedia org wiki pollard 27s_rho_algorithm pollard_rho 18446744073709551617 274177 pollard_rho 97546105601219326301 9876543191 pollard_rho 100 2 pollard_rho 17 pollard_rho 17 3 17 pollard_rho 17 3 attempts 1 pollard_rho 3 5 7 21 pollard_rho 1 traceback most recent call last valueerror the input value cannot be less than 2 a value less than 2 can cause an infinite loop in the algorithm because of the relationship between f f x and f x this algorithm struggles to find factors that are divisible by two as a workaround we specifically check for two and even inputs see https math stackexchange com a 2856214 165820 pollard s rho algorithm requires a function that returns pseudorandom values between 0 x num it doesn t need to be random in the sense that the output value is cryptographically secure or difficult to calculate it only needs to be random in the sense that all output values should be equally likely to appear for this reason pollard suggested using f x x 2 1 num however the success of pollard s algorithm isn t guaranteed and is determined in part by the initial seed and the chosen random function to make retries easier we will instead use f x x 2 c num where c is a value that we can modify between each attempt returns a pseudorandom value modulo modulus based on the input value and attempt specific step size rand_fn 0 0 0 traceback most recent call last zerodivisionerror integer division or modulo by zero rand_fn 1 2 3 0 rand_fn 0 10 7 3 rand_fn 1234 1 17 16 these track the position within the cycle detection logic at each iteration the tortoise moves one step and the hare moves two at some point both the tortoise and the hare will enter a cycle whose length p is a divisor of num once in that cycle at some point the tortoise and hare will end up on the same value modulo p we can detect when this happens because the position difference between the tortoise and the hare will share a common divisor with num no common divisor yet just keep searching we found a common divisor unfortunately the divisor is num itself and is useless the divisor is a nontrivial factor of num if we made it here then this attempt failed we need to pick a new starting seed for the tortoise and hare in addition to a new step value for the random function to keep this example implementation deterministic the new values will be generated based on currently available values instead of using something like random randint we can use the hare s position as the new seed this is actually what richard brent s the optimized variant does the new step value for the random function can just be incremented at first the results will be similar to what the old function would have produced but the value will quickly diverge after a bit we haven t found a divisor within the requested number of attempts we were unlucky or num itself is actually prime
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: if num < 2: raise ValueError("The input value cannot be less than 2") if num > 2 and num % 2 == 0: return 2 def rand_fn(value: int, step: int, modulus: int) -> int: return (pow(value, 2) + step) % modulus for _ in range(attempts): tortoise = seed hare = seed while True: tortoise = rand_fn(tortoise, step, num) hare = rand_fn(hare, step, num) hare = rand_fn(hare, step, num) divisor = gcd(hare - tortoise, num) if divisor == 1: continue else: if divisor == num: break else: return divisor seed = hare step += 1 return None if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) args = parser.parse_args() divisor = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"{args.num} is probably prime") else: quotient = args.num // divisor print(f"{args.num} = {divisor} * {quotient}")
evaluate a polynomial fx 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 evaluatepoly0 0 0 0 5 0 9 3 7 0 10 0 79800 0 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 on where n is the degree of the polynomial https en wikipedia orgwikihorner smethod arguments poly the coefficients of a polynomial as an iterable in order of ascending degree x the point at which to evaluate the polynomial horner0 0 0 0 5 0 9 3 7 0 10 0 79800 0 example poly 0 0 0 0 5 0 9 3 7 0 fx 7 0x4 9 3x3 5 0x2 x 13 0 f13 7 0134 9 3133 5 0132 180339 9 evaluatepolypoly x 180339 9 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 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 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
from collections.abc import Sequence def evaluate_poly(poly: Sequence[float], x: float) -> float: return sum(c * (x**i) for i, c in enumerate(poly)) def horner(poly: Sequence[float], x: float) -> float: result = 0.0 for coeff in reversed(poly): result = result * x + coeff return result if __name__ == "__main__": poly = (0.0, 0.0, 5.0, 9.3, 7.0) x = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
this module implements a single indeterminate polynomials class with some basic operations reference https en wikipedia orgwikipolynomial the coefficients should be in order of degree from smallest to largest p polynomial2 1 2 3 p polynomial2 1 2 3 4 traceback most recent call last valueerror the number of coefficients should be equal to the degree 1 polynomial addition p polynomial2 1 2 3 q polynomial2 1 2 3 p q 6x2 4x 2 polynomial subtraction p polynomial2 1 2 4 q polynomial2 1 2 3 p q 1x2 polynomial negation p polynomial2 1 2 3 p 3x2 2x 1 polynomial multiplication p polynomial2 1 2 3 q polynomial2 1 2 3 p q 9x4 12x3 10x2 4x 1 evaluates the polynomial at x p polynomial2 1 2 3 p evaluate2 17 p polynomial2 1 2 3 printp 3x2 2x 1 p polynomial2 1 2 3 p 3x2 2x 1 returns the derivative of the polynomial p polynomial2 1 2 3 p derivative 6x 2 returns the integral of the polynomial p polynomial2 1 2 3 p integral 1 0x3 1 0x2 1 0x checks if two polynomials are equal p polynomial2 1 2 3 q polynomial2 1 2 3 p q true checks if two polynomials are not equal p polynomial2 1 2 3 q polynomial2 1 2 3 p q false the coefficients should be in order of degree from smallest to largest p polynomial 2 1 2 3 p polynomial 2 1 2 3 4 traceback most recent call last valueerror the number of coefficients should be equal to the degree 1 polynomial addition p polynomial 2 1 2 3 q polynomial 2 1 2 3 p q 6x 2 4x 2 polynomial subtraction p polynomial 2 1 2 4 q polynomial 2 1 2 3 p q 1x 2 polynomial negation p polynomial 2 1 2 3 p 3x 2 2x 1 polynomial multiplication p polynomial 2 1 2 3 q polynomial 2 1 2 3 p q 9x 4 12x 3 10x 2 4x 1 evaluates the polynomial at x p polynomial 2 1 2 3 p evaluate 2 17 p polynomial 2 1 2 3 print p 3x 2 2x 1 p polynomial 2 1 2 3 p 3x 2 2x 1 returns the derivative of the polynomial p polynomial 2 1 2 3 p derivative 6x 2 returns the integral of the polynomial p polynomial 2 1 2 3 p integral 1 0x 3 1 0x 2 1 0x checks if two polynomials are equal p polynomial 2 1 2 3 q polynomial 2 1 2 3 p q true checks if two polynomials are not equal p polynomial 2 1 2 3 q polynomial 2 1 2 3 p q false
from __future__ import annotations from collections.abc import MutableSequence class Polynomial: def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None: if len(coefficients) != degree + 1: raise ValueError( "The number of coefficients should be equal to the degree + 1." ) self.coefficients: list[float] = list(coefficients) self.degree = degree def __add__(self, polynomial_2: Polynomial) -> Polynomial: if self.degree > polynomial_2.degree: coefficients = self.coefficients[:] for i in range(polynomial_2.degree + 1): coefficients[i] += polynomial_2.coefficients[i] return Polynomial(self.degree, coefficients) else: coefficients = polynomial_2.coefficients[:] for i in range(self.degree + 1): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_2.degree, coefficients) def __sub__(self, polynomial_2: Polynomial) -> Polynomial: return self + polynomial_2 * Polynomial(0, [-1]) def __neg__(self) -> Polynomial: return Polynomial(self.degree, [-c for c in self.coefficients]) def __mul__(self, polynomial_2: Polynomial) -> Polynomial: coefficients: list[float] = [0] * (self.degree + polynomial_2.degree + 1) for i in range(self.degree + 1): for j in range(polynomial_2.degree + 1): coefficients[i + j] += ( self.coefficients[i] * polynomial_2.coefficients[j] ) return Polynomial(self.degree + polynomial_2.degree, coefficients) def evaluate(self, substitution: float) -> float: result: int | float = 0 for i in range(self.degree + 1): result += self.coefficients[i] * (substitution**i) return result def __str__(self) -> str: polynomial = "" for i in range(self.degree, -1, -1): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i])) elif i == 1: polynomial += str(abs(self.coefficients[i])) + "x" else: polynomial += str(abs(self.coefficients[i])) + "x^" + str(i) return polynomial def __repr__(self) -> str: return self.__str__() def derivative(self) -> Polynomial: coefficients: list[float] = [0] * self.degree for i in range(self.degree): coefficients[i] = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1, coefficients) def integral(self, constant: float = 0) -> Polynomial: coefficients: list[float] = [0] * (self.degree + 2) coefficients[0] = constant for i in range(self.degree + 1): coefficients[i + 1] = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1, coefficients) def __eq__(self, polynomial_2: object) -> bool: if not isinstance(polynomial_2, Polynomial): return False if self.degree != polynomial_2.degree: return False for i in range(self.degree + 1): if self.coefficients[i] != polynomial_2.coefficients[i]: return False return True def __ne__(self, polynomial_2: object) -> bool: return not self.__eq__(polynomial_2)
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 calculate the power of a base raised to an exponent power3 4 81 power2 0 1 allpowerbase exponent powbase exponent for base in range10 10 for exponent in range10 true power a 1 a power a 2 traceback most recent call last typeerror can t multiply sequence by nonint of type str power a b traceback most recent call last typeerror unsupported operand types for str and int power2 1 traceback most recent call last recursionerror maximum recursion depth exceeded 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 does not properly deal w negative exponents
def power(base: int, exponent: int) -> float: 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: result = 1 / result print(f"{base} to the power of {exponent} is {result}")
prime check import math import unittest import pytest def isprimenumber int bool precondition if not isinstancenumber int or not number 0 raise valueerrorisprime 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 range5 intmath sqrtnumber 1 6 if number i 0 or number i 2 0 return false return true class testunittest testcase def testprimesself assert isprime2 assert isprime3 assert isprime5 assert isprime7 assert isprime11 assert isprime13 assert isprime17 assert isprime19 assert isprime23 assert isprime29 def testnotprimesself with pytest raisesvalueerror isprime19 assert not isprime 0 zero doesn t have any positive factors primes must have exactly two assert not isprime 1 one only has 1 positive factor primes must have exactly two assert not isprime2 2 assert not isprime2 3 assert not isprime3 3 assert not isprime3 5 assert not isprime3 5 7 if name main unittest main 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 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1
import math import unittest import pytest def is_prime(number: int) -> bool: if not isinstance(number, int) or not number >= 0: raise ValueError("is_prime() only accepts positive integers") if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False 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()
pythonblack true returns prime factors of n as a list primefactors0 primefactors100 2 2 5 5 primefactors2560 2 2 2 2 2 2 2 2 2 5 primefactors102 primefactors0 02 x primefactors10241 doctest normalizewhitespace x 2241 5241 true primefactors10354 primefactors hello traceback most recent call last typeerror not supported between instances of int and str primefactors1 2 hello traceback most recent call last typeerror not supported between instances of int and list 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
from __future__ import annotations def prime_factors(n: int) -> list[int]: i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
return a list of all primes numbers up to max listslowprimes0 listslowprimes1 listslowprimes10 listslowprimes25 2 3 5 7 11 13 17 19 23 listslowprimes11 2 3 5 7 11 listslowprimes33 2 3 5 7 11 13 17 19 23 29 31 listslowprimes10001 997 return a list of all primes numbers up to max listprimes0 listprimes1 listprimes10 listprimes25 2 3 5 7 11 13 17 19 23 listprimes11 2 3 5 7 11 listprimes33 2 3 5 7 11 13 17 19 23 29 31 listprimes10001 997 only need to check for factors up to sqrti return a list of all primes numbers up to max listfastprimes0 listfastprimes1 listfastprimes10 listfastprimes25 2 3 5 7 11 13 17 19 23 listfastprimes11 2 3 5 7 11 listfastprimes33 2 3 5 7 11 13 17 19 23 29 31 listfastprimes10001 997 it s useless to test even numbers as they will not be prime as we removed the even numbers we don t need them now let s benchmark our functions sidebyside 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 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 only need to check for factors up to sqrt i 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 it s useless to test even numbers as they will not be prime because 2 will not be tested it s necessary to yield it now as we removed the even numbers we don t need them now let s benchmark our functions side by side
import math from collections.abc import Generator def slow_primes(max_n: int) -> Generator[int, None, None]: 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, None, None]: numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): 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, None, None]: numbers: Generator = (i for i in range(1, (max_n + 1), 2)) if max_n > 2: yield 2 for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 for j in range(3, bound, 2): if (i % j) == 0: break else: yield i def benchmark(): from timeit import timeit setup = "from __main__ import slow_primes, primes, fast_primes" print(timeit("slow_primes(1_000_000_000_000)", setup=setup, number=1_000_000)) print(timeit("primes(1_000_000_000_000)", setup=setup, number=1_000_000)) print(timeit("fast_primes(1_000_000_000_000)", setup=setup, number=1_000_000)) if __name__ == "__main__": number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) benchmark()
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 orgwikisieveoferatosthenes print the prime numbers up to n primesieveeratosthenes10 2 3 5 7 primesieveeratosthenes20 2 3 5 7 11 13 17 19 primesieveeratosthenes2 2 primesieveeratosthenes1 primesieveeratosthenes1 traceback most recent call last valueerror input must be a positive integer 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
def prime_sieve_eratosthenes(num: int) -> list[int]: if num <= 0: raise ValueError("Input must be a positive integer") primes = [True] * (num + 1) p = 2 while p * p <= num: if primes[p]: for i in range(p * p, num + 1, p): primes[i] = False p += 1 return [prime for prime in range(2, num + 1) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() user_num = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
created on thu oct 5 16 44 23 2017 christian bender this python library contains some useful functions to deal with prime numbers and whole numbers overview isprimenumber sieveern getprimenumbersn primefactorizationnumber greatestprimefactornumber smallestprimefactornumber getprimen getprimesbetweenpnumber1 pnumber2 isevennumber isoddnumber kgvnumber1 number2 least common multiple getdivisorsnumber all divisors of number inclusive 1 number isperfectnumbernumber newfunctions simplifyfractionnumerator denominator factorial n n fib n calculate the nth fibonacci term goldbachnumber goldbach s assumption input positive integer number returns true if number is prime otherwise false isprime3 true isprime10 false isprime97 true isprime9991 false isprime1 traceback most recent call last assertionerror number must been an int and positive isprimetest traceback most recent call last assertionerror number must been an int and positive precondition 0 and 1 are none primes if number divisible by divisor then sets status of false and break up the loop precondition 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 sieveer8 2 3 5 7 sieveer1 traceback most recent call last assertionerror n must been an int and 2 sieveertest traceback most recent call last assertionerror n must been an int and 2 precondition beginlist contains all natural numbers from 2 up to n actual sieve of erathostenes filters actual prime numbers precondition 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 getprimenumbers8 2 3 5 7 getprimenumbers1 traceback most recent call last assertionerror n must been an int and 2 getprimenumberstest traceback most recent call last assertionerror n must been an int and 2 precondition iterates over all numbers between 2 up to n1 if a number is prime then appends to list ans precondition input positive integer number returns a list of the prime number factors of number primefactorization0 0 primefactorization8 2 2 2 primefactorization287 7 41 primefactorization1 traceback most recent call last assertionerror number must been an int and 0 primefactorizationtest traceback most recent call last assertionerror number must been an int and 0 precondition potential prime number factors if number not prime then builds the prime factorization of number precondition input positive integer number 0 returns the greatest prime number factor of number greatestprimefactor0 0 greatestprimefactor8 2 greatestprimefactor287 41 greatestprimefactor1 traceback most recent call last assertionerror number must been an int and 0 greatestprimefactortest traceback most recent call last assertionerror number must been an int and 0 precondition prime factorization of number precondition input integer number 0 returns the smallest prime number factor of number smallestprimefactor0 0 smallestprimefactor8 2 smallestprimefactor287 7 smallestprimefactor1 traceback most recent call last assertionerror number must been an int and 0 smallestprimefactortest traceback most recent call last assertionerror number must been an int and 0 precondition prime factorization of number precondition input integer number returns true if number is even otherwise false iseven0 true iseven8 true iseven287 false iseven1 false iseventest traceback most recent call last assertionerror number must been an int precondition input integer number returns true if number is odd otherwise false isodd0 false isodd8 false isodd287 true isodd1 true isoddtest traceback most recent call last assertionerror number must been an int precondition goldbach s assumption input a even positive integer number 2 returns a list of two prime numbers whose sum is equal to number goldbach8 3 5 goldbach824 3 821 goldbach0 traceback most recent call last assertionerror number must been an int even and 2 goldbach1 traceback most recent call last assertionerror number must been an int even and 2 goldbachtest traceback most recent call last assertionerror number must been an int even and 2 precondition creates a list of prime numbers between 2 up to number run variable for whileloops exit variable for break up the loops precondition least common multiple input two positive integer number1 and number2 returns the least common multiple of number1 and number2 kgv8 10 40 kgv824 67 55208 kgv1 10 10 kgv0 traceback most recent call last typeerror kgv missing 1 required positional argument number2 kgv10 1 traceback most recent call last assertionerror number1 and number2 must been positive integer kgvtest test2 traceback most recent call last assertionerror number1 and number2 must been positive integer precondition for kgv x 1 builds the prime factorization of number1 and number2 iterates through primefac1 iterates through primefac2 precondition gets the nth prime number input positive integer n 0 returns the nth prime number beginning at index 0 getprime0 2 getprime8 23 getprime824 6337 getprime1 traceback most recent call last assertionerror number must been a positive int getprimetest traceback most recent call last assertionerror number must been a positive int precondition if ans not prime then runs to the next prime number precondition input prime numbers pnumber1 and pnumber2 pnumber1 pnumber2 returns a list of all prime numbers between pnumber1 exclusive and pnumber2 exclusive getprimesbetween3 67 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 getprimesbetween0 traceback most recent call last typeerror getprimesbetween missing 1 required positional argument pnumber2 getprimesbetween0 1 traceback most recent call last assertionerror the arguments must been prime numbers and pnumber1 pnumber2 getprimesbetween1 3 traceback most recent call last assertionerror number must been an int and positive getprimesbetweentest test traceback most recent call last assertionerror number must been an int and positive precondition if number is not prime then fetch the next prime number fetch the next prime number precondition ans contains not pnumber1 and pnumber2 input positive integer n 1 returns all divisors of n inclusive 1 and n getdivisors8 1 2 4 8 getdivisors824 1 2 4 8 103 206 412 824 getdivisors1 traceback most recent call last assertionerror n must been int and 1 getdivisorstest traceback most recent call last assertionerror n must been int and 1 precondition precondition input positive integer number 1 returns true if number is a perfect number otherwise false isperfectnumber28 true isperfectnumber824 false isperfectnumber1 traceback most recent call last assertionerror number must been an int and 1 isperfectnumbertest traceback most recent call last assertionerror number must been an int and 1 precondition precondition summed all divisors up to number exclusive hence 1 input two integer numerator and denominator assumes denominator 0 returns a tuple with simplify numerator and denominator simplifyfraction10 20 1 2 simplifyfraction10 1 10 1 simplifyfractiontest test traceback most recent call last assertionerror the arguments must been from type int and denominator 0 precondition build the greatest common divisor of numerator and denominator precondition input positive integer n returns the factorial of n n factorial0 1 factorial20 2432902008176640000 factorial1 traceback most recent call last assertionerror n must been a int and 0 factorialtest traceback most recent call last assertionerror n must been a int and 0 precondition input positive integer n returns the nth fibonacci term indexing by 0 fib0 1 fib5 8 fib20 10946 fib99 354224848179261915075 fib1 traceback most recent call last assertionerror n must been an int and 0 fibtest traceback most recent call last assertionerror n must been an int and 0 precondition 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 0 and 1 are none primes if number divisible by divisor then sets status of false and break up the loop precondition 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 beginlist contains all natural numbers from 2 up to n this list will be returns actual sieve of erathostenes filters actual prime numbers precondition 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 iterates over all numbers between 2 up to n 1 if a number is prime then appends to list ans precondition 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 this list will be returns of the function potential prime number factors if number not prime then builds the prime factorization of number precondition 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 prime factorization of number precondition 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 prime factorization of number precondition 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 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 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 this list will returned creates a list of prime numbers between 2 up to number run variable for while loops exit variable for break up the loops precondition 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 actual answer that will be return for kgv x 1 builds the prime factorization of number1 and number2 captured numbers int both primefac1 and primefac2 iterates through primefac1 iterates through primefac2 precondition 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 this variable holds the answer counts to the next number if ans not prime then runs to the next prime number precondition 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 jump to the next number this list will be returns if number is not prime then fetch the next prime number fetch the next prime number precondition ans contains not pnumber1 and pnumber2 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 will be returned precondition 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 precondition summed all divisors up to number exclusive hence 1 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 build the greatest common divisor of numerator and denominator precondition 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 this will be return 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 this will be return
from math import sqrt from maths.greatest_common_divisor import gcd_by_iterative def is_prime(number: int) -> bool: assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" status = True if number <= 1: status = False for divisor in range(2, int(round(sqrt(number))) + 1): if number % divisor == 0: status = False break assert isinstance(status, bool), "'status' must been from type bool" return status def sieve_er(n): assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" begin_list = list(range(2, n + 1)) ans = [] 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 ans = [x for x in begin_list if x != 0] assert isinstance(ans, list), "'ans' must been from type list" return ans def get_prime_numbers(n): assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" ans = [] for number in range(2, n + 1): if is_prime(number): ans.append(number) assert isinstance(ans, list), "'ans' must been from type list" return ans def prime_factorization(number): assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] factor = 2 quotient = number if number in {0, 1}: ans.append(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) assert isinstance(ans, list), "'ans' must been from type list" return ans def greatest_prime_factor(number): assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and >= 0" ans = 0 prime_factors = prime_factorization(number) ans = max(prime_factors) assert isinstance(ans, int), "'ans' must been from type int" return ans def smallest_prime_factor(number): assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and >= 0" ans = 0 prime_factors = prime_factorization(number) ans = min(prime_factors) assert isinstance(ans, int), "'ans' must been from type int" return ans def is_even(number): 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): 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): assert ( isinstance(number, int) and (number > 2) and is_even(number) ), "'number' must been an int, even and > 2" ans = [] prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) i = 0 j = None 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 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): assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 if number1 > 1 and number2 > 1: 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 = [] 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) 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) assert isinstance(ans, int) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def get_prime(n): assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 while index < n: index += 1 ans += 1 while not is_prime(ans): ans += 1 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): 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 ans = [] while not is_prime(number): number += 1 while number < p_number_2: ans.append(number) number += 1 while not is_prime(number): number += 1 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" return ans def get_divisors(n): assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans def is_perfect_number(number): assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = get_divisors(number) assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" return sum(divisors[:-1]) == number def simplify_fraction(numerator, denominator): assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" gcd_of_fraction = gcd_by_iterative(abs(numerator), abs(denominator)) 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): assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 for factor in range(1, n + 1): ans *= factor return ans def fib(n: int) -> int: assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 for _ in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans if __name__ == "__main__": import doctest doctest.testmod()
prints the multiplication table of a given number till the given number of terms printmultiplicationtable3 5 3 1 3 3 2 6 3 3 9 3 4 12 3 5 15 printmultiplicationtable4 6 4 1 4 4 2 8 4 3 12 4 4 16 4 5 20 4 6 24 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
def multiplication_table(number: int, number_of_terms: int) -> str: 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))
uses pythagoras theorem to calculate the distance between two points in space import math class point def initself x y z self x x self y y self z z def reprself str return fpointself x self y self z def distancea point b point float return math sqrtabsb x a x 2 b y a y 2 b z a z 2 if name main import doctest doctest testmod 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
import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) if __name__ == "__main__": import doctest doctest.testmod()
return a qrdecomposition of the matrix a using householder reflection the qrdecomposition 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 on3 https en wikipedia orgwikiqrdecompositionusinghouseholderreflections 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 array12 51 4 6 167 68 4 24 41 dtypefloat q r qrhouseholdera check that the decomposition is correct np allcloseqr a true check that q is orthogonal np allcloseqq t np eyea shape0 true np allcloseq tq np eyea shape0 true check that r is upper triangular np allclosenp triur r true select a column of modified matrix a construct first basis vector determine scaling factor construct vector v for householder reflection construct the householder matrix pad with ones and zeros as necessary 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 select a column of modified matrix a construct first basis vector determine scaling factor construct vector v for householder reflection construct the householder matrix pad with ones and zeros as necessary
import numpy as np def qr_householder(a: np.ndarray): m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): x = r[k:, [k]] e1 = np.zeros_like(x) e1[0] = 1.0 alpha = np.linalg.norm(x) v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) q_k = np.eye(m - k) - 2.0 * v @ v.T 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()
given the numerical coefficients a b and c calculates the roots for any quadratic equation of the form ax2 bx c quadraticrootsa1 b3 c4 1 0 4 0 quadraticroots5 6 1 0 2 1 0 quadraticroots1 6 25 34j 34j given the numerical coefficients a b and c calculates the roots for any quadratic equation of the form ax 2 bx c quadratic_roots a 1 b 3 c 4 1 0 4 0 quadratic_roots 5 6 1 0 2 1 0 quadratic_roots 1 6 25 3 4j 3 4j
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
converts the given angle from degrees to radians https en wikipedia orgwikiradian radians180 3 141592653589793 radians92 1 6057029118347832 radians274 4 782202150464463 radians109 82 1 9167205845401725 from math import radians as mathradians allabsradiansi mathradiansi 1e8 for i in range2 361 true converts the given angle from degrees to radians https en wikipedia org wiki radian radians 180 3 141592653589793 radians 92 1 6057029118347832 radians 274 4 782202150464463 radians 109 82 1 9167205845401725 from math import radians as math_radians all abs radians i math_radians i 1e 8 for i in range 2 361 true
from math import pi def radians(degree: float) -> float: return degree / (180 / pi) if __name__ == "__main__": from doctest import testmod testmod()
fast polynomial multiplication using radix2 fast fourier transform fast polynomial multiplication using radix2 fast fourier transform reference https en wikipedia orgwikicooleye28093tukeyfftalgorithmtheradix2ditcase for polynomials of degree m and n the algorithms has complexity onlogn mlogm the main part of the algorithm is split in two parts 1 dft we compute the discrete fourier transform dft of a and b using a bottomup dynamic approach 2 multiply once we obtain the dft of ab we can similarly invert it to obtain ab the class fft takes two polynomials a and b with complex coefficients as arguments the two polynomials should be represented as a sequence of coefficients starting from the free term thus for instance x 2x3 could be represented as 0 1 0 2 or 0 1 0 2 the constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product example create two polynomials as sequences a 0 1 0 2 x2x3 b 2 3 4 0 23x4x2 create an fft object with them x ffta b print product x product 2x 3x2 8x3 4x4 6x5 00j 20j 30j 80j 60j 80j str test printx a 0x0 1x1 2x0 3x2 b 0x2 1x3 2x4 ab 0x00j 1x20j 2x30j 3x80j 4x60j 5x80j input as list remove leading zero coefficients add 0 to make lengths equal a power of 2 a complex root used for the fourier transform the product discrete fourier transform of a and b corner case first half of next step second half of next step update multiply the dfts of a and b and find ab corner case inverse dft first half of next step even positions odd positions update unpack remove leading 0 s overwrite str for print shows a b and ab unit tests for roots of unity fast polynomial multiplication using radix 2 fast fourier transform reference https en wikipedia org wiki cooley e2 80 93tukey_fft_algorithm the_radix 2_dit_case for polynomials of degree m and n the algorithms has complexity o n logn m logm the main part of the algorithm is split in two parts 1 __dft we compute the discrete fourier transform dft of a and b using a bottom up dynamic approach 2 __multiply once we obtain the dft of a b we can similarly invert it to obtain a b the class fft takes two polynomials a and b with complex coefficients as arguments the two polynomials should be represented as a sequence of coefficients starting from the free term thus for instance x 2 x 3 could be represented as 0 1 0 2 or 0 1 0 2 the constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product example create two polynomials as sequences a 0 1 0 2 x 2x 3 b 2 3 4 0 2 3x 4x 2 create an fft object with them x fft a b print product x product 2x 3x 2 8x 3 4x 4 6x 5 0 0j 2 0j 3 0j 8 0j 6 0j 8 0j __str__ test print x a 0 x 0 1 x 1 2 x 0 3 x 2 b 0 x 2 1 x 3 2 x 4 a b 0 x 0 0j 1 x 2 0j 2 x 3 0j 3 x 8 0j 4 x 6 0j 5 x 8 0j input as list remove leading zero coefficients add 0 to make lengths equal a power of 2 a complex root used for the fourier transform the product discrete fourier transform of a and b corner case first half of next step second half of next step update multiply the dfts of a and b and find a b corner case inverse dft first half of next step even positions odd positions update unpack remove leading 0 s overwrite __str__ for print shows a b and a b unit tests
import mpmath import numpy as np class FFT: def __init__(self, poly_a=None, poly_b=None): self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) self.c_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) self.product = self.__multiply() def __dft(self, which): dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] if len(dft) <= 1: return dft[0] next_ncol = self.c_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root dft = new_dft next_ncol = next_ncol // 2 return dft[0] def __multiply(self): dft_a = self.__dft("A") dft_b = self.__dft("B") inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b if len(inverce_c[0]) <= 1: return inverce_c[0] next_ncol = 2 while next_ncol <= self.c_max_length: new_inverse_c = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root inverce_c = new_inverse_c next_ncol *= 2 inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c] while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__(self): a = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) b = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) c = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return f"{a}\n{b}\n{c}" if __name__ == "__main__": import doctest doctest.testmod()
returns the biggest possible result that can be achieved by removing one digit from the given number removedigit152 52 removedigit6385 685 removedigit11 1 removedigit2222222 222222 removedigit2222222 traceback most recent call last typeerror only integers accepted as input removedigitstring input traceback most recent call last typeerror only integers accepted as input 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
def remove_digit(num: int) -> int: 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()
segmented sieve import math def sieven int listint if n 0 or isinstancen float msg fnumber n must instead be a positive integer raise valueerrormsg inprime start 2 end intmath sqrtn size of every segment temp true end 1 prime while start end if tempstart is true inprime appendstart for i in rangestart start end 1 start tempi false start 1 prime inprime low end 1 high min2 end n while low n temp true high low 1 for each in inprime t math floorlow each each if t low t each for j in ranget high 1 each tempj low false for j in rangelentemp if tempj is true prime appendj low low high 1 high minhigh end n return prime if name main import doctest doctest testmod printfsieve106 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 size of every segment
import math def sieve(n: int) -> list[int]: 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)) 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) = }")
arithmetic mean reference https en wikipedia orgwikiarithmeticmean arithmetic series reference https en wikipedia orgwikiarithmeticseries the url above will redirect you to arithmetic progression checking whether the input series is arithmetic series or not isarithmeticseries2 4 6 true isarithmeticseries3 6 12 24 false isarithmeticseries1 2 3 true isarithmeticseries4 traceback most recent call last valueerror input series is not valid valid series 2 4 6 isarithmeticseries traceback most recent call last valueerror input list must be a non empty list return the arithmetic mean of series arithmeticmean2 4 6 4 0 arithmeticmean3 6 9 12 7 5 arithmeticmean4 traceback most recent call last valueerror input series is not valid valid series 2 4 6 arithmeticmean4 8 1 4 333333333333333 arithmeticmean1 2 3 2 0 arithmeticmean traceback most recent call last valueerror input list must be a non empty list checking whether the input series is arithmetic series or not is_arithmetic_series 2 4 6 true is_arithmetic_series 3 6 12 24 false is_arithmetic_series 1 2 3 true is_arithmetic_series 4 traceback most recent call last valueerror input series is not valid valid series 2 4 6 is_arithmetic_series traceback most recent call last valueerror input list must be a non empty list return the arithmetic mean of series arithmetic_mean 2 4 6 4 0 arithmetic_mean 3 6 9 12 7 5 arithmetic_mean 4 traceback most recent call last valueerror input series is not valid valid series 2 4 6 arithmetic_mean 4 8 1 4 333333333333333 arithmetic_mean 1 2 3 2 0 arithmetic_mean traceback most recent call last valueerror input list must be a non empty list
def is_arithmetic_series(series: list) -> bool: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
geometric mean reference https en wikipedia orgwikigeometricmean geometric series reference https en wikipedia orgwikigeometricseries checking whether the input series is geometric series or not isgeometricseries2 4 8 true isgeometricseries3 6 12 24 true isgeometricseries1 2 3 false isgeometricseries0 0 3 false isgeometricseries traceback most recent call last valueerror input list must be a non empty list isgeometricseries4 traceback most recent call last valueerror input series is not valid valid series 2 4 8 return the geometric mean of series geometricmean2 4 8 3 9999999999999996 geometricmean3 6 12 24 8 48528137423857 geometricmean4 8 16 7 999999999999999 geometricmean4 traceback most recent call last valueerror input series is not valid valid series 2 4 8 geometricmean1 2 3 1 8171205928321397 geometricmean0 2 3 0 0 geometricmean traceback most recent call last valueerror input list must be a non empty list checking whether the input series is geometric series or not is_geometric_series 2 4 8 true is_geometric_series 3 6 12 24 true is_geometric_series 1 2 3 false is_geometric_series 0 0 3 false is_geometric_series traceback most recent call last valueerror input list must be a non empty list is_geometric_series 4 traceback most recent call last valueerror input series is not valid valid series 2 4 8 return the geometric mean of series geometric_mean 2 4 8 3 9999999999999996 geometric_mean 3 6 12 24 8 48528137423857 geometric_mean 4 8 16 7 999999999999999 geometric_mean 4 traceback most recent call last valueerror input series is not valid valid series 2 4 8 geometric_mean 1 2 3 1 8171205928321397 geometric_mean 0 2 3 0 0 geometric_mean traceback most recent call last valueerror input list must be a non empty list
def is_geometric_series(series: list) -> bool: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True try: common_ratio = series[1] / series[0] for index in range(len(series) - 1): if series[index + 1] / series[index] != common_ratio: return False except ZeroDivisionError: return False return True def geometric_mean(series: list) -> float: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 1 for value in series: answer *= value return pow(answer, 1 / len(series)) if __name__ == "__main__": import doctest doctest.testmod()
this is a pure python implementation of the geometric series algorithm https en wikipedia orgwikigeometricseries run the doctests with the following command python3 m doctest v geometricseries py or python m doctest v geometricseries py for manual testing run python3 geometricseries py pure python implementation of geometric series algorithm param nthterm the last term nth term of geometric series param startterma the first term of geometric series param commonratior the common ratio between all the terms return the geometric series starting from first term a and multiple of common ration with first term with increase in power till last term nth term examples geometricseries4 2 2 2 4 0 8 0 16 0 geometricseries4 0 2 0 2 0 2 0 4 0 8 0 16 0 geometricseries4 1 2 1 2 1 2 1 4 41 9 261000000000001 19 448100000000004 geometricseries4 2 2 2 4 0 8 0 16 0 geometricseries4 2 2 2 4 0 8 0 16 0 geometricseries4 2 2 geometricseries0 100 500 geometricseries1 1 1 1 geometricseries0 0 0 pure python implementation of geometric series algorithm param nth_term the last term nth term of geometric series param start_term_a the first term of geometric series param common_ratio_r the common ratio between all the terms return the geometric series starting from first term a and multiple of common ration with first term with increase in power till last term nth term examples geometric_series 4 2 2 2 4 0 8 0 16 0 geometric_series 4 0 2 0 2 0 2 0 4 0 8 0 16 0 geometric_series 4 1 2 1 2 1 2 1 4 41 9 261000000000001 19 448100000000004 geometric_series 4 2 2 2 4 0 8 0 16 0 geometric_series 4 2 2 2 4 0 8 0 16 0 geometric_series 4 2 2 geometric_series 0 100 500 geometric_series 1 1 1 1 geometric_series 0 0 0
from __future__ import annotations def geometric_series( nth_term: float, start_term_a: float, common_ratio_r: float, ) -> list[float]: if not all((nth_term, start_term_a, common_ratio_r)): return [] series: list[float] = [] power = 1 multiple = common_ratio_r for _ in range(int(nth_term)): if not series: series.append(start_term_a) else: power += 1 series.append(float(start_term_a * multiple)) multiple = pow(float(common_ratio_r), power) return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = float(input("Enter the last number (n term) of the Geometric Series")) start_term_a = float(input("Enter the starting term (a) of the Geometric Series")) common_ratio_r = float( input("Enter the common ratio between two terms (r) of the Geometric Series") ) print("Formula of Geometric Series => a + ar + ar^2 ... +ar^n") print(geometric_series(nth_term, start_term_a, common_ratio_r))
harmonic mean reference https en wikipedia orgwikiharmonicmean harmonic series reference https en wikipedia orgwikiharmonicseriesmathematics checking whether the input series is arithmetic series or not isharmonicseries 1 23 12 25 13 true isharmonicseries 1 23 25 13 false isharmonicseries1 2 3 false isharmonicseries12 13 14 true isharmonicseries25 210 215 220 225 true isharmonicseries4 traceback most recent call last valueerror input series is not valid valid series 1 23 2 isharmonicseries traceback most recent call last valueerror input list must be a non empty list isharmonicseries0 traceback most recent call last valueerror input series cannot have 0 as an element isharmonicseries1 2 0 6 traceback most recent call last valueerror input series cannot have 0 as an element return the harmonic mean of series harmonicmean1 4 4 2 0 harmonicmean3 6 9 12 5 759999999999999 harmonicmean4 traceback most recent call last valueerror input series is not valid valid series 2 4 6 harmonicmean1 2 3 1 6363636363636365 harmonicmean traceback most recent call last valueerror input list must be a non empty list checking whether the input series is arithmetic series or not is_harmonic_series 1 2 3 1 2 2 5 1 3 true is_harmonic_series 1 2 3 2 5 1 3 false is_harmonic_series 1 2 3 false is_harmonic_series 1 2 1 3 1 4 true is_harmonic_series 2 5 2 10 2 15 2 20 2 25 true is_harmonic_series 4 traceback most recent call last valueerror input series is not valid valid series 1 2 3 2 is_harmonic_series traceback most recent call last valueerror input list must be a non empty list is_harmonic_series 0 traceback most recent call last valueerror input series cannot have 0 as an element is_harmonic_series 1 2 0 6 traceback most recent call last valueerror input series cannot have 0 as an element return the harmonic mean of series harmonic_mean 1 4 4 2 0 harmonic_mean 3 6 9 12 5 759999999999999 harmonic_mean 4 traceback most recent call last valueerror input series is not valid valid series 2 4 6 harmonic_mean 1 2 3 1 6363636363636365 harmonic_mean traceback most recent call last valueerror input list must be a non empty list
def is_harmonic_series(series: list) -> bool: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [1, 2/3, 2]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1 and series[0] != 0: return True rec_series = [] series_len = len(series) for i in range(series_len): if series[i] == 0: raise ValueError("Input series cannot have 0 as an element") rec_series.append(1 / series[i]) common_diff = rec_series[1] - rec_series[0] for index in range(2, series_len): if rec_series[index] - rec_series[index - 1] != common_diff: return False return True def harmonic_mean(series: list) -> float: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += 1 / val return len(series) / answer if __name__ == "__main__": import doctest doctest.testmod()
this is a pure python implementation of the harmonic series algorithm https en wikipedia orgwikiharmonicseriesmathematics for doctests run following command python m doctest v harmonicseries py or python3 m doctest v harmonicseries py for manual testing run python3 harmonicseries py pure python implementation of harmonic series algorithm param nterm the last nth term of harmonic series return the harmonic series starting from 1 to last nth term examples harmonicseries5 1 12 13 14 15 harmonicseries5 0 1 12 13 14 15 harmonicseries5 1 1 12 13 14 15 harmonicseries5 harmonicseries0 harmonicseries1 1 pure python implementation of harmonic series algorithm param n_term the last nth term of harmonic series return the harmonic series starting from 1 to last nth term examples harmonic_series 5 1 1 2 1 3 1 4 1 5 harmonic_series 5 0 1 1 2 1 3 1 4 1 5 harmonic_series 5 1 1 1 2 1 3 1 4 1 5 harmonic_series 5 harmonic_series 0 harmonic_series 1 1
def harmonic_series(n_term: str) -> list: if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
a hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number h is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots when the hexagons are overlaid so that they share one vertex calculates the hexagonal numbers sequence with a formula h n2n1 where h is nth element of the sequence n is the number of element in the sequence referencehexagonal number wikipedia https en wikipedia orgwikihexagonalnumber param len max number of elements type len int return hexagonal numbers as a list tests hexagonalnumbers10 0 1 6 15 28 45 66 91 120 153 hexagonalnumbers5 0 1 6 15 28 hexagonalnumbers0 traceback most recent call last valueerror length must be a positive integer param len max number of elements type len int return hexagonal numbers as a list tests hexagonal_numbers 10 0 1 6 15 28 45 66 91 120 153 hexagonal_numbers 5 0 1 6 15 28 hexagonal_numbers 0 traceback most recent call last valueerror length must be a positive integer
def hexagonal_numbers(length: int) -> list[int]: if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
this is a pure python implementation of the pseries algorithm https en wikipedia orgwikiharmonicseriesmathematicspseries for doctests run following command python m doctest v pseries py or python3 m doctest v pseries py for manual testing run python3 pseries py pure python implementation of pseries algorithm return the pseries starting from 1 to last nth term examples pseries5 2 1 1 4 1 9 1 16 1 25 pseries5 2 pseries5 2 1 1 0 25 1 0 1111111111111111 1 0 0625 1 0 04 pseries 1000 pseries0 0 pseries1 1 1 pure python implementation of p series algorithm return the p series starting from 1 to last nth term examples p_series 5 2 1 1 4 1 9 1 16 1 25 p_series 5 2 p_series 5 2 1 1 0 25 1 0 1111111111111111 1 0 0625 1 0 04 p_series 1000 p_series 0 0 p_series 1 1 1
from __future__ import annotations def p_series(nth_term: float | str, power: float | str) -> list[str]: if nth_term == "": return [""] nth_term = int(nth_term) power = int(power) series: list[str] = [] for temp in range(int(nth_term)): series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1") return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = int(input("Enter the last number (nth term) of the P-Series")) power = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
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 orgwikipediacommonsbb9sieveoferatosthenesanimation gif reference https en wikipedia orgwikisieveoferatosthenes doctest provider bruno simas hadlich https github combrunohadlich also thanks to dmitry https github comlizardwizzard for finding the problem returns a list with all prime numbers up to n primesieve50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 primesieve25 2 3 5 7 11 13 17 19 23 primesieve10 2 3 5 7 primesieve9 2 3 5 7 primesieve2 2 primesieve1 if start is a prime set multiples of start be false 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 start is a prime set multiples of start be false
from __future__ import annotations import math def prime_sieve(num: int) -> list[int]: if num <= 0: msg = f"{num}: Invalid input, please enter a positive integer." raise ValueError(msg) sieve = [True] * (num + 1) prime = [] start = 2 end = int(math.sqrt(num)) while start <= end: if sieve[start] is True: prime.append(start) 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())))
this script demonstrates the implementation of the sigmoid function the function takes a vector of k real numbers as input and then 1 1 expx 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 orgwikisigmoidfunction implements the sigmoid function parameters vector np array a numpy array of shape 1 n consisting of real values returns sigmoidvec np array the input numpy array after applying sigmoid examples sigmoidnp array1 0 1 0 2 0 array0 26894142 0 73105858 0 88079708 sigmoidnp array0 0 array0 5 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
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-vector)) if __name__ == "__main__": import doctest doctest.testmod()
signum function https en wikipedia orgwikisignfunction applies signum function on the number custom test cases signum10 1 signum10 1 signum0 0 signum20 5 1 signum20 5 1 signum1e6 1 signum1e6 1 signumhello 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 tests the signum function testsignum 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 tests the signum function test_signum
def signum(num: float) -> int: if num < 0: return -1 return 1 if num else 0 def test_signum() -> None: assert signum(5) == 1 assert signum(-5) == -1 assert signum(0) == 0 assert signum(10.5) == 1 assert signum(-10.5) == -1 assert signum(1e-6) == 1 assert signum(-1e-6) == -1 assert signum(123456789) == 1 assert signum(-123456789) == -1 if __name__ == "__main__": print(signum(12)) print(signum(-12)) print(signum(0))
https en wikipedia orgwikiaugmentedmatrix this algorithm solves simultaneous linear equations of the form a b c d as where 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 0 simplify1 2 3 4 5 6 1 0 2 0 3 0 0 0 0 75 1 5 simplify5 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 subtract to cancel term if first term is 0 it is already in form we want so we preserve it create next recursion iteration set solvesimultaneous1 2 3 4 5 6 1 0 2 0 solvesimultaneous0 3 1 7 3 2 1 11 5 1 2 12 6 4 1 2 10 6 solvesimultaneous traceback most recent call last indexerror solvesimultaneous requires n lists of length n1 solvesimultaneous1 2 3 1 2 traceback most recent call last indexerror solvesimultaneous requires n lists of length n1 solvesimultaneous1 2 3 a 7 8 traceback most recent call last valueerror solvesimultaneous requires lists of integers solvesimultaneous0 2 3 4 0 6 traceback most recent call last valueerror solvesimultaneous requires at least 1 full equation 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 subtract to cancel term if first term is 0 it is already in form we want so we preserve it create next recursion iteration set 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
def simplify(current_set: list[list]) -> list[list]: 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 first_row = current_set[0] final_set = [first_row] current_set = current_set[1::] for row in current_set: temp_row = [] 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) if len(final_set[0]) != 3: current_first_row = final_set[0] current_first_column = [] next_iteration = [] for row in final_set[1::]: current_first_column.append(row[0]) next_iteration.append(row[1::]) resultant = simplify(next_iteration) for i in range(len(resultant)): resultant[i].insert(0, current_first_column[i]) resultant.insert(0, current_first_row) final_set = resultant return final_set def solve_simultaneous(equations: list[list]) -> list: if len(equations) == 0: raise IndexError("solve_simultaneous() requires n lists of length n+1") _length = len(equations) + 1 if any(len(item) != _length for item in equations): raise IndexError("solve_simultaneous() requires n lists of length n+1") for row in equations: if any(not isinstance(column, (int, float)) for column in row): raise ValueError("solve_simultaneous() requires lists of integers") if len(equations) == 1: return [equations[0][-1] / equations[0][0]] data_set = equations.copy() if any(0 in row for row in data_set): temp_data = data_set.copy() full_row = [] for row_index, row in enumerate(temp_data): if 0 not in row: full_row = data_set.pop(row_index) break if not full_row: raise ValueError("solve_simultaneous() requires at least 1 full equation") data_set.insert(0, full_row) useable_form = data_set.copy() simplified = simplify(useable_form) simplified = simplified[::-1] solutions: list = [] for row in simplified: current_solution = row[-1] if not solutions: if row[-2] == 0: solutions.append(0) continue solutions.append(current_solution / row[-2]) continue temp_row = row.copy()[: len(row) - 1 :] while temp_row[0] == 0: temp_row.pop(0) if len(temp_row) == 0: solutions.append(0) continue temp_row = temp_row[1::] temp_row = temp_row[::-1] for column_index, column in enumerate(temp_row): current_solution -= column * solutions[column_index] solutions.append(current_solution) final = [] for item in solutions: final.append(float(round(item, 5))) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() eq = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
calculate sin function it s not a perfect function so i am rounding the result to 10 decimal places by default formula sinx x x33 x55 x77 where x angle in randians source https www homeschoolmath netteachingsinecalculator php implement sin function sin0 0 0 0 sin90 0 1 0 sin180 0 0 0 sin270 0 1 0 sin0 68 0 0118679603 sin1 97 0 0343762121 sin64 0 0 8987940463 sin9999 0 0 9876883406 sin689 0 0 5150380749 sin89 7 0 9999862922 simplify the angle to be between 360 and 360 degrees converting from degrees to radians implement sin function sin 0 0 0 0 sin 90 0 1 0 sin 180 0 0 0 sin 270 0 1 0 sin 0 68 0 0118679603 sin 1 97 0 0343762121 sin 64 0 0 8987940463 sin 9999 0 0 9876883406 sin 689 0 0 5150380749 sin 89 7 0 9999862922 simplify the angle to be between 360 and 360 degrees converting from degrees to radians one positive term and the next will be negative and so on increased by 2 for every term
from math import factorial, radians def sin( angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10 ) -> float: angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) angle_in_radians = radians(angle_in_degrees) result = angle_in_radians a = 3 b = -1 for _ in range(accuracy): result += (b * (angle_in_radians**a)) / factorial(a) b = -b a += 2 return round(result, rounded_values_count) if __name__ == "__main__": __import__("doctest").testmod()
sockmerchant10 20 20 10 10 30 50 10 20 3 sockmerchant1 1 3 3 2 sock_merchant 10 20 20 10 10 30 50 10 20 3 sock_merchant 1 1 3 3 2
from collections import Counter def sock_merchant(colors: list[int]) -> int: return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
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 orgwikisoftmaxfunction 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 softmaxvec np array the input numpy array after applying softmax the softmax vector adds up to one we need to ceil to mitigate for precision np ceilnp sumsoftmax1 2 3 4 1 0 vec np array5 5 softmaxvec array0 5 0 5 softmax0 array1 calculate ex for each x in your vector where e is euler s number approximately 2 718 add up the all the exponentials divide every exponent by the sum of all exponents 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 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 add up the all the exponentials divide every exponent by the sum of all exponents
import numpy as np def softmax(vector): exponent_vector = np.exp(vector) sum_of_exponents = np.sum(exponent_vector) softmax_vector = exponent_vector / sum_of_exponents return softmax_vector if __name__ == "__main__": print(softmax((0,)))
this script implements the solovaystrassen 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 orgwikisolovaye28093strassenprimalitytest 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 solovaystrassen 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 randoma a randomly chosen integer from 2 to n2 inclusive number the number that is tested for primality returns jacobisymbol the jacobi symbol is a mathematical function used to determine whether an integer is a quadratic residue modulo another integer usually prime or not jacobisymbol2 13 1 jacobisymbol5 19 1 jacobisymbol7 14 0 check whether the input number is prime or not using the solovaystrassen 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 seed10 solovaystrassen13 5 true solovaystrassen9 10 false solovaystrassen17 15 true 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 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
import random def jacobi_symbol(random_a: int, number: int) -> int: 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: 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()
assigns ranks to elements in the array param data list of floats return list of ints representing the ranks example assignranks3 2 1 5 4 0 2 7 5 1 3 1 4 2 5 assignranks10 5 8 1 12 4 9 3 11 0 3 1 5 2 4 calculates spearman s rank correlation coefficient param variable1 list of floats representing the first variable param variable2 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 calculatespearmanrankcorrelationx y 1 0 x 1 2 3 4 5 y 2 4 6 8 10 calculatespearmanrankcorrelationx y 1 0 x 1 2 3 4 5 y 5 1 2 9 5 calculatespearmanrankcorrelationx y 0 6 calculate differences of ranks calculate the sum of squared differences calculate the spearman s rank correlation coefficient example usage 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 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 calculate differences of ranks calculate the sum of squared differences calculate the spearman s rank correlation coefficient example usage
from collections.abc import Sequence def assign_ranks(data: Sequence[float]) -> list[int]: ranked_data = sorted((value, index) for index, value in enumerate(data)) ranks = [0] * len(data) for position, (_, index) in enumerate(ranked_data): ranks[index] = position + 1 return ranks def calculate_spearman_rank_correlation( variable_1: Sequence[float], variable_2: Sequence[float] ) -> float: n = len(variable_1) rank_var1 = assign_ranks(variable_1) rank_var2 = assign_ranks(variable_2) d = [rx - ry for rx, ry in zip(rank_var1, rank_var2)] d_squared = sum(di**2 for di in d) rho = 1 - (6 * d_squared) / (n * (n**2 - 1)) return rho if __name__ == "__main__": import doctest doctest.testmod() 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]) = }")
an armstrong number is equal to the sum of its own digits each raised to the power of the number of digits for example 370 is an armstrong number because 333 777 000 370 armstrong numbers are also called narcissistic numbers and pluperfect numbers online encyclopedia of integer sequences entry https oeis orga005188 return true if n is an armstrong number or false if it is not allarmstrongnumbern for n in passing true anyarmstrongnumbern for n in failing false initialization of sum and number of digits calculation of digits of the number dividing number into separate digits and find armstrong number return true if n is a pluperfect number or false if it is not allarmstrongnumbern for n in passing true anyarmstrongnumbern for n in failing false init a histogram of the digits return true if n is a narcissistic number or false if it is not allarmstrongnumbern for n in passing true anyarmstrongnumbern for n in failing false check if sum of each digit multiplied expo times is equal to number request that user input an integer and tell them if it is armstrong number return true if n is an armstrong number or false if it is not all armstrong_number n for n in passing true any armstrong_number n for n in failing false initialization of sum and number of digits calculation of digits of the number dividing number into separate digits and find armstrong number return true if n is a pluperfect number or false if it is not all armstrong_number n for n in passing true any armstrong_number n for n in failing false init a histogram of the digits return true if n is a narcissistic number or false if it is not all armstrong_number n for n in passing true any armstrong_number n for n in failing false the power that all digits will be raised to check if sum of each digit multiplied expo times is equal to number request that user input an integer and tell them if it is armstrong number
PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) def armstrong_number(n: int) -> bool: if not isinstance(n, int) or n < 1: return False total = 0 number_of_digits = 0 temp = n number_of_digits = len(str(n)) temp = n while temp > 0: rem = temp % 10 total += rem**number_of_digits temp //= 10 return n == total def pluperfect_number(n: int) -> bool: if not isinstance(n, int) or n < 1: return False digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] digit_total = 0 total = 0 temp = n while temp > 0: temp, rem = divmod(temp, 10) digit_histogram[rem] += 1 digit_total += 1 for cnt, i in zip(digit_histogram, range(len(digit_histogram))): total += cnt * i**digit_total return n == total def narcissistic_number(n: int) -> bool: if not isinstance(n, int) or n < 1: return False expo = len(str(n)) return n == sum(int(i) ** expo for i in str(n)) def main(): num = int(input("Enter an integer to see if it is an Armstrong number: ").strip()) print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if pluperfect_number(num) else 'not '}an Armstrong number.") if __name__ == "__main__": import doctest doctest.testmod() main()
automorphic numbers a number n is said to be a automorphic number if the square of n ends in the same digits as n itself examples of automorphic numbers 0 1 5 6 25 76 376 625 9376 90625 https en wikipedia orgwikiautomorphicnumber akshay dubey https github comitsakshaydubey time complexity olog10n doctest normalizewhitespace this functions takes an integer number as input returns true if the number is automorphic isautomorphicnumber1 false isautomorphicnumber0 true isautomorphicnumber5 true isautomorphicnumber6 true isautomorphicnumber7 false isautomorphicnumber25 true isautomorphicnumber259918212890625 true isautomorphicnumber259918212890636 false isautomorphicnumber740081787109376 true isautomorphicnumber5 0 traceback most recent call last typeerror input value of number5 0 must be an integer akshay dubey https github com itsakshaydubey time complexity o log10n doctest normalize_whitespace this functions takes an integer number as input returns true if the number is automorphic is_automorphic_number 1 false is_automorphic_number 0 true is_automorphic_number 5 true is_automorphic_number 6 true is_automorphic_number 7 false is_automorphic_number 25 true is_automorphic_number 259918212890625 true is_automorphic_number 259918212890636 false is_automorphic_number 740081787109376 true is_automorphic_number 5 0 traceback most recent call last typeerror input value of number 5 0 must be an integer
def is_automorphic_number(number: int) -> bool: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0: return False number_square = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
bell numbers represent the number of ways to partition a set into nonempty subsets this module provides functions to calculate bell numbers for sets of integers in other words the first n 1 bell numbers for more information about bell numbers refer to https en wikipedia orgwikibellnumber calculate bell numbers for the sets of lengths from 0 to maxsetlength in other words calculate first maxsetlength 1 bell numbers args maxsetlength int the maximum length of the sets for which bell numbers are calculated returns list a list of bell numbers for sets of lengths from 0 to maxsetlength examples bellnumbers0 1 bellnumbers1 1 1 bellnumbers5 1 1 2 5 15 52 calculate the binomial coefficient ctotalelements elementstochoose args totalelements int the total number of elements elementstochoose int the number of elements to choose returns int the binomial coefficient ctotalelements elementstochoose examples binomialcoefficient5 2 10 binomialcoefficient6 3 20 calculate bell numbers for the sets of lengths from 0 to max_set_length in other words calculate first max_set_length 1 bell numbers args max_set_length int the maximum length of the sets for which bell numbers are calculated returns list a list of bell numbers for sets of lengths from 0 to max_set_length examples bell_numbers 0 1 bell_numbers 1 1 1 bell_numbers 5 1 1 2 5 15 52 calculate the binomial coefficient c total_elements elements_to_choose args total_elements int the total number of elements elements_to_choose int the number of elements to choose returns int the binomial coefficient c total_elements elements_to_choose examples _binomial_coefficient 5 2 10 _binomial_coefficient 6 3 20
def bell_numbers(max_set_length: int) -> list[int]: if max_set_length < 0: raise ValueError("max_set_length must be non-negative") bell = [0] * (max_set_length + 1) bell[0] = 1 for i in range(1, max_set_length + 1): for j in range(i): bell[i] += _binomial_coefficient(i - 1, j) * bell[j] return bell def _binomial_coefficient(total_elements: int, elements_to_choose: int) -> int: if elements_to_choose in {0, total_elements}: return 1 if elements_to_choose > total_elements - elements_to_choose: elements_to_choose = total_elements - elements_to_choose coefficient = 1 for i in range(elements_to_choose): coefficient *= total_elements - i coefficient //= i + 1 return coefficient if __name__ == "__main__": import doctest doctest.testmod()
carmichael numbers a number n is said to be a carmichael number if it satisfies the following modular arithmetic condition powerb n1 mod n 1 for all b ranging from 1 to n such that b and n are relatively prime i e gcdb n 1 examples of carmichael numbers 561 1105 https en wikipedia orgwikicarmichaelnumber examples power2 15 3 2 power5 1 30 5 examples iscarmichaelnumber4 false iscarmichaelnumber561 true iscarmichaelnumber562 false iscarmichaelnumber900 false iscarmichaelnumber1105 true iscarmichaelnumber8911 true iscarmichaelnumber5 1 traceback most recent call last valueerror number 5 1 must instead be a positive integer iscarmichaelnumber7 traceback most recent call last valueerror number 7 must instead be a positive integer iscarmichaelnumber0 traceback most recent call last valueerror number 0 must instead be a positive integer examples power 2 15 3 2 power 5 1 30 5 examples is_carmichael_number 4 false is_carmichael_number 561 true is_carmichael_number 562 false is_carmichael_number 900 false is_carmichael_number 1105 true is_carmichael_number 8911 true is_carmichael_number 5 1 traceback most recent call last valueerror number 5 1 must instead be a positive integer is_carmichael_number 7 traceback most recent call last valueerror number 7 must instead be a positive integer is_carmichael_number 0 traceback most recent call last valueerror number 0 must instead be a positive integer
from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 == 1: temp = (temp * x) % mod return temp def is_carmichael_number(n: int) -> bool: if n <= 0 or not isinstance(n, int): msg = f"Number {n} must instead be a positive integer" raise ValueError(msg) return all( power(b, n - 1, n) == 1 for b in range(2, n) if greatest_common_divisor(b, n) == 1 ) if __name__ == "__main__": import doctest doctest.testmod() number = int(input("Enter number: ").strip()) if is_carmichael_number(number): print(f"{number} is a Carmichael Number.") else: print(f"{number} is not a Carmichael Number.")
calculate the nth catalan number source https en wikipedia orgwikicatalannumber param number nth catalan number to calculate return the nth catalan number note a catalan number is only defined for positive integers catalan5 14 catalan0 traceback most recent call last valueerror input value of number0 must be 0 catalan1 traceback most recent call last valueerror input value of number1 must be 0 catalan5 0 traceback most recent call last typeerror input value of number5 0 must be an integer param number nth catalan number to calculate return the nth catalan number note a catalan number is only defined for positive integers catalan 5 14 catalan 0 traceback most recent call last valueerror input value of number 0 must be 0 catalan 1 traceback most recent call last valueerror input value of number 1 must be 0 catalan 5 0 traceback most recent call last typeerror input value of number 5 0 must be an integer
def catalan(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) current_number = 1 for i in range(1, number): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
a hamming number is a positive integer of the form 2i3j5k for some nonnegative integers i j and k they are often referred to as regular numbers more info at https en wikipedia orgwikiregularnumber this function creates an ordered list of n length as requested and afterwards returns the last value of the list it must be given a positive integer param nelement the number of elements on the list return the nth element of the list hamming5 1 2 3 4 5 hamming10 1 2 3 4 5 6 8 9 10 12 hamming15 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 this function creates an ordered list of n length as requested and afterwards returns the last value of the list it must be given a positive integer param n_element the number of elements on the list return the nth element of the list hamming 5 1 2 3 4 5 hamming 10 1 2 3 4 5 6 8 9 10 12 hamming 15 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24
def hamming(n_element: int) -> list: n_element = int(n_element) if n_element < 1: my_error = ValueError("a should be a positive number") raise my_error hamming_list = [1] i, j, k = (0, 0, 0) index = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5) ) index += 1 return hamming_list if __name__ == "__main__": n = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") hamming_numbers = hamming(int(n)) print("-----------------------------------------------------") print(f"The list with nth numbers is: {hamming_numbers}") print("-----------------------------------------------------")
a happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit param number the number to check for happiness return true if the number is a happy number false otherwise ishappynumber19 true ishappynumber2 false ishappynumber23 true ishappynumber1 true ishappynumber0 traceback most recent call last valueerror number0 must be a positive integer ishappynumber19 traceback most recent call last valueerror number19 must be a positive integer ishappynumber19 1 traceback most recent call last valueerror number19 1 must be a positive integer ishappynumberhappy traceback most recent call last valueerror number happy must be a positive integer a happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit param number the number to check for happiness return true if the number is a happy number false otherwise is_happy_number 19 true is_happy_number 2 false is_happy_number 23 true is_happy_number 1 true is_happy_number 0 traceback most recent call last valueerror number 0 must be a positive integer is_happy_number 19 traceback most recent call last valueerror number 19 must be a positive integer is_happy_number 19 1 traceback most recent call last valueerror number 19 1 must be a positive integer is_happy_number happy traceback most recent call last valueerror number happy must be a positive integer
def is_happy_number(number: int) -> bool: if not isinstance(number, int) or number <= 0: msg = f"{number=} must be a positive integer" raise ValueError(msg) seen = set() while number != 1 and number not in seen: seen.add(number) number = sum(int(digit) ** 2 for digit in str(number)) return number == 1 if __name__ == "__main__": import doctest doctest.testmod()
a harshad number or more specifically an nharshad number is a number that s divisible by the sum of its digits in some given base n reference https en wikipedia orgwikiharshadnumber convert a given positive decimal integer to base base where base ranges from 2 to 36 examples inttobase23 2 10111 inttobase58 5 213 inttobase167 16 a7 bases below 2 and beyond 36 will error inttobase98 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive inttobase98 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive calculate the sum of digit values in a positive integer converted to the given base where base ranges from 2 to 36 examples sumofdigits103 12 13 sumofdigits1275 4 30 sumofdigits6645 2 1001 bases below 2 and beyond 36 will error sumofdigits543 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive sumofdigits543 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive finds all harshad numbers smaller than num in base base where base ranges from 2 to 36 examples harshadnumbersinbase15 2 1 10 100 110 1000 1010 1100 harshadnumbersinbase12 34 1 2 3 4 5 6 7 8 9 a b harshadnumbersinbase12 4 1 2 3 10 12 20 21 bases below 2 and beyond 36 will error harshadnumbersinbase234 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive harshadnumbersinbase234 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive determines whether n in base base is a harshad number where base ranges from 2 to 36 examples isharshadnumberinbase18 10 true isharshadnumberinbase21 10 true isharshadnumberinbase21 5 false bases below 2 and beyond 36 will error isharshadnumberinbase45 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive isharshadnumberinbase45 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive convert a given positive decimal integer to base base where base ranges from 2 to 36 examples int_to_base 23 2 10111 int_to_base 58 5 213 int_to_base 167 16 a7 bases below 2 and beyond 36 will error int_to_base 98 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive int_to_base 98 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive calculate the sum of digit values in a positive integer converted to the given base where base ranges from 2 to 36 examples sum_of_digits 103 12 13 sum_of_digits 1275 4 30 sum_of_digits 6645 2 1001 bases below 2 and beyond 36 will error sum_of_digits 543 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive sum_of_digits 543 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive finds all harshad numbers smaller than num in base base where base ranges from 2 to 36 examples harshad_numbers_in_base 15 2 1 10 100 110 1000 1010 1100 harshad_numbers_in_base 12 34 1 2 3 4 5 6 7 8 9 a b harshad_numbers_in_base 12 4 1 2 3 10 12 20 21 bases below 2 and beyond 36 will error harshad_numbers_in_base 234 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive harshad_numbers_in_base 234 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive determines whether n in base base is a harshad number where base ranges from 2 to 36 examples is_harshad_number_in_base 18 10 true is_harshad_number_in_base 21 10 true is_harshad_number_in_base 21 5 false bases below 2 and beyond 36 will error is_harshad_number_in_base 45 37 traceback most recent call last valueerror base must be between 2 and 36 inclusive is_harshad_number_in_base 45 1 traceback most recent call last valueerror base must be between 2 and 36 inclusive
def int_to_base(number: int, base: int) -> str: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" if number < 0: raise ValueError("number must be a positive integer") while number > 0: number, remainder = divmod(number, base) result = digits[remainder] + result if result == "": result = "0" return result def sum_of_digits(num: int, base: int) -> str: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") num_str = int_to_base(num, base) res = sum(int(char, base) for char in num_str) res_str = int_to_base(res, base) return res_str def harshad_numbers_in_base(limit: int, base: int) -> list[str]: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if limit < 0: return [] numbers = [ int_to_base(i, base) for i in range(1, limit) if i % int(sum_of_digits(i, base), base) == 0 ] return numbers def is_harshad_number_in_base(num: int, base: int) -> bool: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if num < 0: return False n = int_to_base(num, base) d = sum_of_digits(num, base) return int(n, base) % int(d, base) == 0 if __name__ == "__main__": import doctest doctest.testmod()
hexagonal number the nth hexagonal number hn is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots when the hexagons are overlaid so that they share one vertex https en wikipedia orgwikihexagonalnumber akshay dubey https github comitsakshaydubey param number nth hexagonal number to calculate return the nth hexagonal number note a hexagonal number is only defined for positive integers hexagonal4 28 hexagonal11 231 hexagonal22 946 hexagonal0 traceback most recent call last valueerror input must be a positive integer hexagonal1 traceback most recent call last valueerror input must be a positive integer hexagonal11 0 traceback most recent call last typeerror input value of number11 0 must be an integer akshay dubey https github com itsakshaydubey param number nth hexagonal number to calculate return the nth hexagonal number note a hexagonal number is only defined for positive integers hexagonal 4 28 hexagonal 11 231 hexagonal 22 946 hexagonal 0 traceback most recent call last valueerror input must be a positive integer hexagonal 1 traceback most recent call last valueerror input must be a positive integer hexagonal 11 0 traceback most recent call last typeerror input value of number 11 0 must be an integer
def hexagonal(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise ValueError("Input must be a positive integer") return number * (2 * number - 1) if __name__ == "__main__": import doctest doctest.testmod()
krishnamurthy number it is also known as peterson number a krishnamurthy number is a number whose sum of the factorial of the digits equals to the original number itself for example 145 1 4 5 so 145 is a krishnamurthy number factorial3 6 factorial0 1 factorial5 120 krishnamurthy145 true krishnamurthy240 false krishnamurthy1 true factorial 3 6 factorial 0 1 factorial 5 120 krishnamurthy 145 true krishnamurthy 240 false krishnamurthy 1 true
def factorial(digit: int) -> int: return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: fact_sum = 0 duplicate = number while duplicate > 0: duplicate, digit = divmod(duplicate, 10) fact_sum += factorial(digit) return fact_sum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") number = int(input("Enter number: ").strip()) print( f"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number." )
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 divisors1 2 3 6 excluding 6 the sumdivisors is 1 2 3 6 so 6 is a perfect number other examples of perfect numbers 28 486 https en wikipedia orgwikiperfectnumber 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 false otherwise 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 perfect27 false perfect28 true perfect29 false perfect6 true perfect12 false perfect496 true perfect8128 true perfect0 false perfect1 false perfect12 34 traceback most recent call last valueerror number must be an integer perfecthello traceback most recent call last valueerror number must be an integer 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 false otherwise 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 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
def perfect(number: int) -> bool: 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" print(msg) raise ValueError(msg) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
returns the numth sidesgonal number it is assumed that num 0 and sides 3 see for reference https en wikipedia orgwikipolygonalnumber polygonalnum0 3 0 polygonalnum3 3 6 polygonalnum5 4 25 polygonalnum2 5 5 polygonalnum1 0 traceback most recent call last valueerror invalid input num must be 0 and sides must be 3 polygonalnum0 2 traceback most recent call last valueerror invalid input num must be 0 and sides must be 3 returns the num th sides gonal number it is assumed that num 0 and sides 3 see for reference https en wikipedia org wiki polygonal_number polygonal_num 0 3 0 polygonal_num 3 3 6 polygonal_num 5 4 25 polygonal_num 2 5 5 polygonal_num 1 0 traceback most recent call last valueerror invalid input num must be 0 and sides must be 3 polygonal_num 0 2 traceback most recent call last valueerror invalid input num must be 0 and sides must be 3
def polygonal_num(num: int, sides: int) -> int: if num < 0 or sides < 3: raise ValueError("Invalid input: num must be >= 0 and sides must be >= 3.") return ((sides - 2) * num**2 - (sides - 4) * num) // 2 if __name__ == "__main__": import doctest doctest.testmod()
pronic number a number n is said to be a proic number if there exists an integer m such that n m m 1 examples of proic numbers 0 2 6 12 20 30 42 56 72 90 110 https en wikipedia orgwikipronicnumber akshay dubey https github comitsakshaydubey doctest normalizewhitespace this functions takes an integer number as input returns true if the number is pronic ispronic1 false ispronic0 true ispronic2 true ispronic5 false ispronic6 true ispronic8 false ispronic30 true ispronic32 false ispronic2147441940 true ispronic9223372033963249500 true ispronic6 0 traceback most recent call last typeerror input value of number6 0 must be an integer akshay dubey https github com itsakshaydubey doctest normalize_whitespace this functions takes an integer number as input returns true if the number is pronic is_pronic 1 false is_pronic 0 true is_pronic 2 true is_pronic 5 false is_pronic 6 true is_pronic 8 false is_pronic 30 true is_pronic 32 false is_pronic 2147441940 true is_pronic 9223372033963249500 true is_pronic 6 0 traceback most recent call last typeerror input value of number 6 0 must be an integer
def is_pronic(number: int) -> bool: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0 or number % 2 == 1: return False number_sqrt = int(number**0.5) return number == number_sqrt * (number_sqrt + 1) if __name__ == "__main__": import doctest doctest.testmod()
calculate the nth proth number source https handwiki orgwikiprothnumber param number nth number to calculate in the sequence return the nth number in proth number note indexing starts at 1 i e proth1 gives the first proth number of 3 proth6 25 proth0 traceback most recent call last valueerror input value of number0 must be 0 proth1 traceback most recent call last valueerror input value of number1 must be 0 proth6 0 traceback most recent call last typeerror input value of number6 0 must be an integer 1 for binary starting at 0 i e 20 21 etc 1 to start the sequence at the 3rd proth number hence we have a 2 in the below statement param number nth number to calculate in the sequence return the nth number in proth number note indexing starts at 1 i e proth 1 gives the first proth number of 3 proth 6 25 proth 0 traceback most recent call last valueerror input value of number 0 must be 0 proth 1 traceback most recent call last valueerror input value of number 1 must be 0 proth 6 0 traceback most recent call last typeerror input value of number 6 0 must be an integer 1 for binary starting at 0 i e 2 0 2 1 etc 1 to start the sequence at the 3rd proth number hence we have a 2 in the below statement
import math def proth(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) elif number == 1: return 3 elif number == 2: return 5 else: block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for _ in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")
a triangular number or triangle number counts objects arranged in an equilateral triangle this module provides a function to generate n th triangular number for more information about triangular numbers refer to https en wikipedia orgwikitriangularnumber generate the triangular number at the specified position args position int the position of the triangular number to generate returns int the triangular number at the specified position raises valueerror if position is negative examples triangularnumber1 1 triangularnumber3 6 triangularnumber1 traceback most recent call last valueerror param position must be nonnegative generate the triangular number at the specified position args position int the position of the triangular number to generate returns int the triangular number at the specified position raises valueerror if position is negative examples triangular_number 1 1 triangular_number 3 6 triangular_number 1 traceback most recent call last valueerror param position must be non negative
def triangular_number(position: int) -> int: if position < 0: raise ValueError("param `position` must be non-negative") return position * (position + 1) // 2 if __name__ == "__main__": import doctest doctest.testmod()
ugly numbers are numbers whose only prime factors are 2 3 or 5 the sequence 1 2 3 4 5 6 8 9 10 12 15 shows the first 11 ugly numbers by convention 1 is included given an integer n we have to find the nth ugly number for more details refer this article https www geeksforgeeks orguglynumbers returns the nth ugly number uglynumbers100 1536 uglynumbers0 1 uglynumbers20 36 uglynumbers5 1 uglynumbers5 5 traceback most recent call last typeerror float object cannot be interpreted as an integer returns the nth ugly number ugly_numbers 100 1536 ugly_numbers 0 1 ugly_numbers 20 36 ugly_numbers 5 1 ugly_numbers 5 5 traceback most recent call last typeerror float object cannot be interpreted as an integer
def ugly_numbers(n: int) -> int: ugly_nums = [1] i2, i3, i5 = 0, 0, 0 next_2 = ugly_nums[i2] * 2 next_3 = ugly_nums[i3] * 3 next_5 = ugly_nums[i5] * 5 for _ in range(1, n): next_num = min(next_2, next_3, next_5) ugly_nums.append(next_num) if next_num == next_2: i2 += 1 next_2 = ugly_nums[i2] * 2 if next_num == next_3: i3 += 1 next_3 = ugly_nums[i3] * 3 if next_num == next_5: i5 += 1 next_5 = ugly_nums[i5] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(f"{ugly_numbers(200) = }")
https en wikipedia orgwikiweirdnumber fun fact the set of weird numbers has positive asymptotic density factors12 1 2 3 4 6 factors1 1 factors100 1 2 4 5 10 20 25 50 factors12 1 2 3 4 6 abundant0 true abundant1 false abundant12 true abundant13 false abundant20 true abundant12 true semiperfect0 true semiperfect1 true semiperfect12 true semiperfect13 false semiperfect12 true weird0 false weird70 true weird77 false factors 12 1 2 3 4 6 factors 1 1 factors 100 1 2 4 5 10 20 25 50 factors 12 1 2 3 4 6 abundant 0 true abundant 1 false abundant 12 true abundant 13 false abundant 20 true abundant 12 true semi_perfect 0 true semi_perfect 1 true semi_perfect 12 true semi_perfect 13 false semi_perfect 12 true weird 0 false weird 70 true weird 77 false
from math import sqrt def factors(number: int) -> list[int]: values = [1] for i in range(2, int(sqrt(number)) + 1, 1): if number % i == 0: values.append(i) if int(number // i) != i: values.append(int(number // i)) return sorted(values) def abundant(n: int) -> bool: return sum(factors(n)) > n def semi_perfect(number: int) -> bool: values = factors(number) r = len(values) subset = [[0 for i in range(number + 1)] for j in range(r + 1)] for i in range(r + 1): subset[i][0] = True for i in range(1, number + 1): subset[0][i] = False for i in range(1, r + 1): for j in range(1, number + 1): if j < values[i - 1]: subset[i][j] = subset[i - 1][j] else: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - values[i - 1]] return subset[r][number] != 0 def weird(number: int) -> bool: return abundant(number) and not semi_perfect(number) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) for number in (69, 70, 71): print(f"{number} is {'' if weird(number) else 'not '}weird.")
darkcoder find the sum of n terms in an arithmetic progression sumofseries1 1 10 55 0 sumofseries1 10 100 49600 0 formula for sum of series darkcoder find the sum of n terms in an arithmetic progression sum_of_series 1 1 10 55 0 sum_of_series 1 10 100 49600 0 formula for sum of series
def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float: total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) return total def main(): print(sum_of_series(1, 1, 10)) if __name__ == "__main__": import doctest doctest.testmod()
find the sum of digits of a number sumofdigits12345 15 sumofdigits123 6 sumofdigits123 6 sumofdigits0 0 find the sum of digits of a number using recursion sumofdigitsrecursion12345 15 sumofdigitsrecursion123 6 sumofdigitsrecursion123 6 sumofdigitsrecursion0 0 find the sum of digits of a number sumofdigitscompact12345 15 sumofdigitscompact123 6 sumofdigitscompact123 6 sumofdigitscompact0 0 benchmark multiple functions with three different length int values 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 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 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 benchmark multiple functions with three different length int values
def sum_of_digits(n: int) -> int: n = abs(n) res = 0 while n > 0: res += n % 10 n //= 10 return res def sum_of_digits_recursion(n: int) -> int: n = abs(n) return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: return sum(int(c) for c in str(abs(n))) def benchmark() -> None: 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()
return the sum of n terms in a geometric progression sumofgeometricprogression1 2 10 1023 0 sumofgeometricprogression1 10 5 11111 0 sumofgeometricprogression0 2 10 0 0 sumofgeometricprogression1 0 10 1 0 sumofgeometricprogression1 2 0 0 0 sumofgeometricprogression1 2 10 1023 0 sumofgeometricprogression1 2 10 341 0 sumofgeometricprogression1 2 10 0 9990234375 formula for sum if common ratio is 1 formula for finding sum of n terms of a geometricprogression 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 formula for sum if common ratio is 1 formula for finding sum of n terms of a geometricprogression
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: if common_ratio == 1: return num_of_terms * first_term return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)
https en wikipedia orgwikiharmonicprogressionmathematics find the sum of n terms in an harmonic progression the calculation starts with the firstterm and loops adding the common difference of arithmetic progression by which the given harmonic progression is linked sumofharmonicprogression1 2 2 2 0 75 sumofharmonicprogression1 5 5 5 0 45666666666666667 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
def sum_of_harmonic_progression( first_term: float, common_difference: float, number_of_terms: int ) -> float: 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))
calculates the sumset of two sets of numbers a and b source https en wikipedia orgwikisumset param first set a set of numbers param second set a set of numbers return the nth number in sylvester s sequence sumset1 2 3 4 5 6 5 6 7 8 9 sumset1 2 3 4 5 6 7 5 6 7 8 9 10 sumset1 2 3 4 3 traceback most recent call last assertionerror the input value of setb3 is not a 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
def sumset(set_a: set, set_b: set) -> 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()
calculates the nth number in sylvester s sequence source https en wikipedia orgwikisylvester27ssequence param number nth number to calculate in the sequence return the nth number in sylvester s sequence sylvester8 113423713055421844361000443 sylvester1 traceback most recent call last valueerror the input value of n1 has to be 0 sylvester8 0 traceback most recent call last assertionerror the input value of n8 0 is not an integer 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
def sylvester(number: int) -> int: 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)}")
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 ex exex ex after through tanh the element of the vector mostly 1 between 1 script inspired from its corresponding wikipedia article https en wikipedia orgwikiactivationfunction implements the tanh function parameters vector np ndarray returns tanh np array the input numpy array after applying tanh mathematically ex exex ex can be written as 21e2x1 examples tangenthyperbolicnp array1 5 6 0 67 array 0 76159416 0 9999092 0 99998771 0 58497988 tangenthyperbolicnp array8 10 2 0 98 13 array 0 99999977 1 0 96402758 0 7530659 1 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
import numpy as np def tangent_hyperbolic(vector: np.ndarray) -> np.ndarray: return (2 / (1 + np.exp(-2 * vector))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
minimalist file that allows pytest to find and run the test unittest for details see https doc pytest orgenlatestgoodpractices htmlconventionsforpythontestdiscovery
from .prime_check import Test Test()
https en wikipedia orgwiki3sum 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 threesum1 0 1 2 1 4 1 1 2 1 0 1 threesum1 2 3 4 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
def three_sum(nums: list[int]) -> list[list[int]]: 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()
numerical integration or quadrature for a smooth function f with known values at xi this method is the classical approach of suming equally spaced abscissas method 1 extended trapezoidal rule extended trapezoidal rule intf dx2 f1 2f2 fn printi extended trapezoidal rule int f dx 2 f1 2f2 fn print i enter your function here lower bound of integration upper bound of integration define number of steps or resolution define boundary of integration
def method_1(boundary, steps): 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): x = a + h while x < (b - h): yield x x = x + h def f(x): y = (x - 0) * (x - 0) return y def main(): a = 0.0 b = 1.0 steps = 10.0 boundary = [a, b] y = method_1(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
twin prime a number n2 is said to be a twin prime of number n if both n and n2 are prime examples of twin pairs 3 5 5 7 11 13 17 19 29 31 41 43 https en wikipedia orgwikitwinprime akshay dubey https github comitsakshaydubey doctest normalizewhitespace this functions takes an integer number as input returns n2 if n and n2 are prime numbers and 1 otherwise twinprime3 5 twinprime4 1 twinprime5 7 twinprime17 19 twinprime0 1 twinprime6 0 traceback most recent call last typeerror input value of number6 0 must be an integer akshay dubey https github com itsakshaydubey 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
from maths.prime_check import is_prime def twin_prime(number: int) -> int: 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()
given a sorted array of integers return indices of the two numbers such that they add up to a specific target using the two pointers technique you may assume that each input would have exactly one solution and you may not use the same element twice this is an alternative solution of the twosum problem which uses a map to solve the problem hence can not solve the issue if there is a constraint not use the same index twice 1 example given nums 2 7 11 15 target 9 because nums0 nums1 2 7 9 return 0 1 1 https github comthealgorithmspythonblobmasterothertwosum py twopointer2 7 11 15 9 0 1 twopointer2 7 11 15 17 0 3 twopointer2 7 11 15 18 1 2 twopointer2 7 11 15 26 2 3 twopointer1 3 3 6 1 2 twopointer2 7 11 15 8 twopointer3 i for i in range10 19 twopointer1 2 3 6 two_pointer 2 7 11 15 9 0 1 two_pointer 2 7 11 15 17 0 3 two_pointer 2 7 11 15 18 1 2 two_pointer 2 7 11 15 26 2 3 two_pointer 1 3 3 6 1 2 two_pointer 2 7 11 15 8 two_pointer 3 i for i in range 10 19 two_pointer 1 2 3 6
from __future__ import annotations def two_pointer(nums: list[int], target: int) -> list[int]: i = 0 j = len(nums) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: i = i + 1 else: j = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_pointer([2, 7, 11, 15], 9) = }")
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 nums0 nums1 2 7 9 return 0 1 twosum2 7 11 15 9 0 1 twosum15 2 11 7 13 1 2 twosum2 7 11 15 17 0 3 twosum7 15 11 2 18 0 2 twosum2 7 11 15 26 2 3 twosum2 7 11 15 8 twosum3 i for i in range10 19 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
from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: 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) = }")
find the volume of various shapes https en wikipedia orgwikivolume https en wikipedia orgwikisphericalcap calculate the volume of a cube volcube1 1 0 volcube3 27 0 volcube0 0 0 volcube1 6 4 096000000000001 volcube1 traceback most recent call last valueerror volcube only accepts nonnegative values calculate the volume of the spherical cap volsphericalcap1 2 5 235987755982988 volsphericalcap1 6 2 6 16 621119532592402 volsphericalcap0 0 0 0 volsphericalcap1 2 traceback most recent call last valueerror volsphericalcap only accepts nonnegative values volsphericalcap1 2 traceback most recent call last valueerror volsphericalcap only accepts nonnegative values volume is 13 pi height squared 3 radius height 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 h1 h2 of the spherical caps then the two volumes and it returns the sum the height formulas are h1 radius1 radius2 centersdistance radius1 radius2 centersdistance 2 centersdistance h2 radius2 radius1 centersdistance radius2 radius1 centersdistance 2 centersdistance if centersdistance is 0 then it returns the volume of the smallers sphere return volsphericalcaph1 radius2 volsphericalcaph2 radius1 volspheresintersect2 2 1 21 205750411731103 volspheresintersect2 6 2 6 1 6 40 71504079052372 volspheresintersect0 0 0 0 0 volspheresintersect2 2 1 traceback most recent call last valueerror volspheresintersect only accepts nonnegative values volspheresintersect2 2 1 traceback most recent call last valueerror volspheresintersect only accepts nonnegative values volspheresintersect2 2 1 traceback most recent call last valueerror volspheresintersect only accepts nonnegative values calculate the volume of the union of two spheres that possibly intersect it is the sum of sphere a and sphere b minus their intersection first it calculates the volumes v1 v2 of the spheres then the volume of the intersection i and it returns the sum v1v2i if centersdistance is 0 then it returns the volume of the larger sphere return volsphereradius1 volsphereradius2 volspheresintersectradius1 radius2 centersdistance volspheresunion2 2 1 45 814892864851146 volspheresunion1 56 2 2 1 4 48 77802773671288 volspheresunion0 2 1 traceback most recent call last valueerror volspheresunion only accepts nonnegative values nonzero radius volspheresunion 1 56 2 2 1 4 traceback most recent call last typeerror not supported between instances of str and int volspheresunion1 none 1 traceback most recent call last typeerror not supported between instances of nonetype and int calculate the volume of a cuboid return multiple of width length and height volcuboid1 1 1 1 0 volcuboid1 2 3 6 0 volcuboid1 6 2 6 3 6 14 976 volcuboid0 0 0 0 0 volcuboid1 2 3 traceback most recent call last valueerror volcuboid only accepts nonnegative values volcuboid1 2 3 traceback most recent call last valueerror volcuboid only accepts nonnegative values volcuboid1 2 3 traceback most recent call last valueerror volcuboid only accepts nonnegative values calculate the volume of a cone wikipedia reference https en wikipedia orgwikicone return 13 areaofbase height volcone10 3 10 0 volcone1 1 0 3333333333333333 volcone1 6 1 6 0 8533333333333335 volcone0 0 0 0 volcone1 1 traceback most recent call last valueerror volcone only accepts nonnegative values volcone1 1 traceback most recent call last valueerror volcone only accepts nonnegative values calculate the volume of a right circular cone wikipedia reference https en wikipedia orgwikicone return 13 pi radius2 height volrightcirccone2 3 12 566370614359172 volrightcirccone0 0 0 0 volrightcirccone1 6 1 6 4 289321169701265 volrightcirccone1 1 traceback most recent call last valueerror volrightcirccone only accepts nonnegative values volrightcirccone1 1 traceback most recent call last valueerror volrightcirccone only accepts nonnegative values calculate the volume of a prism wikipedia reference https en wikipedia orgwikiprismgeometry return v bh volprism10 2 20 0 volprism11 1 11 0 volprism1 6 1 6 2 5600000000000005 volprism0 0 0 0 volprism1 1 traceback most recent call last valueerror volprism only accepts nonnegative values volprism1 1 traceback most recent call last valueerror volprism only accepts nonnegative values calculate the volume of a pyramid wikipedia reference https en wikipedia orgwikipyramidgeometry return 13 bh volpyramid10 3 10 0 volpyramid1 5 3 1 5 volpyramid1 6 1 6 0 8533333333333335 volpyramid0 0 0 0 volpyramid1 1 traceback most recent call last valueerror volpyramid only accepts nonnegative values volpyramid1 1 traceback most recent call last valueerror volpyramid only accepts nonnegative values calculate the volume of a sphere wikipedia reference https en wikipedia orgwikisphere return 43 pi r3 volsphere5 523 5987755982989 volsphere1 4 1887902047863905 volsphere1 6 17 15728467880506 volsphere0 0 0 volsphere1 traceback most recent call last valueerror volsphere only accepts nonnegative values volume is 43 pi radius cubed calculate the volume of a hemisphere wikipedia reference https en wikipedia orgwikihemisphere other references https www cuemath comgeometryhemisphere return 23 pi radius3 volhemisphere1 2 0943951023931953 volhemisphere7 718 377520120866 volhemisphere1 6 8 57864233940253 volhemisphere0 0 0 volhemisphere1 traceback most recent call last valueerror volhemisphere only accepts nonnegative values volume is radius cubed pi 23 calculate the volume of a circular cylinder wikipedia reference https en wikipedia orgwikicylinder return pi radius2 height volcircularcylinder1 1 3 141592653589793 volcircularcylinder4 3 150 79644737231007 volcircularcylinder1 6 1 6 12 867963509103795 volcircularcylinder0 0 0 0 volcircularcylinder1 1 traceback most recent call last valueerror volcircularcylinder only accepts nonnegative values volcircularcylinder1 1 traceback most recent call last valueerror volcircularcylinder only accepts nonnegative values volume is radius squared height pi calculate the volume of a hollow circular cylinder volhollowcircularcylinder1 2 3 28 274333882308138 volhollowcircularcylinder1 6 2 6 3 6 47 50088092227767 volhollowcircularcylinder1 2 3 traceback most recent call last valueerror volhollowcircularcylinder only accepts nonnegative values volhollowcircularcylinder1 2 3 traceback most recent call last valueerror volhollowcircularcylinder only accepts nonnegative values volhollowcircularcylinder1 2 3 traceback most recent call last valueerror volhollowcircularcylinder only accepts nonnegative values volhollowcircularcylinder2 1 3 traceback most recent call last valueerror outerradius must be greater than innerradius volhollowcircularcylinder0 0 0 traceback most recent call last valueerror outerradius must be greater than innerradius volume outerradius squared innerradius squared pi height calculate the volume of a conical frustum wikipedia reference https en wikipedia orgwikifrustum volconicalfrustum45 7 28 48490 482608158454 volconicalfrustum1 1 2 7 330382858376184 volconicalfrustum1 6 2 6 3 6 48 7240076620753 volconicalfrustum0 0 0 0 0 volconicalfrustum2 2 1 traceback most recent call last valueerror volconicalfrustum only accepts nonnegative values volconicalfrustum2 2 1 traceback most recent call last valueerror volconicalfrustum only accepts nonnegative values volconicalfrustum2 2 1 traceback most recent call last valueerror volconicalfrustum only accepts nonnegative values volume is 13 pi height radius1 squared radius2 squared radius1 radius2 calculate the volume of a torus wikipedia reference https en wikipedia orgwikitorus return 2pi2 torusradius tuberadius2 voltorus1 1 19 739208802178716 voltorus4 3 710 6115168784338 voltorus3 4 947 4820225045784 voltorus1 6 1 6 80 85179925372404 voltorus0 0 0 0 voltorus1 1 traceback most recent call last valueerror voltorus only accepts nonnegative values voltorus1 1 traceback most recent call last valueerror voltorus only accepts nonnegative values calculate the volume of an icosahedron wikipedia reference https en wikipedia orgwikiregularicosahedron from math import isclose isclosevolicosahedron2 5 34 088984228514256 true isclosevolicosahedron10 2181 694990624912374 true isclosevolicosahedron5 272 711873828114047 true isclosevolicosahedron3 49 92 740688412033628 true volicosahedron0 0 0 volicosahedron1 traceback most recent call last valueerror volicosahedron only accepts nonnegative values volicosahedron0 2 traceback most recent call last valueerror volicosahedron only accepts nonnegative values print the results of various volume calculations printvolumes printfcube volcube2 8 printfcuboid volcuboid2 2 2 8 printfcone volcone2 2 1 33 printfright circular cone volrightcirccone2 2 8 38 printfprism volprism2 2 4 printfpyramid volpyramid2 2 1 33 printfsphere volsphere2 33 5 printfhemisphere volhemisphere2 16 75 printfcircular cylinder volcircularcylinder2 2 25 1 printftorus voltorus2 2 157 9 printfconical frustum volconicalfrustum2 2 4 58 6 printfspherical cap volsphericalcap1 2 5 24 printfspheres intersetion volspheresintersect2 2 1 21 21 printfspheres union volspheresunion2 2 1 45 81 print fhollow circular cylinder volhollowcircularcylinder1 2 3 28 3 printficosahedron volicosahedron2 5 34 09 if name main main 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 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 volume is 1 3 pi height squared 3 radius height 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 h1 h2 of the spherical caps then the two volumes and it returns the sum the height formulas are 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 if centers_distance is 0 then it returns the volume of the smallers sphere return vol_spherical_cap h1 radius_2 vol_spherical_cap h2 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 calculate the volume of the union of two spheres that possibly intersect it is the sum of sphere a and sphere b minus their intersection first it calculates the volumes v1 v2 of the spheres then the volume of the intersection i and it returns the sum v1 v2 i if centers_distance is 0 then it returns the volume of the larger sphere return vol_sphere radius_1 vol_sphere radius_2 vol_spheres_intersect radius_1 radius_2 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 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 calculate the volume of a cone wikipedia reference https en wikipedia org wiki cone return 1 3 area_of_base 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 calculate the volume of a right circular cone wikipedia reference https en wikipedia org wiki cone return 1 3 pi radius 2 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 calculate the volume of a prism wikipedia reference https en wikipedia org wiki prism_ geometry return v bh 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 calculate the volume of a pyramid wikipedia reference https en wikipedia org wiki pyramid_ geometry return 1 3 bh 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 calculate the volume of a sphere wikipedia reference https en wikipedia org wiki sphere return 4 3 pi 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 volume is 4 3 pi radius cubed calculate the volume of a hemisphere wikipedia reference https en wikipedia org wiki hemisphere other references https www cuemath com geometry hemisphere return 2 3 pi 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 volume is radius cubed pi 2 3 calculate the volume of a circular cylinder wikipedia reference https en wikipedia org wiki cylinder return pi radius 2 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 volume is radius squared height pi 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 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 calculate the volume of a torus wikipedia reference https en wikipedia org wiki torus return 2pi 2 torus_radius 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 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 print the results of various volume calculations 8 8 1 33 8 38 4 1 33 33 5 16 75 25 1 157 9 58 6 5 24 21 21 45 81 28 3 34 09
from __future__ import annotations from math import pi, pow def vol_cube(side_length: float) -> float: 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: if height < 0 or radius < 0: raise ValueError("vol_spherical_cap() only accepts non-negative values") return 1 / 3 * pi * pow(height, 2) * (3 * radius - height) def vol_spheres_intersect( radius_1: float, radius_2: float, centers_distance: float ) -> float: 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: 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: 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: 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: 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: 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: 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: if radius < 0: raise ValueError("vol_sphere() only accepts non-negative values") return 4 / 3 * pi * pow(radius, 3) def vol_hemisphere(radius: float) -> float: if radius < 0: raise ValueError("vol_hemisphere() only accepts non-negative values") return pow(radius, 3) * pi * 2 / 3 def vol_circular_cylinder(radius: float, height: float) -> float: if height < 0 or radius < 0: raise ValueError("vol_circular_cylinder() only accepts non-negative values") return pow(radius, 2) * height * pi def vol_hollow_circular_cylinder( inner_radius: float, outer_radius: float, height: float ) -> float: 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: 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: 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: 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("Volumes:") print(f"Cube: {vol_cube(2) = }") print(f"Cuboid: {vol_cuboid(2, 2, 2) = }") print(f"Cone: {vol_cone(2, 2) = }") print(f"Right Circular Cone: {vol_right_circ_cone(2, 2) = }") print(f"Prism: {vol_prism(2, 2) = }") print(f"Pyramid: {vol_pyramid(2, 2) = }") print(f"Sphere: {vol_sphere(2) = }") print(f"Hemisphere: {vol_hemisphere(2) = }") print(f"Circular Cylinder: {vol_circular_cylinder(2, 2) = }") print(f"Torus: {vol_torus(2, 2) = }") print(f"Conical Frustum: {vol_conical_frustum(2, 2, 4) = }") print(f"Spherical cap: {vol_spherical_cap(1, 2) = }") print(f"Spheres intersetion: {vol_spheres_intersect(2, 2, 1) = }") print(f"Spheres union: {vol_spheres_union(2, 2, 1) = }") print( f"Hollow Circular Cylinder: {vol_hollow_circular_cylinder(1, 2, 3) = }" ) print(f"Icosahedron: {vol_icosahedron(2.5) = }") if __name__ == "__main__": main()
zellers congruence algorithm find the day of the week for nearly any gregorian or julian calendar date zeller 01312010 your date 01312010 is a sunday validate out of range month zeller 13312010 traceback most recent call last valueerror month must be between 1 12 zeller 2312010 traceback most recent call last valueerror invalid literal for int with base 10 2 validate out of range date zeller 01332010 traceback most recent call last valueerror date must be between 1 31 zeller 01 42010 traceback most recent call last valueerror invalid literal for int with base 10 4 validate second separator zeller 01312010 traceback most recent call last valueerror date separator must be or validate first separator zeller 01312010 traceback most recent call last valueerror date separator must be or validate out of range year zeller 01318999 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 dateinput test length of dateinput zeller traceback most recent call last valueerror must be 10 characters long zeller 013119082939 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 convertdatetimedays 0 1 1 2 2 3 3 4 4 5 5 6 6 0 validate if not 0 lendateinput 11 raise valueerrormust be 10 characters long get month m int intdateinput0 dateinput1 validate if not 0 m 13 raise valueerrormonth must be between 1 12 sep1 str dateinput2 validate if sep1 not in raise valueerrordate separator must be or get day d int intdateinput3 dateinput4 validate if not 0 d 32 raise valueerrordate must be between 1 31 get second separator sep2 str dateinput5 validate if sep2 not in raise valueerrordate separator must be or get year y int intdateinput6 dateinput7 dateinput8 dateinput9 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 dtck datetime dateinty intm intd start math if m 2 y y 1 m m 12 maths var c int intstry 2 k int intstry2 t int int2 6 m 5 39 u int intc 4 v int intk 4 x int intd k z int intt u v x w int intz 2 c f int roundw 7 end math validate math if f convertdatetimedaysdtck weekday raise assertionerrorthe date was evaluated incorrectly contact developer response response str fyour date dateinput is a daysstrf 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 mmddyyyy or mmddyyyy format parser addargument dateinput typestr helpdate as a string mmddyyyy or mmddyyyy args parser parseargs zellerargs dateinput 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 validate get month validate validate get day validate get second separator validate get year arbitrary year range get datetime obj for validation start math maths var end math validate math response
import argparse import datetime def zeller(date_input: str) -> str: 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} if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") m: int = int(date_input[0] + date_input[1]) if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") d: int = int(date_input[3] + date_input[4]) if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") sep_2: str = date_input[5] if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) dt_ck = datetime.date(int(y), int(m), int(d)) if m <= 2: y = y - 1 m = m + 12 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) if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") 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)
this function carries out binary search on a 1d array and return 1 if it do not exist array a 1d sorted array value the value meant to be searched matrix 1 4 7 11 15 binarysearchmatrix 0 lenmatrix 1 1 0 binarysearchmatrix 0 lenmatrix 1 23 1 this function loops over a 2d matrix and calls binarysearch on the selected 1d array and returns 1 1 is it do not exist value value meant to be searched matrix a sorted 2d matrix matrix 1 4 7 11 15 2 5 8 12 19 3 6 9 16 22 10 13 14 17 24 18 21 23 26 30 target 1 matbinsearchtarget matrix 0 0 target 34 matbinsearchtarget matrix 1 1 this function carries out binary search on a 1d array and return 1 if it do not exist array a 1d sorted array value the value meant to be searched matrix 1 4 7 11 15 binary_search matrix 0 len matrix 1 1 0 binary_search matrix 0 len matrix 1 23 1 this function loops over a 2d matrix and calls binarysearch on the selected 1d array and returns 1 1 is it do not exist value value meant to be searched matrix a sorted 2d matrix matrix 1 4 7 11 15 2 5 8 12 19 3 6 9 16 22 10 13 14 17 24 18 21 23 26 30 target 1 mat_bin_search target matrix 0 0 target 34 mat_bin_search target matrix 1 1
def binary_search(array: list, lower_bound: int, upper_bound: int, value: int) -> int: r = int((lower_bound + upper_bound) // 2) if array[r] == value: return r if lower_bound >= upper_bound: return -1 if array[r] < value: return binary_search(array, r + 1, upper_bound, value) else: return binary_search(array, lower_bound, r - 1, value) def mat_bin_search(value: int, matrix: list) -> list: index = 0 if matrix[index][0] == value: return [index, 0] while index < len(matrix) and matrix[index][0] < value: r = binary_search(matrix[index], 0, len(matrix[index]) - 1, value) if r != -1: return [index, r] index += 1 return [-1, -1] if __name__ == "__main__": import doctest doctest.testmod()
an island in matrix is a group of linked areas all having the same value this code counts number of islands in a given matrix with including diagonal connections checking all 8 elements surrounding nth element an island in matrix is a group of linked areas all having the same value this code counts number of islands in a given matrix with including diagonal connections public class to implement a graph checking all 8 elements surrounding nth element coordinate order make those cells visited and finally count all islands
class Matrix: def __init__(self, row: int, col: int, graph: list[list[bool]]) -> None: self.ROW = row self.COL = col self.graph = graph def is_safe(self, i: int, j: int, visited: list[list[bool]]) -> bool: return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def diffs(self, i: int, j: int, visited: list[list[bool]]) -> None: row_nbr = [-1, -1, -1, 0, 0, 1, 1, 1] col_nbr = [-1, 0, 1, -1, 1, -1, 0, 1] visited[i][j] = True for k in range(8): if self.is_safe(i + row_nbr[k], j + col_nbr[k], visited): self.diffs(i + row_nbr[k], j + col_nbr[k], visited) def count_islands(self) -> int: visited = [[False for j in range(self.COL)] for i in range(self.ROW)] count = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(i, j, visited) count += 1 return count
given an matrix of numbers in which all rows and all columns are sorted in decreasing order return the number of negative numbers in grid reference https leetcode comproblemscountnegativenumbersinasortedmatrix generatelargematrix doctest ellipsis 1000 999 999 1001 2 1998 validate that the rows and columns of the grid is sorted in decreasing order for grid in testgrids validategridgrid find the smallest negative index findnegativeindex0 0 0 0 4 findnegativeindex4 3 2 1 3 findnegativeindex1 0 1 10 2 findnegativeindex0 0 0 1 3 findnegativeindex11 8 7 3 5 9 3 findnegativeindex1 1 2 3 0 findnegativeindex5 1 0 3 findnegativeindex5 5 5 0 findnegativeindex0 1 findnegativeindex 0 edge cases such as no values or all numbers are negative num must be negative and the index must be greater than or equal to 0 no negative numbers so return the last index of the array 1 which is the length an om logn solution that uses binary search in order to find the boundary between positive and negative numbers countnegativesbinarysearchgrid for grid in testgrids 8 0 0 3 1498500 this solution is on2 because it iterates through every column and row countnegativesbruteforcegrid for grid in testgrids 8 0 0 3 1498500 similar to the brute force solution above but uses break in order to reduce the number of iterations countnegativesbruteforcewithbreakgrid for grid in testgrids 8 0 0 3 1498500 benchmark our functions next to each other from timeit import timeit printrunning benchmarks setup from main import countnegativesbinarysearch countnegativesbruteforce countnegativesbruteforcewithbreak grid for func in countnegativesbinarysearch took 0 7727 seconds countnegativesbruteforcewithbreak took 4 6505 seconds countnegativesbruteforce took 12 8160 seconds time timeitffuncgridgrid setupsetup number500 printffunc took time 0 4f seconds if name main import doctest doctest testmod benchmark generate_large_matrix doctest ellipsis 1000 999 999 1001 2 1998 validate that the rows and columns of the grid is sorted in decreasing order for grid in test_grids validate_grid grid find the smallest negative index find_negative_index 0 0 0 0 4 find_negative_index 4 3 2 1 3 find_negative_index 1 0 1 10 2 find_negative_index 0 0 0 1 3 find_negative_index 11 8 7 3 5 9 3 find_negative_index 1 1 2 3 0 find_negative_index 5 1 0 3 find_negative_index 5 5 5 0 find_negative_index 0 1 find_negative_index 0 edge cases such as no values or all numbers are negative num must be negative and the index must be greater than or equal to 0 no negative numbers so return the last index of the array 1 which is the length an o m logn solution that uses binary search in order to find the boundary between positive and negative numbers count_negatives_binary_search grid for grid in test_grids 8 0 0 3 1498500 this solution is o n 2 because it iterates through every column and row count_negatives_brute_force grid for grid in test_grids 8 0 0 3 1498500 similar to the brute force solution above but uses break in order to reduce the number of iterations count_negatives_brute_force_with_break grid for grid in test_grids 8 0 0 3 1498500 benchmark our functions next to each other took 0 7727 seconds took 4 6505 seconds took 12 8160 seconds
def generate_large_matrix() -> list[list[int]]: return [list(range(1000 - i, -1000 - i, -1)) for i in range(1000)] grid = generate_large_matrix() test_grids = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def validate_grid(grid: list[list[int]]) -> None: assert all(row == sorted(row, reverse=True) for row in grid) assert all(list(col) == sorted(col, reverse=True) for col in zip(*grid)) def find_negative_index(array: list[int]) -> int: left = 0 right = len(array) - 1 if not array or array[0] < 0: return 0 while right + 1 > left: mid = (left + right) // 2 num = array[mid] if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: left = mid + 1 else: right = mid - 1 return len(array) def count_negatives_binary_search(grid: list[list[int]]) -> int: total = 0 bound = len(grid[0]) for i in range(len(grid)): bound = find_negative_index(grid[i][:bound]) total += bound return (len(grid) * len(grid[0])) - total def count_negatives_brute_force(grid: list[list[int]]) -> int: return len([number for row in grid for number in row if number < 0]) def count_negatives_brute_force_with_break(grid: list[list[int]]) -> int: total = 0 for row in grid: for i, number in enumerate(row): if number < 0: total += len(row) - i break return total def benchmark() -> None: from timeit import timeit print("Running benchmarks") setup = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", "count_negatives_brute_force_with_break", "count_negatives_brute_force", ): time = timeit(f"{func}(grid=grid)", setup=setup, number=500) print(f"{func}() took {time:0.4f} seconds") if __name__ == "__main__": import doctest doctest.testmod() benchmark()
given a grid where you start from the top left position 0 0 you want to find how many paths you can take to get to the bottom right position start here 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 finish here how many distinct paths can you take to get to the finish using a recursive depthfirst search algorithm below you are able to find the number of distinct unique paths count will demonstrate a path in the example above there are two distinct paths 1 2 0 1 1 0 1 1 0 0 1 0 0 1 0 1 0 1 recursive backtracking depth first search algorithm starting from top left of a matrix count the number of paths that can reach the bottom right of a matrix 1 represents a block inaccessible 0 represents a valid space accessible 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 grid 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 depthfirstsearchgrid 0 0 set 2 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 grid 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 depthfirstsearchgrid 0 0 set 2 recursive backtracking depth first search algorithm starting from top left of a matrix count the number of paths that can reach the bottom right of a matrix 1 represents a block inaccessible 0 represents a valid space accessible 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 grid 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 depth_first_search grid 0 0 set 2 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 grid 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 depth_first_search grid 0 0 set 2
def depth_first_search(grid: list[list[int]], row: int, col: int, visit: set) -> int: row_length, col_length = len(grid), len(grid[0]) if ( min(row, col) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col)) count = 0 count += depth_first_search(grid, row + 1, col, visit) count += depth_first_search(grid, row - 1, col, visit) count += depth_first_search(grid, row, col + 1, visit) count += depth_first_search(grid, row, col - 1, visit) visit.remove((row, col)) return count if __name__ == "__main__": import doctest doctest.testmod()
https www chilimath comlessonsadvancedalgebracramersrulewithtwovariables https en wikipedia orgwikicramer27srule solves the system of linear equation in 2 variables param equation1 list of 3 numbers param equation2 list of 3 numbers return string of result input format a1 b1 d1 a2 b2 d2 determinant a1 b1 a2 b2 determinantx d1 b1 d2 b2 determinanty a1 d1 a2 d2 cramersrule2x22 3 0 5 1 0 0 0 0 0 cramersrule2x20 4 50 2 0 26 13 0 12 5 cramersrule2x211 2 30 1 0 4 4 0 7 0 cramersrule2x24 7 1 1 2 0 2 0 1 0 cramersrule2x21 2 3 2 4 6 traceback most recent call last valueerror infinite solutions consistent system cramersrule2x21 2 3 2 4 7 traceback most recent call last valueerror no solution inconsistent system cramersrule2x21 2 3 11 22 traceback most recent call last valueerror please enter a valid equation cramersrule2x20 1 6 0 0 3 traceback most recent call last valueerror no solution inconsistent system cramersrule2x20 0 6 0 0 3 traceback most recent call last valueerror both a b of two equations can t be zero cramersrule2x21 2 3 1 2 3 traceback most recent call last valueerror infinite solutions consistent system cramersrule2x20 4 50 0 3 99 traceback most recent call last valueerror no solution inconsistent system check if the input is valid extract the coefficients calculate the determinants of the matrices check if the system of linear equations has a solution using cramer s rule trivial solution inconsistent system nontrivial solution consistent system https www chilimath com lessons advanced algebra cramers rule with two variables https en wikipedia org wiki cramer 27s_rule solves the system of linear equation in 2 variables param equation1 list of 3 numbers param equation2 list of 3 numbers return string of result input format a1 b1 d1 a2 b2 d2 determinant a1 b1 a2 b2 determinant_x d1 b1 d2 b2 determinant_y a1 d1 a2 d2 cramers_rule_2x2 2 3 0 5 1 0 0 0 0 0 cramers_rule_2x2 0 4 50 2 0 26 13 0 12 5 cramers_rule_2x2 11 2 30 1 0 4 4 0 7 0 cramers_rule_2x2 4 7 1 1 2 0 2 0 1 0 cramers_rule_2x2 1 2 3 2 4 6 traceback most recent call last valueerror infinite solutions consistent system cramers_rule_2x2 1 2 3 2 4 7 traceback most recent call last valueerror no solution inconsistent system cramers_rule_2x2 1 2 3 11 22 traceback most recent call last valueerror please enter a valid equation cramers_rule_2x2 0 1 6 0 0 3 traceback most recent call last valueerror no solution inconsistent system cramers_rule_2x2 0 0 6 0 0 3 traceback most recent call last valueerror both a b of two equations can t be zero cramers_rule_2x2 1 2 3 1 2 3 traceback most recent call last valueerror infinite solutions consistent system cramers_rule_2x2 0 4 50 0 3 99 traceback most recent call last valueerror no solution inconsistent system check if the input is valid extract the coefficients calculate the determinants of the matrices check if the system of linear equations has a solution using cramer s rule trivial solution inconsistent system non trivial solution consistent system
def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> tuple[float, float]: if not len(equation1) == len(equation2) == 3: raise ValueError("Please enter a valid equation.") if equation1[0] == equation1[1] == equation2[0] == equation2[1] == 0: raise ValueError("Both a & b of two equations can't be zero.") a1, b1, c1 = equation1 a2, b2, c2 = equation2 determinant = a1 * b2 - a2 * b1 determinant_x = c1 * b2 - c2 * b1 determinant_y = a1 * c2 - a2 * c1 if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("Infinite solutions. (Consistent system)") else: raise ValueError("No solution. (Inconsistent system)") else: if determinant_x == determinant_y == 0: return (0.0, 0.0) else: x = determinant_x / determinant y = determinant_y / determinant return (x, y)
a matrix multiplied with its inverse gives the identity matrix this function finds the inverse of a 2x2 and 3x3 matrix if the determinant of a matrix is 0 its inverse does not exist sources for fixing inaccurate float arithmetic https stackoverflow comquestions6563058howdoiuseaccuratefloatarithmeticinpython https docs python org3librarydecimal html doctests for 2x2 inverseofmatrix2 5 2 0 0 0 0 5 0 2 0 2 inverseofmatrix2 5 5 1 2 traceback most recent call last valueerror this matrix has no inverse inverseofmatrix12 16 9 0 0 0 0 1111111111111111 0 0625 0 08333333333333333 inverseofmatrix12 3 16 8 0 16666666666666666 0 0625 0 3333333333333333 0 25 inverseofmatrix10 5 3 2 5 0 25 0 5 0 3 1 0 doctests for 3x3 inverseofmatrix2 5 7 2 0 1 1 2 3 2 0 5 0 4 0 1 0 1 0 1 0 5 0 12 0 10 0 inverseofmatrix1 2 2 1 2 2 3 2 1 traceback most recent call last valueerror this matrix has no inverse inverseofmatrix traceback most recent call last valueerror please provide a matrix of size 2x2 or 3x3 inverseofmatrix1 2 3 4 5 6 traceback most recent call last valueerror please provide a matrix of size 2x2 or 3x3 inverseofmatrix1 2 1 0 3 4 traceback most recent call last valueerror please provide a matrix of size 2x2 or 3x3 inverseofmatrix1 2 3 7 8 9 7 8 9 traceback most recent call last valueerror this matrix has no inverse inverseofmatrix1 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 check if the provided matrix has 2 rows and 2 columns since this implementation only works for 2x2 matrices calculate the determinant of the matrix creates a copy of the matrix with swapped positions of the elements calculate the inverse of the matrix calculate the determinant of the matrix using sarrus rule creating cofactor matrix transpose the cofactor matrix adjoint matrix inverse of the matrix using the formula 1determinant adjoint matrix calculate the inverse of the matrix a matrix multiplied with its inverse gives the identity matrix this function finds the inverse of a 2x2 and 3x3 matrix if the determinant of a matrix is 0 its inverse does not exist sources for fixing inaccurate float arithmetic https stackoverflow com questions 6563058 how do i use accurate float arithmetic in python https docs python org 3 library decimal html doctests for 2x2 inverse_of_matrix 2 5 2 0 0 0 0 5 0 2 0 2 inverse_of_matrix 2 5 5 1 2 traceback most recent call last valueerror this matrix has no inverse inverse_of_matrix 12 16 9 0 0 0 0 1111111111111111 0 0625 0 08333333333333333 inverse_of_matrix 12 3 16 8 0 16666666666666666 0 0625 0 3333333333333333 0 25 inverse_of_matrix 10 5 3 2 5 0 25 0 5 0 3 1 0 doctests for 3x3 inverse_of_matrix 2 5 7 2 0 1 1 2 3 2 0 5 0 4 0 1 0 1 0 1 0 5 0 12 0 10 0 inverse_of_matrix 1 2 2 1 2 2 3 2 1 traceback most recent call last valueerror this matrix has no inverse inverse_of_matrix traceback most recent call last valueerror please provide a matrix of size 2x2 or 3x3 inverse_of_matrix 1 2 3 4 5 6 traceback most recent call last valueerror please provide a matrix of size 2x2 or 3x3 inverse_of_matrix 1 2 1 0 3 4 traceback most recent call last valueerror please provide a matrix of size 2x2 or 3x3 inverse_of_matrix 1 2 3 7 8 9 7 8 9 traceback most recent call last valueerror this matrix has no inverse inverse_of_matrix 1 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 check if the provided matrix has 2 rows and 2 columns since this implementation only works for 2x2 matrices calculate the determinant of the matrix creates a copy of the matrix with swapped positions of the elements calculate the inverse of the matrix calculate the determinant of the matrix using sarrus rule creating cofactor matrix transpose the cofactor matrix adjoint matrix inverse of the matrix using the formula 1 determinant adjoint matrix calculate the inverse of the matrix
from __future__ import annotations from decimal import Decimal from numpy import array def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: d = Decimal if len(matrix) == 2 and len(matrix[0]) == 2 and len(matrix[1]) == 2: determinant = float( d(matrix[0][0]) * d(matrix[1][1]) - d(matrix[1][0]) * d(matrix[0][1]) ) if determinant == 0: raise ValueError("This matrix has no inverse.") swapped_matrix = [[0.0, 0.0], [0.0, 0.0]] swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0] swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1] return [ [(float(d(n)) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(matrix) == 3 and len(matrix[0]) == 3 and len(matrix[1]) == 3 and len(matrix[2]) == 3 ): determinant = float( ( (d(matrix[0][0]) * d(matrix[1][1]) * d(matrix[2][2])) + (d(matrix[0][1]) * d(matrix[1][2]) * d(matrix[2][0])) + (d(matrix[0][2]) * d(matrix[1][0]) * d(matrix[2][1])) ) - ( (d(matrix[0][2]) * d(matrix[1][1]) * d(matrix[2][0])) + (d(matrix[0][1]) * d(matrix[1][0]) * d(matrix[2][2])) + (d(matrix[0][0]) * d(matrix[1][2]) * d(matrix[2][1])) ) ) if determinant == 0: raise ValueError("This matrix has no inverse.") cofactor_matrix = [ [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], ] cofactor_matrix[0][0] = (d(matrix[1][1]) * d(matrix[2][2])) - ( d(matrix[1][2]) * d(matrix[2][1]) ) cofactor_matrix[0][1] = -( (d(matrix[1][0]) * d(matrix[2][2])) - (d(matrix[1][2]) * d(matrix[2][0])) ) cofactor_matrix[0][2] = (d(matrix[1][0]) * d(matrix[2][1])) - ( d(matrix[1][1]) * d(matrix[2][0]) ) cofactor_matrix[1][0] = -( (d(matrix[0][1]) * d(matrix[2][2])) - (d(matrix[0][2]) * d(matrix[2][1])) ) cofactor_matrix[1][1] = (d(matrix[0][0]) * d(matrix[2][2])) - ( d(matrix[0][2]) * d(matrix[2][0]) ) cofactor_matrix[1][2] = -( (d(matrix[0][0]) * d(matrix[2][1])) - (d(matrix[0][1]) * d(matrix[2][0])) ) cofactor_matrix[2][0] = (d(matrix[0][1]) * d(matrix[1][2])) - ( d(matrix[0][2]) * d(matrix[1][1]) ) cofactor_matrix[2][1] = -( (d(matrix[0][0]) * d(matrix[1][2])) - (d(matrix[0][2]) * d(matrix[1][0])) ) cofactor_matrix[2][2] = (d(matrix[0][0]) * d(matrix[1][1])) - ( d(matrix[0][1]) * d(matrix[1][0]) ) adjoint_matrix = array(cofactor_matrix) for i in range(3): for j in range(3): adjoint_matrix[i][j] = cofactor_matrix[j][i] inverse_matrix = array(cofactor_matrix) for i in range(3): for j in range(3): inverse_matrix[i][j] /= d(determinant) return [[float(d(n)) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("Please provide a matrix of size 2x2 or 3x3.")