function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def find_max(nums: list[int | float]) -> int | float: if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num
maths
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) # formula for sum of series return total
maths
def main(): print(sum_of_series(1, 1, 10))
maths
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]: try: decimal = float(decimal) except ValueError: raise ValueError("Please enter a valid number") fractional_part = decimal - int(decimal) if fractional_part == 0: return int(decimal), 1 else: number_of_frac_digits = len(str(decimal).split(".")[1]) numerator = int(decimal * (10**number_of_frac_digits)) denominator = 10**number_of_frac_digits divisor, dividend = denominator, numerator while True: remainder = dividend % divisor if remainder == 0: break dividend, divisor = divisor, remainder numerator, denominator = numerator / divisor, denominator / divisor return int(numerator), int(denominator)
maths
def greatest_common_divisor(a: int, b: int) -> int: return abs(b) if a == 0 else greatest_common_divisor(b % a, a)
maths
def gcd_by_iterative(x: int, y: int) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x)
maths
def main(): try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input")
maths
def n31(a: int) -> tuple[list[int], int]: if not isinstance(a, int): raise TypeError(f"Must be int, not {type(a).__name__}") if a < 1: raise ValueError(f"Given integer must be positive, not {a}") path = [a] while a != 1: if a % 2 == 0: a //= 2 else: a = 3 * a + 1 path.append(a) return path, len(path)
maths
def test_n31(): assert n31(4) == ([4, 2, 1], 3) assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15) assert n31(31) == ( [ 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, ], 107, )
maths
def signum(num: float) -> int: if num < 0: return -1 return 1 if num else 0
maths
def test_signum() -> None: assert signum(5) == 1 assert signum(-5) == -1 assert signum(0) == 0
maths
def add(first: int, second: int) -> int: while second != 0: c = first & second first ^= second second = c << 1 return first
maths
def get_factors( number: int, factors: Counter | None = None, factor: int = 2 ) -> Counter: match number: case int(number) if number == 1: return Counter({1: 1}) case int(num) if number > 0: number = num case _: raise TypeError("number must be integer and greater than zero") factors = factors or Counter() if number == factor: # break condition # all numbers are factors of itself factors[factor] += 1 return factors if number % factor > 0: # if it is greater than zero # so it is not a factor of number and we check next number return get_factors(number, factors, factor + 1) factors[factor] += 1 # else we update factors (that is Counter(dict-like) type) and check again return get_factors(number // factor, factors, factor)
maths
def get_greatest_common_divisor(*numbers: int) -> int: # we just need factors, not numbers itself try: same_factors, *factors = map(get_factors, numbers) except TypeError as e: raise Exception("numbers must be integer and greater than zero") from e for factor in factors: same_factors &= factor # get common factor between all # `&` return common elements with smaller value (for Counter type) # now, same_factors is something like {2: 2, 3: 4} that means 2 * 2 * 3 * 3 * 3 * 3 mult = 1 # power each factor and multiply # for {2: 2, 3: 4}, it is [4, 81] and then 324 for m in [factor**power for factor, power in same_factors.items()]: mult *= m return mult
maths
def average_absolute_deviation(nums: list[int]) -> float: if not nums: # Makes sure that the list is not empty raise ValueError("List is empty") average = sum(nums) / len(nums) # Calculate the average return sum(abs(x - average) for x in nums) / len(nums)
maths
def gamma(num: float) -> float: if num <= 0: raise ValueError("math domain error") if num > 171.5: raise OverflowError("math range error") elif num - int(num) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer") elif num == 0.5: return sqrt(pi) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1)
maths
def test_gamma() -> None: assert gamma(0.5) == sqrt(pi) assert gamma(1) == 1.0 assert gamma(2) == 1.0
maths
def jaccard_similarity(set_a, set_b, alternative_union=False): if isinstance(set_a, set) and isinstance(set_b, set): intersection = len(set_a.intersection(set_b)) if alternative_union: union = len(set_a) + len(set_b) else: union = len(set_a.union(set_b)) return intersection / union if isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)): intersection = [element for element in set_a if element in set_b] if alternative_union: union = len(set_a) + len(set_b) return len(intersection) / union else: union = set_a + [element for element in set_b if element not in set_a] return len(intersection) / len(union) return len(intersection) / len(union) return None
maths
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(0, len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps
maths
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(0, len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps
maths
def proth(number: int) -> int: if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError(f"Input value of [number={number}] must be > 0") 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]
maths
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}
maths
def is_prime_big(n, prec=1000): if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd d = n - 1 exp = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) count = 0 while count < prec: a = random.randint(2, n - 1) b = bin_exp_mod(a, d, n) if b != 1: flag = True for _ in range(exp): if b == n - 1: flag = False break b = b * b b %= n if flag: return False count += 1 return True
maths
def sigmoid(vector: np.array) -> np.array: return 1 / (1 + np.exp(-vector))
maths
def sigmoid_linear_unit(vector: np.array) -> np.array: return vector * sigmoid(vector)
maths
def is_prime(number: int) -> bool: # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2, int(round(sqrt(number))) + 1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status, bool), "'status' must been from type bool" return status
maths
def sieve_er(n): # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(begin_list)): for j in range(i + 1, len(begin_list)): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 # filters actual prime numbers. ans = [x for x in begin_list if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans
maths
def get_prime_numbers(n): # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1): if is_prime(number): ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans
maths
def prime_factorization(number): # precondition assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number == 0 or number == 1: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(number): while quotient != 1: if is_prime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans
maths
def greatest_prime_factor(number): # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = max(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans
maths
def smallest_prime_factor(number): # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = min(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans
maths
def is_even(number): # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number % 2 == 0
maths
def is_odd(number): # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2 != 0
maths
def goldbach(number): # precondition assert ( isinstance(number, int) and (number > 2) and is_even(number) ), "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < len_pn and loop: j = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) ans.append(prime_numbers[j]) j += 1 i += 1 # precondition assert ( isinstance(ans, list) and (len(ans) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0]) and is_prime(ans[1]) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans
maths
def gcd(number1, number2): # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 0) and (number2 >= 0) ), "'number1' and 'number2' must been positive integer." rest = 0 while number2 != 0: rest = number1 % number2 number1 = number2 number2 = rest # precondition assert isinstance(number1, int) and ( number1 >= 0 ), "'number' must been from type int and positive" return number1
maths
def kg_v(number1, number2): # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_1: if n not in done: if n in prime_fac_2: count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) for _ in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in prime_fac_2: if n not in done: count2 = prime_fac_2.count(n) for _ in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans, int) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans
maths
def get_prime(n): # precondition assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(ans): ans += 1 # precondition assert isinstance(ans, int) and is_prime( ans ), "'ans' must been a prime number and from type int" return ans
maths
def get_primes_between(p_number_1, p_number_2): # precondition assert ( is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = p_number_1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(number): number += 1 while number < p_number_2: ans.append(number) number += 1 # fetch the next prime number. while not is_prime(number): number += 1 # precondition assert ( isinstance(ans, list) and ans[0] != p_number_1 and ans[len(ans) - 1] != p_number_2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans
maths
def get_divisors(n): # precondition assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) # precondition assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans
maths
def is_perfect_number(number): # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = get_divisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number
maths
def simplify_fraction(numerator, denominator): # precondition assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcd_of_fraction = gcd(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcd_of_fraction, int) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
maths
def factorial(n): # precondition assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1, n + 1): ans *= factor return ans
maths
def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: # base cases if abs(a) == 1: return a, 0 elif abs(b) == 1: return 0, b old_remainder, remainder = a, b old_coeff_a, coeff_a = 1, 0 old_coeff_b, coeff_b = 0, 1 while remainder != 0: quotient = old_remainder // remainder old_remainder, remainder = remainder, old_remainder - quotient * remainder old_coeff_a, coeff_a = coeff_a, old_coeff_a - quotient * coeff_a old_coeff_b, coeff_b = coeff_b, old_coeff_b - quotient * coeff_b # sign correction for negative numbers if a < 0: old_coeff_a = -old_coeff_a if b < 0: old_coeff_b = -old_coeff_b return old_coeff_a, old_coeff_b
maths
def liouville_lambda(number: int) -> int: if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError("Input must be a positive integer") return -1 if len(prime_factors(number)) % 2 else 1
maths
def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str: if (not isinstance(digit_position, int)) or (digit_position <= 0): raise ValueError("Digit position must be a positive integer") elif (not isinstance(precision, int)) or (precision < 0): raise ValueError("Precision must be a nonnegative integer") # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly # accurate sum_result = ( 4 * _subsum(digit_position, 1, precision) - 2 * _subsum(digit_position, 4, precision) - _subsum(digit_position, 5, precision) - _subsum(digit_position, 6, precision) ) # return the first hex digit of the fractional part of the result return hex(int((sum_result % 1) * 16))[2:]
maths
def _subsum( digit_pos_to_extract: int, denominator_addend: int, precision: int ) -> float: # only care about first digit of fractional part; don't need decimal total = 0.0 for sum_index in range(digit_pos_to_extract + precision): denominator = 8 * sum_index + denominator_addend if sum_index < digit_pos_to_extract: # if the exponential term is an integer and we mod it by the denominator # before dividing, only the integer part of the sum will change; # the fractional part will not exponential_term = pow( 16, digit_pos_to_extract - 1 - sum_index, denominator ) else: exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index) total += exponential_term / denominator return total
maths
def max_sub_array_sum(a: list, size: int = 0): size = size or len(a) max_so_far = -maxsize - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] max_so_far = max(max_so_far, max_ending_here) max_ending_here = max(max_ending_here, 0) return max_so_far
maths
def add(a: float, b: float) -> float: return a + b
maths
def zeller(date_input: str) -> str: # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response
maths
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) )
maths
def lucas_lehmer_test(p: int) -> bool: if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 m = (1 << p) - 1 for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0
maths
def factors_of_a_number(num: int) -> list: facs: list[int] = [] if num < 1: return facs facs.append(1) if num == 1: return facs facs.append(num) for i in range(2, int(sqrt(num)) + 1): if num % i == 0: # If i is a factor of num facs.append(i) d = num // i # num//i is the other factor of num if d != i: # If d and i are distinct facs.append(d) # we have found another factor facs.sort() return facs
maths
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, )
maths
def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}")
maths
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
maths
def perfect(number: int) -> bool: return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number
maths
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]
maths
def bin_exp_mod(a, n, b): # mod b assert b != 0, "This cannot accept modulo that is == 0" if n == 0: return 1 if n % 2 == 1: return (bin_exp_mod(a, n - 1, b) * a) % b r = bin_exp_mod(a, n / 2, b) return (r * r) % b
maths
def binary_exponentiation(a, n, mod): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod
maths
def sigmoid(vector: np.array) -> np.array: return 1 / (1 + np.exp(-vector))
maths
def gaussian_error_linear_unit(vector: np.array) -> np.array: return vector * sigmoid(1.702 * vector)
maths
def power(base: int, exponent: int) -> float: return base * power(base, (exponent - 1)) if exponent else 1
maths
def catalan(number: int) -> int: if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError(f"Input value of [number={number}] must be > 0") current_number = 1 for i in range(1, number): current_number *= 4 * i - 2 current_number //= i + 1 return current_number
maths
def negative_exist(arr: list) -> int: arr = arr or [0] max_number = arr[0] for i in arr: if i >= 0: return 0 elif max_number <= i: max_number = i return max_number
maths
def kadanes(arr: list) -> int: max_sum = negative_exist(arr) if max_sum < 0: return max_sum max_sum = 0 max_till_element = 0 for i in arr: max_till_element += i max_sum = max(max_sum, max_till_element) max_till_element = max(max_till_element, 0) return max_sum
maths
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)
maths
def abundant(n: int) -> bool: return sum(factors(n)) > n
maths
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
maths
def weird(number: int) -> bool: return abundant(number) and not semi_perfect(number)
maths
def twin_prime(number: int) -> int: if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if is_prime(number) and is_prime(number + 2): return number + 2 else: return -1
maths
def f(x: float) -> float: return x * x
maths
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}" # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function 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)
maths
def __init__(self):
maths
def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: n = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y
maths
def double_factorial(n: int) -> int: if not isinstance(n, int): raise ValueError("double_factorial() only accepts integral values") if n < 0: raise ValueError("double_factorial() not defined for negative values") return 1 if n <= 1 else n * double_factorial(n - 2)
maths
def qr_householder(a): m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): # select a column of modified matrix A': x = r[k:, [k]] # construct first basis vector e1 = np.zeros_like(x) e1[0] = 1.0 # determine scaling factor alpha = np.linalg.norm(x) # construct vector v for Householder reflection v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) # construct the Householder matrix q_k = np.eye(m - k) - 2.0 * v @ v.T # pad with ones and zeros as necessary q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]]) q = q @ q_k.T r = q_k @ r return q, r
maths
def max_sum_in_array(array: list[int], k: int) -> int: if len(array) < k or k < 0: raise ValueError("Invalid Input") max_sum = current_sum = sum(array[:k]) for i in range(len(array) - k): current_sum = current_sum - array[i] + array[i + k] max_sum = max(max_sum, current_sum) return max_sum
maths
def make_dataset() -> tuple[list[int], int]: arr = [randint(-1000, 1000) for i in range(10)] r = randint(-5000, 5000) return (arr, r)
maths
def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]: for triplet in permutations(arr, 3): if sum(triplet) == target: return tuple(sorted(triplet)) return (0, 0, 0)
maths
def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]: arr.sort() n = len(arr) for i in range(n - 1): left, right = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0)
maths
def solution_times() -> tuple[float, float]: times1 = repeat(setup=setup_code, stmt=test_code1, repeat=5, number=10000) times2 = repeat(setup=setup_code, stmt=test_code2, repeat=5, number=10000) return (min(times1), min(times2))
maths
def mobius(n: int) -> int: factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0
maths
def floor(x: float) -> int: return int(x) if x - int(x) >= 0 else int(x) - 1
maths
def maclaurin_sin(theta: float, accuracy: int = 30) -> float: if not isinstance(theta, (int, float)): raise ValueError("maclaurin_sin() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1) for r in range(accuracy) )
maths
def maclaurin_cos(theta: float, accuracy: int = 30) -> float: if not isinstance(theta, (int, float)): raise ValueError("maclaurin_cos() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy))
maths
def recursive_lucas_number(n_th_number: int) -> int: if not isinstance(n_th_number, int): raise TypeError("recursive_lucas_number accepts only integer arguments.") if n_th_number == 0: return 2 if n_th_number == 1: return 1 return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number( n_th_number - 2 )
maths
def dynamic_lucas_number(n_th_number: int) -> int: if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 for _ in range(n_th_number): a, b = b, a + b return a
maths
def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x**2) + (y**2)) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1
maths
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)
maths
def identity_function(x: float) -> float: return x
maths
def function_to_integrate(x: float) -> float: return sqrt(4.0 - x * x)
maths
def is_square_free(factors: list[int]) -> bool: return len(set(factors)) == len(factors)
maths
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]
maths
def evaluate_poly(poly: Sequence[float], x: float) -> float: return sum(c * (x**i) for i, c in enumerate(poly))
maths
def horner(poly: Sequence[float], x: float) -> float: result = 0.0 for coeff in reversed(poly): result = result * x + coeff return result
maths
def ceil(x: float) -> int: return int(x) if x - int(x) <= 0 else int(x) + 1
maths
def __init__(self, poly_a=None, poly_b=None): # Input as list self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] # Remove leading zero coefficients 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) # Add 0 to make lengths equal a power of 2 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) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) # The product self.product = self.__multiply()
maths
def __dft(self, which): dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] # Corner case 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 # First half of next step 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 # Second half of next step 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 # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0]
maths
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 # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT 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 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions 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 # Update inverce_c = new_inverse_c next_ncol *= 2 # Unpack inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c
maths
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 "\n".join((a, b, c))
maths