function
stringlengths 18
3.86k
| intent_category
stringlengths 5
24
|
---|---|
def allocation_num(number_of_bytes: int, partitions: int) -> list[str]:
if partitions <= 0:
raise ValueError("partitions must be a positive number!")
if partitions > number_of_bytes:
raise ValueError("partitions can not > number_of_bytes!")
bytes_per_partition = number_of_bytes // partitions
allocation_list = []
for i in range(partitions):
start_bytes = i * bytes_per_partition + 1
end_bytes = (
number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
)
allocation_list.append(f"{start_bytes}-{end_bytes}")
return allocation_list | maths |
def sylvester(number: int) -> int:
assert isinstance(number, int), f"The input value of [n={number}] is not an integer"
if number == 1:
return 2
elif number < 1:
raise ValueError(f"The input value of [n={number}] has to be > 0")
else:
num = sylvester(number - 1)
lower = num - 1
upper = num
return lower * upper + 1 | maths |
def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float:
all_numbers = sorted(nums1 + nums2)
div, mod = divmod(len(all_numbers), 2)
if mod == 1:
return all_numbers[div]
else:
return (all_numbers[div] + all_numbers[div - 1]) / 2 | maths |
def hamming(n_element: int) -> list:
n_element = int(n_element)
if n_element < 1:
my_error = ValueError("a should be a positive number")
raise my_error
hamming_list = [1]
i, j, k = (0, 0, 0)
index = 1
while index < n_element:
while hamming_list[i] * 2 <= hamming_list[-1]:
i += 1
while hamming_list[j] * 3 <= hamming_list[-1]:
j += 1
while hamming_list[k] * 5 <= hamming_list[-1]:
k += 1
hamming_list.append(
min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5)
)
index += 1
return hamming_list | maths |
def euler_modified(
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
) -> np.array:
n = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((n + 1,))
y[0] = y0
x = x0
for k in range(n):
y_get = y[k] + step_size * ode_func(x, y[k])
y[k + 1] = y[k] + (
(step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get))
)
x += step_size
return y | maths |
def vol_cube(side_length: int | float) -> float:
if side_length < 0:
raise ValueError("vol_cube() only accepts non-negative values")
return pow(side_length, 3) | maths |
def vol_spherical_cap(height: float, radius: float) -> float:
if height < 0 or radius < 0:
raise ValueError("vol_spherical_cap() only accepts non-negative values")
# Volume is 1/3 pi * height squared * (3 * radius - height)
return 1 / 3 * pi * pow(height, 2) * (3 * radius - height) | maths |
def vol_spheres_intersect(
radius_1: float, radius_2: float, centers_distance: float
) -> float:
if radius_1 < 0 or radius_2 < 0 or centers_distance < 0:
raise ValueError("vol_spheres_intersect() only accepts non-negative values")
if centers_distance == 0:
return vol_sphere(min(radius_1, radius_2))
h1 = (
(radius_1 - radius_2 + centers_distance)
* (radius_1 + radius_2 - centers_distance)
/ (2 * centers_distance)
)
h2 = (
(radius_2 - radius_1 + centers_distance)
* (radius_2 + radius_1 - centers_distance)
/ (2 * centers_distance)
)
return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1) | maths |
def vol_spheres_union(
radius_1: float, radius_2: float, centers_distance: float
) -> float:
if radius_1 <= 0 or radius_2 <= 0 or centers_distance < 0:
raise ValueError(
"vol_spheres_union() only accepts non-negative values, non-zero radius"
)
if centers_distance == 0:
return vol_sphere(max(radius_1, radius_2))
return (
vol_sphere(radius_1)
+ vol_sphere(radius_2)
- vol_spheres_intersect(radius_1, radius_2, centers_distance)
) | maths |
def vol_cuboid(width: float, height: float, length: float) -> float:
if width < 0 or height < 0 or length < 0:
raise ValueError("vol_cuboid() only accepts non-negative values")
return float(width * height * length) | maths |
def vol_cone(area_of_base: float, height: float) -> float:
if height < 0 or area_of_base < 0:
raise ValueError("vol_cone() only accepts non-negative values")
return area_of_base * height / 3.0 | maths |
def vol_right_circ_cone(radius: float, height: float) -> float:
if height < 0 or radius < 0:
raise ValueError("vol_right_circ_cone() only accepts non-negative values")
return pi * pow(radius, 2) * height / 3.0 | maths |
def vol_prism(area_of_base: float, height: float) -> float:
if height < 0 or area_of_base < 0:
raise ValueError("vol_prism() only accepts non-negative values")
return float(area_of_base * height) | maths |
def vol_pyramid(area_of_base: float, height: float) -> float:
if height < 0 or area_of_base < 0:
raise ValueError("vol_pyramid() only accepts non-negative values")
return area_of_base * height / 3.0 | maths |
def vol_sphere(radius: float) -> float:
if radius < 0:
raise ValueError("vol_sphere() only accepts non-negative values")
# Volume is 4/3 * pi * radius cubed
return 4 / 3 * pi * pow(radius, 3) | maths |
def vol_hemisphere(radius: float) -> float:
if radius < 0:
raise ValueError("vol_hemisphere() only accepts non-negative values")
# Volume is radius cubed * pi * 2/3
return pow(radius, 3) * pi * 2 / 3 | maths |
def vol_circular_cylinder(radius: float, height: float) -> float:
if height < 0 or radius < 0:
raise ValueError("vol_circular_cylinder() only accepts non-negative values")
# Volume is radius squared * height * pi
return pow(radius, 2) * height * pi | maths |
def vol_hollow_circular_cylinder(
inner_radius: float, outer_radius: float, height: float
) -> float:
# Volume - (outer_radius squared - inner_radius squared) * pi * height
if inner_radius < 0 or outer_radius < 0 or height < 0:
raise ValueError(
"vol_hollow_circular_cylinder() only accepts non-negative values"
)
if outer_radius <= inner_radius:
raise ValueError("outer_radius must be greater than inner_radius")
return pi * (pow(outer_radius, 2) - pow(inner_radius, 2)) * height | maths |
def vol_conical_frustum(height: float, radius_1: float, radius_2: float) -> float:
# Volume is 1/3 * pi * height *
# (radius_1 squared + radius_2 squared + radius_1 * radius_2)
if radius_1 < 0 or radius_2 < 0 or height < 0:
raise ValueError("vol_conical_frustum() only accepts non-negative values")
return (
1
/ 3
* pi
* height
* (pow(radius_1, 2) + pow(radius_2, 2) + radius_1 * radius_2)
) | maths |
def vol_torus(torus_radius: float, tube_radius: float) -> float:
if torus_radius < 0 or tube_radius < 0:
raise ValueError("vol_torus() only accepts non-negative values")
return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2) | maths |
def least_common_multiple_slow(first_num: int, second_num: int) -> int:
max_num = first_num if first_num >= second_num else second_num
common_mult = max_num
while (common_mult % first_num > 0) or (common_mult % second_num > 0):
common_mult += max_num
return common_mult | maths |
def greatest_common_divisor(a: int, b: int) -> int:
return b if a == 0 else greatest_common_divisor(b % a, a) | maths |
def least_common_multiple_fast(first_num: int, second_num: int) -> int:
return first_num // greatest_common_divisor(first_num, second_num) * second_num | maths |
def benchmark():
setup = (
"from __main__ import least_common_multiple_slow, least_common_multiple_fast"
)
print(
"least_common_multiple_slow():",
timeit("least_common_multiple_slow(1000, 999)", setup=setup),
)
print(
"least_common_multiple_fast():",
timeit("least_common_multiple_fast(1000, 999)", setup=setup),
) | maths |
def test_lcm_function(self):
for i, (first_num, second_num) in enumerate(self.test_inputs):
slow_result = least_common_multiple_slow(first_num, second_num)
fast_result = least_common_multiple_fast(first_num, second_num)
with self.subTest(i=i):
self.assertEqual(slow_result, self.expected_results[i])
self.assertEqual(fast_result, self.expected_results[i]) | maths |
def find_max(nums: list[int | float], left: int, right: int) -> int | float:
if len(nums) == 0:
raise ValueError("find_max() arg is an empty sequence")
if (
left >= len(nums)
or left < -len(nums)
or right >= len(nums)
or right < -len(nums)
):
raise IndexError("list index out of range")
if left == right:
return nums[left]
mid = (left + right) >> 1 # the middle
left_max = find_max(nums, left, mid) # find max in range[left, mid]
right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right]
return left_max if left_max >= right_max else right_max | maths |
def prime_factors(n: int) -> list[int]:
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors | maths |
def method_2(boundary, steps):
# "Simpson Rule"
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
h = (boundary[1] - boundary[0]) / steps
a = boundary[0]
b = boundary[1]
x_i = make_points(a, b, h)
y = 0.0
y += (h / 3.0) * f(a)
cnt = 2
for i in x_i:
y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i)
cnt += 1
y += (h / 3.0) * f(b)
return y | maths |
def make_points(a, b, h):
x = a + h
while x < (b - h):
yield x
x = x + h | maths |
def f(x): # enter your function here
y = (x - 0) * (x - 0)
return y | maths |
def main():
a = 0.0 # Lower bound of integration
b = 1.0 # Upper bound of integration
steps = 10.0 # define number of steps or resolution
boundary = [a, b] # define boundary of integration
y = method_2(boundary, steps)
print(f"y = {y}") | maths |
def two_pointer(nums: list[int], target: int) -> list[int]:
i = 0
j = len(nums) - 1
while i < j:
if nums[i] + nums[j] == target:
return [i, j]
elif nums[i] + nums[j] < target:
i = i + 1
else:
j = j - 1
return [] | maths |
def find_min(nums: list[int | float], left: int, right: int) -> int | float:
if len(nums) == 0:
raise ValueError("find_min() arg is an empty sequence")
if (
left >= len(nums)
or left < -len(nums)
or right >= len(nums)
or right < -len(nums)
):
raise IndexError("list index out of range")
if left == right:
return nums[left]
mid = (left + right) >> 1 # the middle
left_min = find_min(nums, left, mid) # find min in range[left, mid]
right_min = find_min(nums, mid + 1, right) # find min in range[mid + 1, right]
return left_min if left_min <= right_min else right_min | maths |
def calc_derivative(f, a, h=0.001):
return (f(a + h) - f(a - h)) / (2 * h) | maths |
def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False):
a = x0 # set the initial guess
steps = [a]
error = abs(f(a))
f1 = lambda x: calc_derivative(f, x, h=step) # noqa: E731 Derivative of f(x)
for _ in range(maxiter):
if f1(a) == 0:
raise ValueError("No converging solution found")
a = a - f(a) / f1(a) # Calculate the next estimate
if logsteps:
steps.append(a)
if error < maxerror:
break
else:
raise ValueError("Iteration limit reached, no converging solution found")
if logsteps:
# If logstep is true, then log intermediate steps
return a, error, steps
return a, error | maths |
def hexagonal(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 number * (2 * number - 1) | maths |
def find_min(nums: list[int | float]) -> int | float:
if len(nums) == 0:
raise ValueError("find_min() arg is an empty sequence")
min_num = nums[0]
for num in nums:
min_num = min(min_num, num)
return min_num | maths |
def method_1(boundary, steps):
# "extended trapezoidal rule"
# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
h = (boundary[1] - boundary[0]) / steps
a = boundary[0]
b = boundary[1]
x_i = make_points(a, b, h)
y = 0.0
y += (h / 2.0) * f(a)
for i in x_i:
# print(i)
y += h * f(i)
y += (h / 2.0) * f(b)
return y | maths |
def make_points(a, b, h):
x = a + h
while x < (b - h):
yield x
x = x + h | maths |
def f(x): # enter your function here
y = (x - 0) * (x - 0)
return y | maths |
def main():
a = 0.0 # Lower bound of integration
b = 1.0 # Upper bound of integration
steps = 10.0 # define number of steps or resolution
boundary = [a, b] # define boundary of integration
y = method_1(boundary, steps)
print(f"y = {y}") | maths |
def decimal_isolate(number: float, digit_amount: int) -> float:
if digit_amount > 0:
return round(number - int(number), digit_amount)
return number - int(number) | maths |
def b_expo(a, b):
res = 0
while b > 0:
if b & 1:
res += a
a += a
b >>= 1
return res | maths |
def is_pronic(number: int) -> bool:
if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer")
if number < 0 or number % 2 == 1:
return False
number_sqrt = int(number**0.5)
return number == number_sqrt * (number_sqrt + 1) | maths |
def armstrong_number(n: int) -> bool:
if not isinstance(n, int) or n < 1:
return False
# Initialization of sum and number of digits.
total = 0
number_of_digits = 0
temp = n
# Calculation of digits of the number
while temp > 0:
number_of_digits += 1
temp //= 10
# Dividing number into separate digits and find Armstrong number
temp = n
while temp > 0:
rem = temp % 10
total += rem**number_of_digits
temp //= 10
return n == total | maths |
def pluperfect_number(n: int) -> bool:
if not isinstance(n, int) or n < 1:
return False
# Init a "histogram" of the digits
digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
digit_total = 0
total = 0
temp = n
while temp > 0:
temp, rem = divmod(temp, 10)
digit_histogram[rem] += 1
digit_total += 1
for cnt, i in zip(digit_histogram, range(len(digit_histogram))):
total += cnt * i**digit_total
return n == total | maths |
def narcissistic_number(n: int) -> bool:
if not isinstance(n, int) or n < 1:
return False
expo = len(str(n)) # the power that all digits will be raised to
# check if sum of each digit multiplied expo times is equal to number
return n == sum(int(i) ** expo for i in str(n)) | maths |
def main():
num = int(input("Enter an integer to see if it is an Armstrong number: ").strip())
print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.")
print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.")
print(f"{num} is {'' if pluperfect_number(num) else 'not '}an Armstrong number.") | maths |
def rand_fn(value: int, step: int, modulus: int) -> int:
return (pow(value, 2) + step) % modulus | maths |
def b_expo(a, b):
res = 1
while b > 0:
if b & 1:
res *= a
a *= a
b >>= 1
return res | maths |
def relu(vector: list[float]):
# compare two arrays and then return element-wise maxima.
return np.maximum(0, vector) | maths |
def sock_merchant(colors: list[int]) -> int:
return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) | maths |
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y | maths |
def is_in_unit_circle(self) -> bool:
return (self.x**2 + self.y**2) <= 1 | maths |
def random_unit_square(cls):
return cls(x=random.random(), y=random.random()) | maths |
def estimate_pi(number_of_simulations: int) -> float:
if number_of_simulations < 1:
raise ValueError("At least one simulation is necessary to estimate PI.")
number_in_unit_circle = 0
for _ in range(number_of_simulations):
random_point = Point.random_unit_square()
if random_point.is_in_unit_circle():
number_in_unit_circle += 1
return 4 * number_in_unit_circle / number_of_simulations | maths |
def totient(n: int) -> list:
is_prime = [True for i in range(n + 1)]
totients = [i - 1 for i in range(n + 1)]
primes = []
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
if i % primes[j] == 0:
totients[i * primes[j]] = totients[i] * primes[j]
break
totients[i * primes[j]] = totients[i] * (primes[j] - 1)
return totients | maths |
def test_totient() -> None:
pass | maths |
def factorial(number: int) -> int:
if number != int(number):
raise ValueError("factorial() only accepts integral values")
if number < 0:
raise ValueError("factorial() not defined for negative values")
value = 1
for i in range(1, number + 1):
value *= i
return value | maths |
def factorial_recursive(n: int) -> int:
if not isinstance(n, int):
raise ValueError("factorial() only accepts integral values")
if n < 0:
raise ValueError("factorial() not defined for negative values")
return 1 if n == 0 or n == 1 else n * factorial(n - 1) | maths |
def fx(x: float, a: float) -> float:
return math.pow(x, 2) - a | maths |
def fx_derivative(x: float) -> float:
return 2 * x | maths |
def get_initial_point(a: float) -> float:
start = 2.0
while start <= a:
start = math.pow(start, 2)
return start | maths |
def square_root_iterative(
a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001
) -> float:
if a < 0:
raise ValueError("math domain error")
value = get_initial_point(a)
for _ in range(max_iter):
prev_value = value
value = value - fx(value, a) / fx_derivative(value)
if abs(prev_value - value) < tolerance:
return value
return value | maths |
def kth_permutation(k, n):
# Factorails from 1! to (n-1)!
factorials = [1]
for i in range(2, n):
factorials.append(factorials[-1] * i)
assert 0 <= k < factorials[-1] * n, "k out of bounds"
permutation = []
elements = list(range(n))
# Find permutation
while factorials:
factorial = factorials.pop()
number, k = divmod(k, factorial)
permutation.append(elements[number])
elements.remove(elements[number])
permutation.append(elements[0])
return permutation | maths |
def double_factorial(num: int) -> int:
if not isinstance(num, int):
raise ValueError("double_factorial() only accepts integral values")
if num < 0:
raise ValueError("double_factorial() not defined for negative values")
value = 1
for i in range(num, 0, -2):
value *= i
return value | maths |
def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
steps: int = 100,
) -> float:
x1 = x_start
fx1 = fnc(x_start)
length = 0.0
for _ in range(steps):
# Approximates curve as a sequence of linear lines and sums their length
x2 = (x_end - x_start) / steps + x1
fx2 = fnc(x2)
length += math.hypot(x2 - x1, fx2 - fx1)
# Increment step
x1 = x2
fx1 = fx2
return length | maths |
def f(x):
return math.sin(10 * x) | maths |
def pi(precision: int) -> str:
if not isinstance(precision, int):
raise TypeError("Undefined for non-integers")
elif precision < 1:
raise ValueError("Undefined for non-natural numbers")
getcontext().prec = precision
num_iterations = ceil(precision / 14)
constant_term = 426880 * Decimal(10005).sqrt()
exponential_term = 1
linear_term = 13591409
partial_sum = Decimal(linear_term)
for k in range(1, num_iterations):
multinomial_term = factorial(6 * k) // (factorial(3 * k) * factorial(k) ** 3)
linear_term += 545140134
exponential_term *= -262537412640768000
partial_sum += Decimal(multinomial_term * linear_term) / exponential_term
return str(constant_term / partial_sum)[:-1] | maths |
def slow_primes(max_n: int) -> Generator[int, None, None]:
numbers: Generator = (i for i in range(1, (max_n + 1)))
for i in (n for n in numbers if n > 1):
for j in range(2, i):
if (i % j) == 0:
break
else:
yield i | maths |
def primes(max_n: int) -> Generator[int, None, None]:
numbers: Generator = (i for i in range(1, (max_n + 1)))
for i in (n for n in numbers if n > 1):
# only need to check for factors up to sqrt(i)
bound = int(math.sqrt(i)) + 1
for j in range(2, bound):
if (i % j) == 0:
break
else:
yield i | maths |
def fast_primes(max_n: int) -> Generator[int, None, None]:
numbers: Generator = (i for i in range(1, (max_n + 1), 2))
# It's useless to test even numbers as they will not be prime
if max_n > 2:
yield 2 # Because 2 will not be tested, it's necessary to yield it now
for i in (n for n in numbers if n > 1):
bound = int(math.sqrt(i)) + 1
for j in range(3, bound, 2):
# As we removed the even numbers, we don't need them now
if (i % j) == 0:
break
else:
yield i | maths |
def benchmark():
from timeit import timeit
setup = "from __main__ import slow_primes, primes, fast_primes"
print(timeit("slow_primes(1_000_000_000_000)", setup=setup, number=1_000_000))
print(timeit("primes(1_000_000_000_000)", setup=setup, number=1_000_000))
print(timeit("fast_primes(1_000_000_000_000)", setup=setup, number=1_000_000)) | maths |
def check_polygon(nums: list[float]) -> bool:
if len(nums) < 2:
raise ValueError("Monogons and Digons are not polygons in the Euclidean space")
if any(i <= 0 for i in nums):
raise ValueError("All values must be greater than 0")
copy_nums = nums.copy()
copy_nums.sort()
return copy_nums[-1] < sum(copy_nums[:-1]) | maths |
def sum_of_harmonic_progression(
first_term: float, common_difference: float, number_of_terms: int
) -> float:
arithmetic_progression = [1 / first_term]
first_term = 1 / first_term
for _ in range(number_of_terms - 1):
first_term += common_difference
arithmetic_progression.append(first_term)
harmonic_series = [1 / step for step in arithmetic_progression]
return sum(harmonic_series) | maths |
def binomial_coefficient(n, r):
c = [0 for i in range(r + 1)]
# nc0 = 1
c[0] = 1
for i in range(1, n + 1):
# to compute current row from previous row.
j = min(i, r)
while j > 0:
c[j] += c[j - 1]
j -= 1
return c[r] | maths |
def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d:
x = end_point2[0] - end_point1[0]
y = end_point2[1] - end_point1[1]
z = end_point2[2] - end_point1[2]
return (x, y, z) | maths |
def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d:
x = ab[1] * ac[2] - ab[2] * ac[1] # *i
y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j
z = ab[0] * ac[1] - ab[1] * ac[0] # *k
return (x, y, z) | maths |
def is_zero_vector(vector: Vector3d, accuracy: int) -> bool:
return tuple(round(x, accuracy) for x in vector) == (0, 0, 0) | maths |
def factorial(digit: int) -> int:
return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) | maths |
def krishnamurthy(number: int) -> bool:
fact_sum = 0
duplicate = number
while duplicate > 0:
duplicate, digit = divmod(duplicate, 10)
fact_sum += factorial(digit)
return fact_sum == number | maths |
def gcd(a: int, b: int) -> int:
if a < b:
return gcd(b, a)
if a % b == 0:
return b
return gcd(b, a % b) | maths |
def power(x: int, y: int, mod: int) -> int:
if y == 0:
return 1
temp = power(x, y // 2, mod) % mod
temp = (temp * temp) % mod
if y % 2 == 1:
temp = (temp * x) % mod
return temp | maths |
def is_carmichael_number(n: int) -> bool:
b = 2
while b < n:
if gcd(b, n) == 1 and power(b, n - 1, n) != 1:
return False
b += 1
return True | maths |
def exact_prime_factor_count(n):
count = 0
if n % 2 == 0:
count += 1
while n % 2 == 0:
n = int(n / 2)
# the n input value must be odd so that
# we can skip one element (ie i += 2)
i = 3
while i <= int(math.sqrt(n)):
if n % i == 0:
count += 1
while n % i == 0:
n = int(n / i)
i = i + 2
# this condition checks the prime
# number n is greater than 2
if n > 2:
count += 1
return count | maths |
def prime_sieve_eratosthenes(num: int) -> list[int]:
if num <= 0:
raise ValueError("Input must be a positive integer")
primes = [True] * (num + 1)
p = 2
while p * p <= num:
if primes[p]:
for i in range(p * p, num + 1, p):
primes[i] = False
p += 1
return [prime for prime in range(2, num + 1) if primes[prime]] | maths |
def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
steps: int = 100,
) -> float:
x1 = x_start
fx1 = fnc(x_start)
area = 0.0
for _ in range(steps):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
x2 = (x_end - x_start) / steps + x1
fx2 = fnc(x2)
area += abs(fx2 + fx1) * (x2 - x1) / 2
# Increment step
x1 = x2
fx1 = fx2
return area | maths |
def f(x):
return x**3 + x**2 | maths |
def dodecahedron_surface_area(edge: float) -> float:
if edge <= 0 or not isinstance(edge, int):
raise ValueError("Length must be a positive.")
return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) | maths |
def dodecahedron_volume(edge: float) -> float:
if edge <= 0 or not isinstance(edge, int):
raise ValueError("Length must be a positive.")
return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) | maths |
def euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut:
return np.sqrt(np.sum((np.asarray(vector_1) - np.asarray(vector_2)) ** 2)) | maths |
def euclidean_distance_no_np(vector_1: Vector, vector_2: Vector) -> VectorOut:
return sum((v1 - v2) ** 2 for v1, v2 in zip(vector_1, vector_2)) ** (1 / 2) | maths |
def benchmark() -> None:
from timeit import timeit
print("Without Numpy")
print(
timeit(
"euclidean_distance_no_np([1, 2, 3], [4, 5, 6])",
number=10000,
globals=globals(),
)
)
print("With Numpy")
print(
timeit(
"euclidean_distance([1, 2, 3], [4, 5, 6])",
number=10000,
globals=globals(),
)
) | maths |
def perfect_square(num: int) -> bool:
return math.sqrt(num) * math.sqrt(num) == num | maths |
def perfect_square_binary_search(n: int) -> bool:
left = 0
right = n
while left <= right:
mid = (left + right) // 2
if mid**2 == n:
return True
elif mid**2 > n:
right = mid - 1
else:
left = mid + 1
return False | maths |
def manhattan_distance(point_a: list, point_b: list) -> float:
_validate_point(point_a)
_validate_point(point_b)
if len(point_a) != len(point_b):
raise ValueError("Both points must be in the same n-dimensional space")
return float(sum(abs(a - b) for a, b in zip(point_a, point_b))) | maths |
def _validate_point(point: list[float]) -> None:
if point:
if isinstance(point, list):
for item in point:
if not isinstance(item, (int, float)):
raise TypeError(
f"Expected a list of numbers as input, "
f"found {type(item).__name__}"
)
else:
raise TypeError(
f"Expected a list of numbers as input, found {type(point).__name__}"
)
else:
raise ValueError("Missing an input") | maths |
def manhattan_distance_one_liner(point_a: list, point_b: list) -> float:
_validate_point(point_a)
_validate_point(point_b)
if len(point_a) != len(point_b):
raise ValueError("Both points must be in the same n-dimensional space")
return float(sum(abs(x - y) for x, y in zip(point_a, point_b))) | maths |
def sigmoid(vector: np.array) -> np.array:
return 1 / (1 + np.exp(-vector)) | maths |
def combinations(n: int, k: int) -> int:
# If either of the conditions are true, the function is being asked
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
return factorial(n) // (factorial(k) * factorial(n - k)) | maths |
Subsets and Splits