Prompt
stringlengths
16
11.5k
Completions
stringlengths
84
25.3k
Integer Square Root Algorithm An efficient method to calculate the square root of a nonnegative integer 'num' rounded down to the nearest integer. It uses a binary search approach to find the integer square root without using any builtin exponent functions or operators. https:en.wikipedia.orgwikiIntegersquareroot ht...
def integer_square_root(num: int) -> int: """ Returns the integer square root of a non-negative integer num. Args: num: A non-negative integer. Returns: The integer square root of num. Raises: ValueError: If num is not an integer or is negative. >>> [integer_square_root(i...
An implementation of interquartile range IQR which is a measure of statistical dispersion, which is the spread of the data. The function takes the list of numeric values as input and returns the IQR. Script inspired by this Wikipedia article: https:en.wikipedia.orgwikiInterquartilerange This is the implementation of th...
from __future__ import annotations def find_median(nums: list[int | float]) -> float: """ This is the implementation of the median. :param nums: The list of numeric nums :return: Median of the list >>> find_median(nums=([1, 2, 2, 3, 4])) 2 >>> find_median(nums=([1, 2, 2, 3, 4, 4])) 2.5...
Returns whether num is a palindrome or not see for reference https:en.wikipedia.orgwikiPalindromicnumber. isintpalindrome121 False isintpalindrome0 True isintpalindrome10 False isintpalindrome11 True isintpalindrome101 True isintpalindrome120 False
def is_int_palindrome(num: int) -> bool: """ Returns whether `num` is a palindrome or not (see for reference https://en.wikipedia.org/wiki/Palindromic_number). >>> is_int_palindrome(-121) False >>> is_int_palindrome(0) True >>> is_int_palindrome(10) False >>> is_int_palindrome(1...
Is IP v4 address valid? A valid IP address must be four octets in the form of A.B.C.D, where A,B,C and D are numbers from 0254 for example: 192.168.23.1, 172.254.254.254 are valid IP address 192.168.255.0, 255.192.3.121 are invalid IP address print Valid IP address If IP is valid. or print Invalid IP address If IP is i...
def is_ip_v4_address_valid(ip_v4_address: str) -> bool: """ print "Valid IP address" If IP is valid. or print "Invalid IP address" If IP is invalid. >>> is_ip_v4_address_valid("192.168.0.23") True >>> is_ip_v4_address_valid("192.255.15.8") False >>> is_ip_v4_address_valid("172.100...
References: wikipedia:square free number psfblack : True ruff : True doctest: NORMALIZEWHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. issquarefree1, 1, 2, 3, 4 False These are wrong but should return some value it simply checks for repetition in the numbe...
from __future__ import annotations def is_square_free(factors: list[int]) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. >>> is_square_free([1, 1, 2, 3, 4]) False These are wrong but should ...
The Jaccard similarity coefficient is a commonly used indicator of the similarity between two sets. Let U be a set and A and B be subsets of U, then the Jaccard indexsimilarity is defined to be the ratio of the number of elements of their intersection and the number of elements of their union. Inspired from Wikipedia a...
def jaccard_similarity( set_a: set[str] | list[str] | tuple[str], set_b: set[str] | list[str] | tuple[str], alternative_union=False, ): """ Finds the jaccard similarity between two sets. Essentially, its intersection over union. The alternative way to calculate this is to take union as sum ...
Calculate joint probability distribution https:en.wikipedia.orgwikiJointprobabilitydistribution jointdistribution jointprobabilitydistribution ... 1, 2, 2, 5, 8, 0.7, 0.3, 0.3, 0.5, 0.2 ... from math import isclose isclosejointdistribution.pop1, 8, 0.14 True jointdistribution 1, 2: 0.21, 1, 5: 0.35, 2, 2: 0....
def joint_probability_distribution( x_values: list[int], y_values: list[int], x_probabilities: list[float], y_probabilities: list[float], ) -> dict: """ >>> joint_distribution = joint_probability_distribution( ... [1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2] ... ) >>> from ma...
The Josephus problem is a famous theoretical problem related to a certain countingout game. This module provides functions to solve the Josephus problem for numpeople and a stepsize. The Josephus problem is defined as follows: numpeople are standing in a circle. Starting with a specified person, you count around the ...
def josephus_recursive(num_people: int, step_size: int) -> int: """ Solve the Josephus problem for num_people and a step_size recursively. Args: num_people: A positive integer representing the number of people. step_size: A positive integer representing the step size for elimination. R...
Juggler Sequence Juggler sequence start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is floor value of square root of n . If n is odd, the next term is floor value of 3 time the square root of n. https:en.wikipedia.orgwikiJugglersequence Author : Akshay Dubey http...
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: """ >>> juggler_sequence(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be a positive integer >>> juggler_sequence(1) [1] >>...
Multiply two numbers using Karatsuba algorithm def karatsubaa: int, b: int int: if lenstra 1 or lenstrb 1: return a b m1 maxlenstra, lenstrb m2 m1 2 a1, a2 divmoda, 10m2 b1, b2 divmodb, 10m2 x karatsubaa2, b2 y karatsubaa1 a2, b1 b2 z karatsubaa1, b1 return z 10 2 m2 y z x 10 m2 x def main: prin...
def karatsuba(a: int, b: int) -> int: """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 ...
Finds k'th lexicographic permutation in increasing order of 0,1,2,...n1 in On2 time. Examples: First permutation is always 0,1,2,...n kthpermutation0,5 0, 1, 2, 3, 4 The order of permutation of 0,1,2,3 is 0,1,2,3, 0,1,3,2, 0,2,1,3, 0,2,3,1, 0,3,1,2, 0,3,2,1, 1,0,2,3, 1,0,3,2, 1,2,0,3, 1,2,3,0, 1,3,0,2 kthpermutation1...
def kth_permutation(k, n): """ Finds k'th lexicographic permutation (in increasing order) of 0,1,2,...n-1 in O(n^2) time. Examples: First permutation is always 0,1,2,...n >>> kth_permutation(0,5) [0, 1, 2, 3, 4] The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], ...
Author: Abhijeeth S Reduces large number to a more manageable number res5, 7 4.892790030352132 res0, 5 0 res3, 0 1 res1, 5 Traceback most recent call last: ... ValueError: math domain error We use the relation xy ylog10x, where 10 is the base. Read two numbers from input and typecast them to int using map function...
# Author: Abhijeeth S import math def res(x, y): """ Reduces large number to a more manageable number >>> res(5, 7) 4.892790030352132 >>> res(0, 5) 0 >>> res(3, 0) 1 >>> res(-1, 5) Traceback (most recent call last): ... ValueError: math domain error """ if 0 no...
Find the least common multiple of two numbers. Learn more: https:en.wikipedia.orgwikiLeastcommonmultiple leastcommonmultipleslow5, 2 10 leastcommonmultipleslow12, 76 228 Find the least common multiple of two numbers. https:en.wikipedia.orgwikiLeastcommonmultipleUsingthegreatestcommondivisor leastcommonmultiplefast5,...
import unittest from timeit import timeit from maths.greatest_common_divisor import greatest_common_divisor def least_common_multiple_slow(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> ...
Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths :param fnc: a function which defines a curve :param 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 accur...
from __future__ import annotations import math from collections.abc import Callable def line_length( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: """ Approximates the arc length of a line segment by treating the curve as a sequence of linear l...
Liouville Lambda Function The Liouville Lambda function, denoted by n and n is 1 if n is the product of an even number of prime numbers, and 1 if it is the product of an odd number of primes. https:en.wikipedia.orgwikiLiouvillefunction Author : Akshay Dubey https:github.comitsAkshayDubey This functions takes an intege...
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_factors import prime_factors def liouville_lambda(number: int) -> int: """ This functions takes an integer number as input. returns 1 if n has even number of prime factors and -1 otherwise. >>> liouville_lambda(10) 1 ...
In mathematics, the LucasLehmer test LLT is a primality test for Mersenne numbers. https:en.wikipedia.orgwikiLucasE28093Lehmerprimalitytest A Mersenne number is a number that is one less than a power of two. That is Mp 2p 1 https:en.wikipedia.orgwikiMersenneprime The LucasLehmer test is the primality test used by th...
# Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p ...
https:en.wikipedia.orgwikiLucasnumber Returns the nth lucas number recursivelucasnumber1 1 recursivelucasnumber20 15127 recursivelucasnumber0 2 recursivelucasnumber25 167761 recursivelucasnumber1.5 Traceback most recent call last: ... TypeError: recursivelucasnumber accepts only integer arguments. Returns the nth ...
def recursive_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> recursive_lucas_number(1) 1 >>> recursive_lucas_number(20) 15127 >>> recursive_lucas_number(0) 2 >>> recursive_lucas_number(25) 167761 >>> recursive_lucas_number(-1.5) Traceback (mos...
https:en.wikipedia.orgwikiTaylorseriesTrigonometricfunctions Finds the maclaurin approximation of sin :param theta: the angle to which sin is found :param accuracy: the degree of accuracy wanted minimum :return: the value of sine in radians from math import isclose, sin allisclosemaclaurinsinx, 50, sinx for x in rang...
from math import factorial, pi def maclaurin_sin(theta: float, accuracy: int = 30) -> float: """ Finds the maclaurin approximation of sin :param theta: the angle to which sin is found :param accuracy: the degree of accuracy wanted minimum :return: the value of sine in radians >>> from math ...
Expectts two list of numbers representing two points in the same ndimensional space https:en.wikipedia.orgwikiTaxicabgeometry manhattandistance1,1, 2,2 2.0 manhattandistance1.5,1.5, 2,2 1.0 manhattandistance1.5,1.5, 2.5,2 1.5 manhattandistance3, 3, 3, 0, 0, 0 9.0 manhattandistance1,1, None Traceback most recent ca...
def manhattan_distance(point_a: list, point_b: list) -> float: """ Expectts two list of numbers representing two points in the same n-dimensional space https://en.wikipedia.org/wiki/Taxicab_geometry >>> manhattan_distance([1,1], [2,2]) 2.0 >>> manhattan_distance([1.5,1.5], [2,2]) 1.0 ...
Matrix Exponentiation import timeit class Matrix: def initself, arg: if isinstancearg, list: Initializes a matrix identical to the one provided. self.t arg self.n lenarg else: Initializes a square matrix of the given size and set values to zero. self.n arg self.t 0 for in rangeself.n for in rangeself.n def mu...
import timeit """ Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time. You read more about it here: https://zobayer.blogspot.com/2010/11/matrix-exponentiation.html https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/ """ class Matrix: def __init__(self, arg): ...
Given an array of integer elements and an integer 'k', we are required to find the maximum sum of 'k' consecutive elements in the array. Instead of using a nested for loop, in a Brute force approach we will use a technique called 'Window sliding technique' where the nested loops can be converted to a single loop to red...
from __future__ import annotations def max_sum_in_array(array: list[int], k: int) -> int: """ Returns the maximum sum of k consecutive elements >>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] >>> k = 4 >>> max_sum_in_array(arr, k) 24 >>> k = 10 >>> max_sum_in_array(arr,k) Traceback (most r...
medianoftwoarrays1, 2, 3 2 medianoftwoarrays0, 1.1, 2.5, 1 0.5 medianoftwoarrays, 2.5, 1 1.75 medianoftwoarrays, 0 0 medianoftwoarrays, Traceback most recent call last: ... IndexError: list index out of range
from __future__ import annotations def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) ...
This function calculates the Minkowski distance for a given order between two ndimensional points represented as lists. For the case of order 1, the Minkowski distance degenerates to the Manhattan distance. For order 2, the usual Euclidean distance is obtained. https:en.wikipedia.orgwikiMinkowskidistance Note: due to...
def minkowski_distance( point_a: list[float], point_b: list[float], order: int, ) -> float: """ This function calculates the Minkowski distance for a given order between two n-dimensional points represented as lists. For the case of order = 1, the Minkowski distance degenerates to the Manhat...
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...
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def mobius(n: int) -> int: """ Mobius function >>> mobius(24) 0 >>> mobius(-1) 1 >>> mobius('asd') Traceback (most recent call last): ... TypeError: '<=' not supported between inst...
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...
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the...
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...
"""Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 wh...
author: 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...
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def pi_estimator(iterations: int): """ 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...
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 proba...
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): """Initialize a six sided dice""" self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def throw_dice(num_throws: int, num_dice: int = 2) ...
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 n...
import math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 >>> num_digits('123') # Raises a TypeEr...
Use the AdamsBashforth methods to solve Ordinary Differential Equations. https:en.wikipedia.orgwikiLinearmultistepmethod Author : 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 valu...
from collections.abc import Callable from dataclasses import dataclass import numpy as np @dataclass class AdamsBashforth: """ args: func: An ordinary differential equation (ODE) as function of x and y. x_initials: List containing initial required values of x. y_initials: List containing initial ...
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 b...
from collections.abc import Callable def bisection(function: Callable[[float], float], a: float, b: float) -> float: """ finds where function becomes 0 in [a,b] using bolzano >>> bisection(lambda x: x ** 3 - 1, -5, 5) 1.0000000149011612 >>> bisection(lambda x: x ** 3 - 1, 2, 1000) Traceback (m...
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 equati...
def equation(x: float) -> float: """ >>> equation(5) -15 >>> equation(0) 10 >>> equation(-5) -15 >>> equation(0.1) 9.99 >>> equation(-0.1) 9.99 """ return 10 - x * x def bisection(a: float, b: float) -> float: """ >>> bisection(-2, 5) 3.1611328125 >>...
Author : 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....
# constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a x...
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....
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: """ function is the f we want to find its root x0 and x1 are two random starting points >>> intersection(lambda x: x ** 3 - 1, -5, 5) 0.9999999999954654 >>> int...
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 Inte...
def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: """ Interpolate and evaluate a polynomial using Neville's method. Arguments: x_points, y_points: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x...
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/ from __future__ import annotations import math # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ t...
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...
from collections.abc import Callable RealFunc = Callable[[float], float] def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: """ Approximate the derivative of a function f(x) at a point x using the finite difference method >>> import math >>> tolerance = 1e-5 >>> deri...
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 o...
from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form ...
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...
import numpy as np def runge_kutta(f, y0, x0, h, x_end): """ Calculate the numeric solution at each step to the ODE f(x, y) using RK4 https://en.wikipedia.org/wiki/Runge-Kutta_methods Arguments: f -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value f...
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 in...
from collections.abc import Callable import numpy as np def runge_kutta_fehlberg_45( func: Callable, x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: """ Solve an Ordinary Differential Equations using Runge-Kutta-Fehlberg Method (rkf45) of order 5...
Use the RungeKuttaGill's method of order 4 to solve Ordinary Differential Equations. https:www.geeksforgeeks.orggills4thordermethodtosolvedifferentialequations Author : Ravi Kumar Solve an Ordinary Differential Equations using RungeKuttaGills Method of order 4. args: func: An ordinary differential equation ODE as funct...
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: """ Solve an Ordinary Differential Equations using Runge-Kutta...
Implementing Secant method in Python Author: dimgrichr f5 39.98652410600183 secantmethod1, 3, 2 0.2139409276214589
from math import exp def f(x: float) -> float: """ >>> f(5) 39.98652410600183 """ return 8 * x - 2 * exp(-x) def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float: """ >>> secant_method(1, 3, 2) 0.2139409276214589 """ x0 = lower_bound x1 = upper...
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:...
def method_2(boundary: list[int], steps: int) -> float: # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) """ Calculate the definite integral of a function using Simpson's Rule. :param boundary: A list containing the lower and upper bounds of integration. :param steps:...
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 squ...
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...
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...
from itertools import compress, repeat from math import ceil, sqrt def odd_sieve(num: int) -> list[int]: """ Returns the prime numbers < `num`. The prime numbers are calculated using an odd sieve implementation of the Sieve of Eratosthenes algorithm (see for reference https://en.wikipedia.org/wiki/Sie...
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 Trace...
def perfect_cube(n: int) -> bool: """ Check if a number is a perfect cube or not. >>> perfect_cube(27) True >>> perfect_cube(4) False """ val = n ** (1 / 3) return (val * val * val) == n def perfect_cube_binary_search(n: int) -> bool: """ Check if a number is a perfect cub...
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.wikipe...
def perfect(number: int) -> bool: """ Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Args: number: The number to be checked. Returns: True if the number is a perfect number other...
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 compl...
import math def perfect_square(num: int) -> bool: """ Check if a number is perfect square number or not :param num: the number to be checked :return: True if number is square number, otherwise False >>> perfect_square(9) True >>> perfect_square(16) True >>> perfect_square(1) T...
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...
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multi...
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 interru...
def calculate_pi(limit: int) -> str: """ https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 Leibniz Formula for Pi The Leibniz formula is the special case arctan(1) = pi / 4. Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence (https://en.wikipedi...
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...
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: """ True, if the point lies in the unit circle False, otherwise """ return (self.x**2 + self.y**2) <= 1 @classmeth...
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 cros...
Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: """ Pass two points to get the vector from them in the form (x, y, z). >>> create_vector((0, 0, 0), (1, 1, 1)) (1, 1, 1) >>> create_vector((45, 70, 2...
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 gua...
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: """ Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. The returned factor may be composite and require further factoriza...
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 me...
from collections.abc import Sequence def evaluate_poly(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial f(x) at specified point x and return the value. Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at whic...
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 nu...
from __future__ import annotations from collections.abc import MutableSequence class Polynomial: def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None: """ The coefficients should be in order of degree, from smallest to largest. >>> p = Polynomial(2, [1, 2, 3]) ...
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 ...
def power(base: int, exponent: int) -> float: """ Calculate the power of a base raised to an exponent. >>> power(3, 4) 81 >>> power(2, 0) 1 >>> all(power(base, exponent) == pow(base, exponent) ... for base in range(-10, 10) for exponent in range(10)) True >>> power('a', 1) ...
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 eve...
import math import unittest import pytest def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) ...
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 ...
from __future__ import annotations def prime_factors(n: int) -> list[int]: """ Returns prime factors of n as a list. >>> prime_factors(0) [] >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(2560) [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] >>> prime_factors(10**-2) [] >>> prime_fa...
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. listpr...
import math from collections.abc import Generator def slow_primes(max_n: int) -> Generator[int, None, None]: """ 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...
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 primesieveeratosthenes...
def prime_sieve_eratosthenes(num: int) -> list[int]: """ Print the prime numbers up to n >>> prime_sieve_eratosthenes(10) [2, 3, 5, 7] >>> prime_sieve_eratosthenes(20) [2, 3, 5, 7, 11, 13, 17, 19] >>> prime_sieve_eratosthenes(2) [2] >>> prime_sieve_eratosthenes(1) [] >>> pri...
Created on Thu Oct 5 16:44:23 2017 author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: isprimenumber sieveerN getprimenumbersN primefactorizationnumber greatestprimefactornumber smallestprimefactornumber getprimen getprimesbetweenpNumber1,...
from math import sqrt from maths.greatest_common_divisor import gcd_by_iterative def is_prime(number: int) -> bool: """ input: positive integer 'number' returns true if 'number' is prime otherwise false. >>> is_prime(3) True >>> is_prime(10) False >>> is_prime(97) True >>> is...
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
def multiplication_table(number: int, number_of_terms: int) -> str: """ Prints the multiplication table of a given number till the given number of terms >>> print(multiplication_table(3, 5)) 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 >>> print(multiplication_table(-4, 6)) ...
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 mai...
import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5...
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 Householde...
import numpy as np def qr_householder(a: np.ndarray): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the ma...
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
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -...
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
from math import pi def radians(degree: float) -> float: """ Converts the given angle from degrees to radians https://en.wikipedia.org/wiki/Radian >>> radians(180) 3.141592653589793 >>> radians(92) 1.6057029118347832 >>> radians(274) 4.782202150464463 >>> radians(109.82) 1...
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 al...
import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complex...
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...
def remove_digit(num: int) -> int: """ returns the biggest possible result that can be achieved by removing one digit from the given number >>> remove_digit(152) 52 >>> remove_digit(6385) 685 >>> remove_digit(-11) 1 >>> remove_digit(2222222) 222222 >>> remove_digit(...
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 ranges...
import math def sieve(n: int) -> list[int]: """ Segmented Sieve. Examples: >>> sieve(8) [2, 3, 5, 7] >>> sieve(27) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> sieve(0) Traceback (most recent call last): ... ValueError: Number 0 must instead be a positive integer >>> si...
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,...
def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback...
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...
def is_geometric_series(series: list) -> bool: """ 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 ...
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 G...
from __future__ import annotations def geometric_series( nth_term: float, start_term_a: float, common_ratio_r: float, ) -> list[float]: """ Pure Python implementation of Geometric Series algorithm :param nth_term: The last term (nth term of Geometric Series) :param start_term_a : The firs...
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 isha...
def is_harmonic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_harmonic_series([ 1, 2/3, 1/2, 2/5, 1/3]) True >>> is_harmonic_series([ 1, 2/3, 2/5, 1/3]) False >>> is_harmonic_series([1, 2, 3]) False >>> is_harmonic_series([1/2,...
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 Harm...
def harmonic_series(n_term: str) -> list: """Pure Python implementation of Harmonic Series algorithm :param n_term: The last (nth) term of Harmonic Series :return: The Harmonic Series starting from 1 to last (nth) term Examples: >>> harmonic_series(5) ['1', '1/2', '1/3', '1/4', '1/5'] >>> ...
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 sequen...
def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0...
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:...
from __future__ import annotations def p_series(nth_term: float | str, power: float | str) -> list[str]: """ 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'] >>...
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 http...
from __future__ import annotations import math def prime_sieve(num: int) -> list[int]: """ Returns a list with all prime numbers up to n. >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] >>> prime_sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> prime_sieve(10) ...
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.orgwikiSigmoid...
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: """ Implements the sigmoid function Parameters: vector (np.array): A numpy array of shape (1,n) consisting of real values Returns: sigmoid_vec (np.array): The input numpy array, after applying sigmoid....
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' si...
def signum(num: float) -> int: """ Applies signum function on the number Custom test cases: >>> signum(-10) -1 >>> signum(10) 1 >>> signum(0) 0 >>> signum(-20.5) -1 >>> signum(20.5) 1 >>> signum(-1e-6) -1 >>> signum(1e-6) 1 >>> signum("Hello") ...
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...
def simplify(current_set: list[list]) -> list[list]: """ >>> simplify([[1, 2, 3], [4, 5, 6]]) [[1.0, 2.0, 3.0], [0.0, 0.75, 1.5]] >>> simplify([[5, 2, 5], [5, 1, 10]]) [[1.0, 0.4, 1.0], [0.0, 0.2, -1.0]] """ # Divide each row by magnitude of first term --> creates 'unit' matrix duplicate...
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....
from math import factorial, radians def sin( angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10 ) -> float: """ Implement sin function. >>> sin(0.0) 0.0 >>> sin(90.0) 1.0 >>> sin(180.0) 0.0 >>> sin(270.0) -1.0 >>> sin(0.68) 0.0118679603 ...
sockmerchant10, 20, 20, 10, 10, 30, 50, 10, 20 3 sockmerchant1, 1, 3, 3 2
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": i...
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 ...
import numpy as np def softmax(vector): """ Implements the softmax function Parameters: vector (np.array,list,tuple): A numpy array of shape (1,n) consisting of real values or a similar list,tuple Returns: softmax_vec (np.array): The input numpy array after applying ...
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 th...
import random def jacobi_symbol(random_a: int, number: int) -> int: """ Calculate the Jacobi symbol. The Jacobi symbol is a generalization of the Legendre symbol, which can be used to simplify computations involving quadratic residues. The Jacobi symbol is used in primality tests, like the Solovay...
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 represen...
from collections.abc import Sequence def assign_ranks(data: Sequence[float]) -> list[int]: """ Assigns ranks to elements in the array. :param data: List of floats. :return: List of ints representing the ranks. Example: >>> assign_ranks([3.2, 1.5, 4.0, 2.7, 5.1]) [3, 1, 4, 2, 5] >>> ...
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.orgA00...
PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) def armstrong_number(n: int) -> bool: """ Return True if n is an Armstrong number or False if it is not. >>> all(armstrong_number(n) for n in PASSING) True...
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 Author : Akshay Dubey https:github.comitsAkshayDubey Time Complexity : Ol...
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. >>> is_automorphic_number(-1) ...
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 f...
def bell_numbers(max_set_length: int) -> list[int]: """ Calculate Bell numbers for the sets of lengths from 0 to max_set_length. In other words, calculate first (max_set_length + 1) Bell numbers. Args: max_set_length (int): The maximum length of the sets for which Bell numbers are calcu...
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.orgwikiCarmichaelnumbe...
from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: """ Examples: >>> power(2, 15, 3) 2 >>> power(5, 1, 30) 5 """ if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 ==...
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...
def catalan(number: int) -> int: """ :param number: nth catalan number to calculate :return: the nth catalan number Note: A catalan number is only defined for positive integers >>> catalan(5) 14 >>> catalan(0) Traceback (most recent call last): ... ValueError: Input value of...
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. I...
def hamming(n_element: int) -> list: """ This function creates an ordered list of n length as requested, and afterwards returns the last value of the list. It must be given a positive integer. :param n_element: The number of elements on the list :return: The nth element of the list >>> hamming...
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 ishappynum...
def is_happy_number(number: int) -> bool: """ 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) ...
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' inttobase5...
def int_to_base(number: int, base: int) -> str: """ Convert a given positive decimal integer to base 'base'. Where 'base' ranges from 2 to 36. Examples: >>> int_to_base(23, 2) '10111' >>> int_to_base(58, 5) '213' >>> int_to_base(167, 16) 'A7' >>> # bases below 2 and beyond 3...
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 Author : Akshay Dubey https:github.comitsAksha...
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def hexagonal(number: int) -> int: """ :param number: nth hexagonal number to calculate :return: the nth hexagonal number Note: A hexagonal number is only defined for positive integers >>> hexagonal(4) 28 >>> hexagonal(11) 231...
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 ...
def factorial(digit: int) -> int: """ >>> factorial(3) 6 >>> factorial(0) 1 >>> factorial(5) 120 """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: """ >>> krishnamurthy(145) True >>> krishnamurthy(240) F...
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.wikipe...
def perfect(number: int) -> bool: """ Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Args: number: The number to be checked. Returns: True if the number is a perfect number, Fals...
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 s...
def polygonal_num(num: int, sides: int) -> int: """ 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) ...
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 Author : Akshay Dubey https:github.comitsAkshayDubey doctest: NORMALIZEWHITESPACE This functions takes a...
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def is_pronic(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is pronic. >>> is_pronic(-1) False >>> is_pronic(0) True >>> is_pronic(2)...
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...
import math def proth(number: int) -> int: """ :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): ...