instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate descriptive docstrings automatically
import numpy as np # List of input, output pairs train_data = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) test_data = (((515, 22, 13), 555), ((61, 35, 49), 150)) parameter_vector = [2, 4, 1, 5] m = len(train_data) LEARNING_RATE = 0.009 def _error...
--- +++ @@ -1,3 +1,7 @@+""" +Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis +function. +""" import numpy as np @@ -16,12 +20,25 @@ def _error(example_no, data_set="train"): + """ + :param data_set: train data or test data + :param example_no: example number who...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/gradient_descent.py
Write docstrings for backend logic
import matplotlib.pyplot as plt import numpy as np def weight_matrix(point: np.ndarray, x_train: np.ndarray, tau: float) -> np.ndarray: m = len(x_train) # Number of training samples weights = np.eye(m) # Initialize weights as identity matrix for j in range(m): diff = point - x_train[j] ...
--- +++ @@ -1,9 +1,63 @@+""" +Locally weighted linear regression, also called local regression, is a type of +non-parametric linear regression that prioritizes data closest to a given +prediction point. The algorithm estimates the vector of model coefficients β +using weighted least squares regression: + +β = (XᵀWX)⁻¹(...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/local_weighted_learning/local_weighted_learning.py
Add detailed docstrings explaining each function
import os import sys import urllib.request import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.datasets import make_blobs, make_circles from sklearn.preprocessing import StandardScaler CANCER_DATASET_URL = ( "https://archive.ics.uci.edu/ml/machine-learning-databases/" "br...
--- +++ @@ -1,3 +1,32 @@+""" +Sequential minimal optimization (SMO) for support vector machines (SVM) + +Sequential minimal optimization (SMO) is an algorithm for solving the quadratic +programming (QP) problem that arises during the training of SVMs. It was invented by +John Platt in 1998. + +Input: + 0: type: nump...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/sequential_minimum_optimization.py
Improve my code by adding docstrings
def binary_multiply(a: int, b: int) -> int: res = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def binary_mod_multiply(a: int, b: int, modulus: int) -> int: res = 0 while b > 0: if b & 1: res = ((res % modulus) + (a % modul...
--- +++ @@ -1,6 +1,52 @@+""" +Binary Multiplication +This is a method to find a*b in a time complexity of O(log b) +This is one of the most commonly used methods of finding result of multiplication. +Also useful in cases where solution to (a*b)%c is required, +where a,b,c can be numbers over the computers calculation l...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/binary_multiplication.py
Turn comments into proper docstrings
import numpy as np def binary_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") y_pred = np.clip(y_pred, epsilon, 1 - epsilon) # Clip predictions to avoid log(0) ...
--- +++ @@ -4,6 +4,33 @@ def binary_cross_entropy( y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 ) -> float: + """ + Calculate the mean binary cross-entropy (BCE) loss between true labels and predicted + probabilities. + + BCE loss quantifies dissimilarity between true labels (0 or 1)...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/loss_functions.py
Add docstrings to clarify complex logic
from __future__ import annotations from collections.abc import Generator def collatz_sequence(n: int) -> Generator[int]: if not isinstance(n, int) or n < 1: raise Exception("Sequence only defined for positive integers") yield n while n != 1: if n % 2 == 0: n //= 2 el...
--- +++ @@ -1,3 +1,16 @@+""" +The Collatz conjecture is a famous unsolved problem in mathematics. Given a starting +positive integer, define the following sequence: +- If the current term n is even, then the next term is n/2. +- If the current term n is odd, then the next term is 3n + 1. +The conjecture claims that thi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/collatz_sequence.py
Add docstrings to existing functions
def rank_of_matrix(matrix: list[list[int | float]]) -> int: rows = len(matrix) columns = len(matrix[0]) rank = min(rows, columns) for row in range(rank): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal ...
--- +++ @@ -1,6 +1,60 @@+""" +Calculate the rank of a matrix. + +See: https://en.wikipedia.org/wiki/Rank_(linear_algebra) +""" def rank_of_matrix(matrix: list[list[int | float]]) -> int: + """ + Finds the rank of a matrix. + + Args: + `matrix`: The matrix as a list of lists. + + Returns: + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/src/rank_of_matrix.py
Create docstrings for each class method
import string from math import log10 """ tf-idf Wikipedia: https://en.wikipedia.org/wiki/Tf%E2%80%93idf tf-idf and other word frequency algorithms are often used as a weighting factor in information retrieval and text mining. 83% of text-based recommender systems use tf-idf for term weighting. In L...
--- +++ @@ -41,6 +41,18 @@ def term_frequency(term: str, document: str) -> int: + """ + Return the number of times a term occurs within + a given document. + @params: term, the term to search a document for, and document, + the document to search within + @returns: an integer representing ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/word_frequency_functions.py
Write beginner-friendly docstrings
def abs_val(num: float) -> float: return -num if num < 0 else num def abs_min(x: list[int]) -> int: if len(x) == 0: raise ValueError("abs_min() arg is an empty sequence") j = x[0] for i in x: if abs_val(i) < abs_val(j): j = i return j def abs_max(x: list[int]) -> in...
--- +++ @@ -1,10 +1,31 @@+"""Absolute Value.""" def abs_val(num: float) -> float: + """ + Find the absolute value of a number. + + >>> abs_val(-5.1) + 5.1 + >>> abs_val(-5) == abs_val(5) + True + >>> abs_val(0) + 0 + """ return -num if num < 0 else num def abs_min(x: list[int])...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/abs.py
Add standardized docstrings across the file
# XGBoost Classifier Example import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def data_handling(data: dict) -> tuple: # Split data...
--- +++ @@ -10,16 +10,42 @@ def data_handling(data: dict) -> tuple: # Split dataset into features and target # data is features + """ + >>> data_handling(({'data':'[5.1, 3.5, 1.4, 0.2]','target':([0])})) + ('[5.1, 3.5, 1.4, 0.2]', [0]) + >>> data_handling( + ... {'data': '[4.9, 3.0, 1.4, 0....
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/xgboost_classifier.py
Write proper docstrings for these functions
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) ->...
--- +++ @@ -1,3 +1,12 @@+""" +Similarity Search : https://en.wikipedia.org/wiki/Similarity_search +Similarity search is a search algorithm for finding the nearest vector from +vectors, used in natural language processing. +In this algorithm, it calculates distance with euclidean distance and +returns a list containing ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/similarity_search.py
Write docstrings for utility functions
from math import pi, sqrt, tan def surface_area_cube(side_length: float) -> float: if side_length < 0: raise ValueError("surface_area_cube() only accepts non-negative values") return 6 * side_length**2 def surface_area_cuboid(length: float, breadth: float, height: float) -> float: if length < 0...
--- +++ @@ -1,165 +1,583 @@- -from math import pi, sqrt, tan - - -def surface_area_cube(side_length: float) -> float: - if side_length < 0: - raise ValueError("surface_area_cube() only accepts non-negative values") - return 6 * side_length**2 - - -def surface_area_cuboid(length: float, breadth: float, heig...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/area.py
Expand my code with proper documentation strings
from __future__ import annotations 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_par...
--- +++ @@ -1,8 +1,34 @@+""" +In a multi-threaded download, this algorithm could be used to provide +each worker thread with a block of non-overlapping bytes to download. +For example: + for i in allocation_list: + requests.get(url,headers={'Range':f'bytes={i}'}) +""" from __future__ import annotations ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/allocation_number.py
Add standardized docstrings across the file
from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): # Approximates small segm...
--- +++ @@ -1,3 +1,6 @@+""" +Approximates the area under the curve using the trapezoidal rule +""" from __future__ import annotations @@ -10,6 +13,26 @@ x_end: float, steps: int = 100, ) -> float: + """ + Treats curve as a collection of linear lines and sums the area of the + trapezium shape the...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/area_under_curve.py
Write Python docstrings for this snippet
import matplotlib.pyplot as plt import numpy as np class PolynomialRegression: __slots__ = "degree", "params" def __init__(self, degree: int) -> None: if degree < 0: raise ValueError("Polynomial degree must be non-negative") self.degree = degree self.params = None @...
--- +++ @@ -1,3 +1,38 @@+""" +Polynomial regression is a type of regression analysis that models the relationship +between a predictor x and the response y as an mth-degree polynomial: + +y = β₀ + β₁x + β₂x² + ... + βₘxᵐ + ε + +By treating x, x², ..., xᵐ as distinct variables, we see that polynomial regression is a +sp...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/polynomial_regression.py
Add docstrings for utility scripts
def add(first: int, second: int) -> int: while second != 0: c = first & second first ^= second second = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() first = int(input("Enter the first number: ").strip()) second = int(input("Enter t...
--- +++ @@ -1,6 +1,27 @@+""" +Illustrate how to add the integer without arithmetic operation +Author: suraj Kumar +Time Complexity: 1 +https://en.wikipedia.org/wiki/Bitwise_operation +""" def add(first: int, second: int) -> int: + """ + Implementation of addition of integer + + Examples: + >>> add(3, 5...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/addition_without_arithmetic.py
Help me comply with documentation standards
def binary_exp_recursive(base: float, exponent: int) -> float: if exponent < 0: raise ValueError("Exponent must be a non-negative integer") if exponent == 0: return 1 if exponent % 2 == 1: return binary_exp_recursive(base, exponent - 1) * base b = binary_exp_recursive(base, ...
--- +++ @@ -1,6 +1,42 @@+""" +Binary Exponentiation + +This is a method to find a^b in O(log b) time complexity and is one of the most commonly +used methods of exponentiation. The method is also useful for modular exponentiation, +when the solution to (a^b) % c is required. + +To calculate a^b: +- If b is even, then a...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/binary_exponentiation.py
Add clean documentation to messy code
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 mu...
--- +++ @@ -1,4 +1,42 @@ def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str: + """ + Implement a popular pi-digit-extraction algorithm known as the + Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi. + Wikipedia page: + https://en.wikipedia.org/wiki/Bai...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/bailey_borwein_plouffe.py
Generate docstrings for exported functions
from __future__ import annotations # Extended Euclid def extended_euclid(a: int, b: int) -> tuple[int, int]: if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2...
--- +++ @@ -1,9 +1,30 @@+""" +Chinese Remainder Theorem: +GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) + +If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b +there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are +two such integers, then ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/chinese_remainder_theorem.py
Generate descriptive docstrings automatically
def ceil(x: float) -> int: return int(x) if x - int(x) <= 0 else int(x) + 1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,10 +1,24 @@+""" +https://en.wikipedia.org/wiki/Floor_and_ceiling_functions +""" def ceil(x: float) -> int: + """ + Return the ceiling of x as an Integral. + + :param x: the number + :return: the smallest integer >= x. + + >>> import math + >>> all(ceil(n) == math.ceil(n) for n + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/ceil.py
Write docstrings for algorithm functions
from __future__ import annotations def find_min_iterative(nums: list[int | float]) -> int | float: if len(nums) == 0: raise ValueError("find_min_iterative() arg is an empty sequence") min_num = nums[0] for num in nums: min_num = min(min_num, num) return min_num # Divide and Conquer a...
--- +++ @@ -2,6 +2,24 @@ def find_min_iterative(nums: list[int | float]) -> int | float: + """ + Find Minimum Number in a List + :param nums: contains elements + :return: min number in list + + >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): + ... find_min_iterative(num...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/find_min.py
Document this module using docstrings
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") res = 1 for i ...
--- +++ @@ -1,6 +1,34 @@+""" +https://en.wikipedia.org/wiki/Combination +""" def combinations(n: int, k: int) -> int: + """ + Returns the number of different combinations of k length which can + be made from n values, where n >= k. + + Examples: + >>> combinations(10,5) + 252 + + >>> combinati...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/combinations.py
Fully document this Python code with docstrings
def decimal_isolate(number: float, digit_amount: int) -> float: if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2))...
--- +++ @@ -1,6 +1,32 @@+""" +Isolate the Decimal part of a Number +https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point +""" def decimal_isolate(number: float, digit_amount: int) -> float: + """ + Isolates the decimal part of a number. + If digitAmount > 0 round to that deci...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/decimal_isolate.py
Write beginner-friendly docstrings
# dodecahedron.py 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) def dodecahedron_volume(edge: float) -> float: if edge <= 0 or not is...
--- +++ @@ -1,8 +1,36 @@ # dodecahedron.py +""" +A regular dodecahedron is a three-dimensional figure made up of +12 pentagon faces having the same equal size. +""" def dodecahedron_surface_area(edge: float) -> float: + """ + Calculates the surface area of a regular dodecahedron + a = 3 * ((25 + 10 * (5...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/dodecahedron.py
Create structured documentation for my script
from fractions import Fraction from math import floor def continued_fraction(num: Fraction) -> list[int]: numerator, denominator = num.as_integer_ratio() continued_fraction_list: list[int] = [] while True: integer_part = floor(numerator / denominator) continued_fraction_list.append(intege...
--- +++ @@ -1,9 +1,41 @@+""" +Finding the continuous fraction for a rational number using python + +https://en.wikipedia.org/wiki/Continued_fraction +""" from fractions import Fraction from math import floor def continued_fraction(num: Fraction) -> list[int]: + """ + :param num: + Fraction of the numb...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/continued_fraction.py
Add docstrings that explain purpose and usage
from maths.prime_check import is_prime def is_germain_prime(number: int) -> bool: if not isinstance(number, int) or number < 1: msg = f"Input value must be a positive integer. Input value: {number}" raise TypeError(msg) return is_prime(number) and is_prime(2 * number + 1) def is_safe_prime...
--- +++ @@ -1,8 +1,36 @@+""" +A Sophie Germain prime is any prime p, where 2p + 1 is also prime. +The second number, 2p + 1 is called a safe prime. + +Examples of Germain primes include: 2, 3, 5, 11, 23 + +Their corresponding safe primes: 5, 7, 11, 23, 47 +https://en.wikipedia.org/wiki/Safe_and_Sophie_Germain_primes +"...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/germain_primes.py
Insert docstrings into my code
#!/usr/bin/env python3 from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def calculate_prob(text: str) -> None: single_char_strings, two_char_strings = analyze_text(text) my_alphas = list(" " + ascii_lowercase) # what is our total sum of p...
--- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python3 +""" +Implementation of entropy of information +https://en.wikipedia.org/wiki/Entropy_(information_theory) +""" from __future__ import annotations @@ -9,6 +13,47 @@ def calculate_prob(text: str) -> None: + """ + This method takes path and two dict as argum...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/entropy.py
Generate docstrings for this script
from __future__ import annotations import typing from collections.abc import Iterable import numpy as np Vector = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 VectorOut = typing.Union[np.float64, int, float] # noqa: UP007 def euclidean_distance(vector_1: Vector, vector_2: Vector) -> Vec...
--- +++ @@ -10,16 +10,39 @@ def euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut: + """ + Calculate the distance between the two endpoints of two vectors. + A vector is defined as a list, tuple, or numpy 1D array. + >>> float(euclidean_distance((0, 0), (2, 2))) + 2.8284271247461903...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/euclidean_distance.py
Write beginner-friendly docstrings
def double_factorial_recursive(n: int) -> int: if not isinstance(n, int): raise ValueError("double_factorial_recursive() only accepts integral values") if n < 0: raise ValueError("double_factorial_recursive() not defined for negative values") return 1 if n <= 1 else n * double_factorial_recu...
--- +++ @@ -1,4 +1,23 @@ def double_factorial_recursive(n: int) -> int: + """ + Compute double factorial using recursive method. + Recursion can be costly for large numbers. + + To learn about the theory behind this algorithm: + https://en.wikipedia.org/wiki/Double_factorial + + >>> from math import p...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/double_factorial.py
Create simple docstrings for beginners
# @Author: S. Sharma <silentcat> # @Date: 2019-02-25T12:08:53-06:00 # @Email: silentcat@protonmail.com # @Last modified by: pikulet # @Last modified time: 2020-10-02 from __future__ import annotations import sys def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: # base cases if abs(a)...
--- +++ @@ -1,3 +1,11 @@+""" +Extended Euclidean Algorithm. + +Finds 2 numbers a and b such that it satisfies +the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) + +https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm +""" # @Author: S. Sharma <silentcat> # @Date: 2019-02-25T12:08:53-06:00 @@ -10,6 ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/extended_euclidean_algorithm.py
Add docstrings for utility scripts
from math import factorial def binomial_distribution(successes: int, trials: int, prob: float) -> float: if successes > trials: raise ValueError("""successes must be lower or equal to trials""") if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integer...
--- +++ @@ -1,27 +1,41 @@- -from math import factorial - - -def binomial_distribution(successes: int, trials: int, prob: float) -> float: - if successes > trials: - raise ValueError("""successes must be lower or equal to trials""") - if trials < 0 or successes < 0: - raise ValueError("the function i...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/binomial_distribution.py
Annotate my code with docstrings
def compute_geometric_mean(*args: int) -> float: product = 1 for number in args: if not isinstance(number, int) and not isinstance(number, float): raise TypeError("Not a Number") product *= number # Cannot calculate the even root for negative product. # Frequently they are ...
--- +++ @@ -1,6 +1,32 @@+""" +The Geometric Mean of n numbers is defined as the n-th root of the product +of those numbers. It is used to measure the central tendency of the numbers. +https://en.wikipedia.org/wiki/Geometric_mean +""" def compute_geometric_mean(*args: int) -> float: + """ + Return the geometr...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/geometric_mean.py
Create Google-style docstrings for my code
import functools from collections.abc import Iterator from math import sqrt from time import time import numpy as np from numpy import ndarray def time_func(func, *args, **kwargs): start = time() output = func(*args, **kwargs) end = time() if int(end - start) > 0: print(f"{func.__name__} run...
--- +++ @@ -1,3 +1,18 @@+""" +Calculates the Fibonacci sequence using iteration, recursion, memoization, +and a simplified form of Binet's formula + +NOTE 1: the iterative, recursive, memoization functions are more accurate than +the Binet's formula function because the Binet formula function uses floats + +NOTE 2: th...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/fibonacci.py
Create documentation strings for testing functions
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 def fa...
--- +++ @@ -1,6 +1,30 @@+""" +Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial +""" def factorial(number: int) -> int: + """ + Calculate the factorial of specified number (n!). + + >>> import math + >>> all(factorial(i) == math.factorial(i) for i in range(20)) + True + >...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/factorial.py
Document this script properly
def karatsuba(a: int, b: int) -> int: 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 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) ...
--- +++ @@ -1,6 +1,13 @@+"""Multiply two numbers using Karatsuba algorithm""" 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 @@ -22,...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/karatsuba.py
Generate consistent docstrings
from __future__ import annotations def find_max_iterative(nums: list[int | float]) -> int | float: if len(nums) == 0: raise ValueError("find_max_iterative() arg is an empty sequence") max_num = nums[0] for x in nums: if x > max_num: # noqa: PLR1730 max_num = x return max_n...
--- +++ @@ -2,6 +2,20 @@ def find_max_iterative(nums: list[int | float]) -> int | float: + """ + >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): + ... find_max_iterative(nums) == max(nums) + True + True + True + True + >>> find_max_iterative([2, 4, 9, 7, 19, 94, 5...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/find_max.py
Document this code for team use
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: max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (...
--- +++ @@ -5,6 +5,16 @@ def least_common_multiple_slow(first_num: int, second_num: int) -> int: + """ + Find the least common multiple of two numbers. + + Learn more: https://en.wikipedia.org/wiki/Least_common_multiple + + >>> least_common_multiple_slow(5, 2) + 10 + >>> least_common_multiple_slow...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/least_common_multiple.py
Add docstrings to existing functions
def floor(x: float) -> int: return int(x) if x - int(x) >= 0 else int(x) - 1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,10 +1,22 @@+""" +https://en.wikipedia.org/wiki/Floor_and_ceiling_functions +""" def floor(x: float) -> int: + """ + Return the floor of x as an Integral. + :param x: the number + :return: the largest integer <= x. + >>> import math + >>> all(floor(n) == math.floor(n) for n + ... ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/floor.py
Generate docstrings for script automation
import math from timeit import timeit def num_digits(n: int) -> int: if not isinstance(n, int): raise TypeError("Input must be an integer") digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n...
--- +++ @@ -3,6 +3,24 @@ 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 Typ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/number_of_digits.py
Generate docstrings with examples
from __future__ import annotations def find_median(nums: list[int | float]) -> float: div, mod = divmod(len(nums), 2) if mod: return nums[div] return (nums[div] + nums[(div) - 1]) / 2 def interquartile_range(nums: list[int | float]) -> float: if not nums: raise ValueError("The list ...
--- +++ @@ -1,8 +1,30 @@+""" +An implementation of interquartile range (IQR) which is a measure of statistical +dispersion, which is the spread of the data. + +The function takes the list of numeric values as input and returns the IQR. + +Script inspired by this Wikipedia article: +https://en.wikipedia.org/wiki/Interqu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/interquartile_range.py
Document functions with detailed explanations
import struct def fast_inverse_sqrt(number: float) -> float: if number <= 0: raise ValueError("Input must be a positive number.") i = struct.unpack(">i", struct.pack(">f", number))[0] i = 0x5F3759DF - (i >> 1) y = struct.unpack(">f", struct.pack(">i", i))[0] return y * (1.5 - 0.5 * number...
--- +++ @@ -1,8 +1,40 @@+""" +Fast inverse square root (1/sqrt(x)) using the Quake III algorithm. +Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root +Accuracy: https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy +""" import struct def fast_inverse_sqrt(number: float) -> float: + "...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/fast_inverse_sqrt.py
Write Python docstrings for this snippet
import math from numpy import inf from scipy.integrate import quad def gamma_iterative(num: float) -> float: if num <= 0: raise ValueError("math domain error") return quad(integrand, 0, inf, args=(num))[0] def integrand(x: float, z: float) -> float: return math.pow(x, z - 1) * math.exp(-x) ...
--- +++ @@ -1,3 +1,13 @@+""" +Gamma function is a very useful tool in math and physics. +It helps calculating complex integral in a convenient way. +for more info: https://en.wikipedia.org/wiki/Gamma_function +In mathematics, the gamma function is one commonly +used extension of the factorial function to complex number...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/gamma.py
Write docstrings that follow conventions
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) + recu...
--- +++ @@ -1,6 +1,24 @@+""" +https://en.wikipedia.org/wiki/Lucas_number +""" 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 + >>> r...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/lucas_series.py
Write reusable docstrings
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: list[...
--- +++ @@ -1,3 +1,4 @@+"""Matrix Exponentiation""" import timeit @@ -38,6 +39,21 @@ def fibonacci_with_matrix_exponentiation(n: int, f1: int, f2: int) -> int: + """ + Returns the nth number of the Fibonacci sequence that + starts with f1 and f2 + Uses the matrix exponentiation + >>> fibonacci_w...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/matrix_exponentiation.py
Can you add docstrings to this Python file?
def integer_square_root(num: int) -> int: if not isinstance(num, int) or num < 0: raise ValueError("num must be non-negative integer") if num < 2: return num left_bound = 0 right_bound = num // 2 while left_bound <= right_bound: mid = left_bound + (right_bound - left_bou...
--- +++ @@ -1,6 +1,49 @@+""" +Integer Square Root Algorithm -- An efficient method to calculate the square root of a +non-negative integer 'num' rounded down to the nearest integer. It uses a binary search +approach to find the integer square root without using any built-in exponent functions +or operators. +* https://...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/integer_square_root.py
Write docstrings describing each step
from collections import Counter 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 _: rais...
--- +++ @@ -1,3 +1,7 @@+""" +Gcd of N Numbers +Reference: https://en.wikipedia.org/wiki/Greatest_common_divisor +""" from collections import Counter @@ -5,6 +9,31 @@ def get_factors( number: int, factors: Counter | None = None, factor: int = 2 ) -> Counter: + """ + this is a recursive function for get ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/gcd_of_n_numbers.py
Can you add docstrings to this Python file?
def joint_probability_distribution( x_values: list[int], y_values: list[int], x_probabilities: list[float], y_probabilities: list[float], ) -> dict: return { (x, y): x_prob * y_prob for x, x_prob in zip(x_values, x_probabilities) for y, y_prob in zip(y_values, y_probabiliti...
--- +++ @@ -1,3 +1,7 @@+""" +Calculate joint probability distribution +https://en.wikipedia.org/wiki/Joint_probability_distribution +""" def joint_probability_distribution( @@ -6,6 +10,16 @@ x_probabilities: list[float], y_probabilities: list[float], ) -> dict: + """ + >>> joint_distribution = joi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/joint_probability_distribution.py
Document this code for team use
def josephus_recursive(num_people: int, step_size: int) -> int: if ( not isinstance(num_people, int) or not isinstance(step_size, int) or num_people <= 0 or step_size <= 0 ): raise ValueError("num_people or step_size is not a positive integer.") if num_people == 1:...
--- +++ @@ -1,6 +1,68 @@+""" +The Josephus problem is a famous theoretical problem related to a certain +counting-out game. This module provides functions to solve the Josephus problem +for num_people and a step_size. + +The Josephus problem is defined as follows: +- num_people are standing in a circle. +- Starting wit...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/josephus_problem.py
Add docstrings that explain purpose and usage
from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> float: return 1 / sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) / (2 * sigma**2)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,62 @@+""" +Reference: https://en.wikipedia.org/wiki/Gaussian_function +""" from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> float: + """ + >>> float(gaussian(1)) + 0.24197072451914337 + + >>> float(gaussian(24)) + 3.342714441794458e-126 +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/gaussian.py
Add docstrings to make code maintainable
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: if n <= 1: raise ValueError("Modulus n must be greater than 1") if a <= 0: raise ValueError("Divisor a must be a positive integer") if greatest_common_divisor(a, n) != 1: raise ValueError("a and...
--- +++ @@ -2,6 +2,32 @@ 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 ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/modular_division.py
Create docstrings for API functions
from __future__ import annotations def is_square_free(factors: list[int]) -> bool: return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,40 @@- -from __future__ import annotations - - -def is_square_free(factors: list[int]) -> bool: - return len(set(factors)) == len(factors) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +References: wikipedia:square free number +psf/black : True +ruff : True ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/is_square_free.py
Auto-generate documentation strings for this file
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def mobius(n: int) -> int: factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,16 +1,43 @@- -from maths.is_square_free import is_square_free -from maths.prime_factors import prime_factors - - -def mobius(n: int) -> int: - factors = prime_factors(n) - if is_square_free(factors): - return -1 if len(factors) % 2 else 1 - return 0 - - -if __name__ == "__main__": - imp...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/mobius_function.py
Write docstrings for data processing functions
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_factors import prime_factors def liouville_lambda(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise Va...
--- +++ @@ -1,9 +1,37 @@+""" +== Liouville Lambda Function == +The Liouville Lambda function, denoted by λ(n) +and λ(n) is 1 if n is the product of an even number of prime numbers, +and -1 if it is the product of an odd number of primes. + +https://en.wikipedia.org/wiki/Liouville_function +""" # Author : Akshay Dube...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/liouville_lambda.py
Add missing documentation to my Python functions
from __future__ import annotations 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_su...
--- +++ @@ -1,8 +1,32 @@+""" +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 b...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/max_sum_sliding_window.py
Document functions with clear intent
def method_2(boundary: list[int], steps: int) -> float: # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) if steps <= 0: raise ZeroDivisionError("Number of steps must be greater than zero") h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary...
--- +++ @@ -1,8 +1,46 @@+""" +Numerical integration or quadrature for a smooth function f with known values at x_i + +This method is the classical approach of summing 'Equally Spaced Abscissas' + +method 2: +"Simpson Rule" + +""" def method_2(boundary: list[int], steps: int) -> float: # "Simpson Rule" # ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/simpson_rule.py
Add documentation for all methods
def is_ip_v4_address_valid(ip: str) -> bool: octets = ip.split(".") if len(octets) != 4: return False for octet in octets: if not octet.isdigit(): return False number = int(octet) if len(str(number)) != len(octet): return False if not 0 <=...
--- +++ @@ -1,6 +1,56 @@+""" +wiki: https://en.wikipedia.org/wiki/IPv4 + +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 0-255 +for example: 192.168.23.1, 172.255.255.255 are valid IP address + 192.168.256.0, 256.192.3.121 are in...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/is_ip_v4_address_valid.py
Add docstrings to clarify complex logic
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): return cls(x=random.random(), y=random.random()) def e...
--- +++ @@ -7,14 +7,42 @@ self.y = y def is_in_unit_circle(self) -> bool: + """ + True, if the point lies in the unit circle + False, otherwise + """ return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): + """ + Genera...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/pi_monte_carlo_estimation.py
Generate NumPy-style docstrings
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))) def _valid...
--- +++ @@ -1,4 +1,39 @@ 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_di...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/manhattan_distance.py
Add docstrings explaining edge cases
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={numb...
--- +++ @@ -1,9 +1,44 @@+""" +== 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.wikiped...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/juggler_sequence.py
Generate docstrings for each module
import math from collections.abc import Generator def slow_primes(max_n: int) -> Generator[int]: 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 ...
--- +++ @@ -3,6 +3,23 @@ def slow_primes(max_n: int) -> Generator[int]: + """ + Return a list of all primes numbers up to max. + >>> list(slow_primes(0)) + [] + >>> list(slow_primes(-1)) + [] + >>> list(slow_primes(-10)) + [] + >>> list(slow_primes(25)) + [2, 3, 5, 7, 11, 13, 17, 19, 2...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/prime_numbers.py
Add concise docstrings to each method
from collections.abc import Callable from dataclasses import dataclass import numpy as np @dataclass class AdamsBashforth: func: Callable[[float, float], float] x_initials: list[float] y_initials: list[float] step_size: float x_final: float def __post_init__(self) -> None: if self....
--- +++ @@ -1,3 +1,9 @@+""" +Use the Adams-Bashforth methods to solve Ordinary Differential Equations. + +https://en.wikipedia.org/wiki/Linear_multistep_method +Author : Ravi Kumar +""" from collections.abc import Callable from dataclasses import dataclass @@ -7,6 +13,35 @@ @dataclass class AdamsBashforth: + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/adams_bashforth.py
Add docstrings to incomplete code
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,6 +1,39 @@+""" +Python program to show how to interpolate and evaluate a polynomial +using Neville's method. +Neville's 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.com/aaron...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/nevilles_method.py
Generate NumPy-style docstrings
"""Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod ...
--- +++ @@ -1,8 +1,22 @@+""" +Modular Exponential. +Modular exponentiation is a type of exponentiation performed over a modulus. +For more explanation, please check +https://en.wikipedia.org/wiki/Modular_exponentiation +""" """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod:...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/modular_exponential.py
Fully document this Python code with docstrings
Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: x = end_point2[0] - end_point1[0] y = end_point2[1] - end_point1[1] z = end_point2[2] - end_point1[2] return (x, y, z) def get_3d_vectors_cross(ab: Vec...
--- +++ @@ -1,9 +1,48 @@+""" +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 ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/points_are_collinear_3d.py
Write Python docstrings for this snippet
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def pi_estimator(iterations: int) -> None: # A local function to see if a dot lands in the circle. def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x**2) + ...
--- +++ @@ -1,3 +1,6 @@+""" +@author: MatteoRaso +""" from collections.abc import Callable from math import pi, sqrt @@ -6,6 +9,16 @@ def pi_estimator(iterations: int) -> None: + """ + An implementation of the Monte Carlo method used to find pi. + 1. Draw a 2x2 square centred at (0,0). + 2. Inscribe...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/monte_carlo.py
Add detailed documentation for each class
def jaccard_similarity( set_a: set[str] | list[str] | tuple[str], set_b: set[str] | list[str] | tuple[str], alternative_union=False, ): if isinstance(set_a, set) and isinstance(set_b, set): intersection_length = len(set_a.intersection(set_b)) if alternative_union: union_l...
--- +++ @@ -1,3 +1,17 @@+""" +The Jaccard similarity coefficient is a commonly used indicator of the +similarity between two sets. Let U be a set and A and B be subsets of U, +then the Jaccard index/similarity is defined to be the ratio of the number +of elements of their intersection and the number of elements of thei...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/jaccard_similarity.py
Create documentation for each function signature
from math import factorial, pi 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_s...
--- +++ @@ -1,48 +1,123 @@- -from math import factorial, pi - - -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: -...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/maclaurin_series.py
Add missing documentation to my Python functions
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 ...
--- +++ @@ -1,6 +1,34 @@+""" +Sieve of Eratosthenes + +Input: n = 10 +Output: 2 3 5 7 + +Input: n = 20 +Output: 2 3 5 7 11 13 17 19 + +you can read in detail about this at +https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes +""" def prime_sieve_eratosthenes(num: int) -> list[int]: + """ + Print the prime nu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/prime_sieve_eratosthenes.py
Document functions with detailed explanations
def is_harmonic_series(series: list) -> bool: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [1, 2/3, 2]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1 and series[0] != 0: return True ...
--- +++ @@ -1,6 +1,42 @@+""" +Harmonic mean +Reference: https://en.wikipedia.org/wiki/Harmonic_mean + +Harmonic series +Reference: https://en.wikipedia.org/wiki/Harmonic_series(mathematics) +""" def is_harmonic_series(series: list) -> bool: + """ + checking whether the input series is arithmetic series or no...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/harmonic.py
Add professional docstrings to my codebase
from __future__ import annotations def prime_factors(n: int) -> list[int]: i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors def unique_prime_factors(n: int...
--- +++ @@ -1,8 +1,39 @@+""" +python/black : True +""" from __future__ import annotations def prime_factors(n: int) -> list[int]: + """ + Returns prime factors of n as a list. + + >>> prime_factors(0) + [] + >>> prime_factors(100) + [2, 2, 5, 5] + >>> prime_factors(2560) + [2, 2, 2, 2, 2...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/prime_factors.py
Write docstrings for backend logic
import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a...
--- +++ @@ -1,3 +1,4 @@+"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math @@ -13,10 +14,16 @@ def distance(a: Point, b: Point) -> float: + """ + >>> point1 = Point(2, -1, 7) + >>> point2 = Point(1, -3, 5) + >>> print(f"Distance from {point1} to {point2...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/pythagoras.py
Insert docstrings into my code
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2")...
--- +++ @@ -9,6 +9,31 @@ 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 factorization. + If the algorithm will return None if it fails to find a factor withi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/pollard_rho.py
Improve documentation using docstrings
import math def perfect_square(num: int) -> bool: return math.sqrt(num) * math.sqrt(num) == num def perfect_square_binary_search(n: int) -> bool: left = 0 right = n while left <= right: mid = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: ...
--- +++ @@ -2,10 +2,58 @@ 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 + >...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/perfect_square.py
Write docstrings that follow conventions
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: x_n: float = x0 x_n1: float = x1 while True: if x_n == x_n1 or function(x_n1) == function(x_n): raise ZeroDivisionError("float division by zero, could n...
--- +++ @@ -3,6 +3,30 @@ 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 + >>> intersection(lambda...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/intersection.py
Help me comply with documentation standards
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-vector)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,39 @@+""" +This script demonstrates the implementation of the Sigmoid function. + +The function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)). +After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1. + +Script inspired from its corresponding Wikip...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sigmoid.py
Fill in missing docstrings in my code
# 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 ...
--- +++ @@ -1,3 +1,17 @@+""" +Author : Syed Faizan ( 3rd Year IIIT Pune ) +Github : faizan2700 + +Purpose : You have one function f(x) which takes float integer and returns +float you have to integrate the function in limits a to b. +The approximation proposed by Thomas Simpson in 1743 is one way to calculate +integrat...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/integration_by_simpson_approx.py
Write docstrings for backend logic
def harmonic_series(n_term: str) -> list: if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Ser...
--- +++ @@ -1,6 +1,37 @@+""" +This is a pure Python implementation of the Harmonic Series algorithm +https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) + +For doctests run following command: +python -m doctest -v harmonic_series.py +or +python3 -m doctest -v harmonic_series.py + +For manual testing run: +pytho...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/harmonic_series.py
Document functions with clear intent
from collections.abc import Callable import numpy as np def runge_kutta_fehlberg_45( func: Callable, x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: if x_initial >= x_final: raise ValueError( "The final value of x must be greater tha...
--- +++ @@ -1,3 +1,6 @@+""" +Use the Runge-Kutta-Fehlberg method to solve Ordinary Differential Equations. +""" from collections.abc import Callable @@ -11,6 +14,50 @@ step_size: float, x_final: float, ) -> np.ndarray: + """ + Solve an Ordinary Differential Equations using Runge-Kutta-Fehlberg Meth...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/runge_kutta_fehlberg_45.py
Add docstrings to incomplete code
def equation(x: float) -> float: return 10 - x * x def bisection(a: float, b: float) -> float: # Bolzano theory in order to find if there is a root between a and b if equation(a) * equation(b) >= 0: raise ValueError("Wrong space!") c = a while (b - a) >= 0.01: # Find middle poin...
--- +++ @@ -1,10 +1,40 @@+""" +Given a function on floating number f(x) and two floating numbers `a` and `b` such that +f(a) * f(b) < 0 and f(x) is continuous in [a, b]. +Here f(x) represents algebraic or transcendental equation. +Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0) + +ht...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/bisection_2.py
Help me add docstrings to my project
def hexagonal_numbers(length: int) -> list[int]: if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length...
--- +++ @@ -1,12 +1,42 @@- - -def hexagonal_numbers(length: int) -> list[int]: - - if length <= 0 or not isinstance(length, int): - raise ValueError("Length must be a positive integer.") - return [n * (2 * n - 1) for n in range(length)] - - -if __name__ == "__main__": - print(hexagonal_numbers(length=5)...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/hexagonal_numbers.py
Help me add docstrings to my project
def is_arithmetic_series(series: list) -> bool: if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = s...
--- +++ @@ -1,6 +1,31 @@+""" +Arithmetic mean +Reference: https://en.wikipedia.org/wiki/Arithmetic_mean + +Arithmetic series +Reference: https://en.wikipedia.org/wiki/Arithmetic_series +(The URL above will redirect you to arithmetic progression) +""" def is_arithmetic_series(series: list) -> bool: + """ + ch...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/arithmetic.py
Add docstrings that explain purpose and usage
def signum(num: float) -> int: if num < 0: return -1 return 1 if num else 0 def test_signum() -> None: assert signum(5) == 1 assert signum(-5) == -1 assert signum(0) == 0 assert signum(10.5) == 1 assert signum(-10.5) == -1 assert signum(1e-6) == 1 assert signum(-1e-6) == ...
--- +++ @@ -1,12 +1,46 @@+""" +Signum function -- https://en.wikipedia.org/wiki/Sign_function +""" def signum(num: float) -> int: + """ + Applies signum function on the number + + Custom test cases: + >>> signum(-10) + -1 + >>> signum(10) + 1 + >>> signum(0) + 0 + >>> signum(-20.5) + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/signum.py
Generate docstrings with parameter types
from collections.abc import Callable RealFunc = Callable[[float], float] def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: return (f(x + delta_x / 2) - f(x - delta_x / 2)) / delta_x def newton_raphson( f: RealFunc, x0: float = 0, max_iter: int = 100, step: float = 1e-...
--- +++ @@ -1,3 +1,14 @@+""" +The Newton-Raphson method (aka the Newton method) is a root-finding algorithm that +approximates a root of a given real-valued function f(x). It is an iterative method +given by the formula + +x_{n + 1} = x_n + f(x_n) / f'(x_n) + +with the precision of the approximation increasing as the n...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/newton_raphson.py
Help me comply with documentation standards
from __future__ import annotations import math def prime_sieve(num: int) -> list[int]: if num <= 0: msg = f"{num}: Invalid input, please enter a positive integer." raise ValueError(msg) sieve = [True] * (num + 1) prime = [] start = 2 end = int(math.sqrt(num)) while start <...
--- +++ @@ -1,38 +1,66 @@- -from __future__ import annotations - -import math - - -def prime_sieve(num: int) -> list[int]: - - if num <= 0: - msg = f"{num}: Invalid input, please enter a positive integer." - raise ValueError(msg) - - sieve = [True] * (num + 1) - prime = [] - start = 2 - end...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sieve_of_eratosthenes.py
Create structured documentation for my script
from collections.abc import Sequence def assign_ranks(data: Sequence[float]) -> list[int]: ranked_data = sorted((value, index) for index, value in enumerate(data)) ranks = [0] * len(data) for position, (_, index) in enumerate(ranked_data): ranks[index] = position + 1 return ranks def calcu...
--- +++ @@ -2,6 +2,19 @@ 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] + + >>>...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/spearman_rank_correlation_coefficient.py
Fill in missing docstrings in my code
import numpy as np def softmax(vector): # Calculate e^x for each x in your vector where e is Euler's # number (approximately 2.718) exponent_vector = np.exp(vector) # Add up the all the exponentials sum_of_exponents = np.sum(exponent_vector) # Divide every exponent by the sum of all expone...
--- +++ @@ -1,8 +1,43 @@+""" +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...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/softmax.py
Add docstrings that explain inputs and outputs
from math import factorial, radians def sin( angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10 ) -> float: # Simplify the angle to be between 360 and -360 degrees. angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radia...
--- +++ @@ -1,3 +1,15 @@+""" +Calculate sin function. + +It's not a perfect function so I am rounding the result to 10 decimal places by default. + +Formula: sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ... +Where: x = angle in randians. + +Source: + https://www.homeschoolmath.net/teaching/sine_calculator.php + +""" f...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sin.py
Write docstrings for utility functions
def simplify(current_set: list[list]) -> list[list]: # Divide each row by magnitude of first term --> creates 'unit' matrix duplicate_set = current_set.copy() for row_index, row in enumerate(duplicate_set): magnitude = row[0] for column_index, column in enumerate(row): if magni...
--- +++ @@ -1,105 +1,142 @@- - -def simplify(current_set: list[list]) -> list[list]: - # Divide each row by magnitude of first term --> creates 'unit' matrix - duplicate_set = current_set.copy() - for row_index, row in enumerate(duplicate_set): - magnitude = row[0] - for column_index, column in e...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/simultaneous_linear_equation_solver.py
Write reusable docstrings
from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 == 1: temp = (temp * x) % mod return temp def is_carmichael_number(n: int) ->...
--- +++ @@ -1,8 +1,27 @@+""" +== Carmichael Numbers == +A number n is said to be a Carmichael number if it +satisfies the following modular arithmetic condition: + + power(b, n-1) MOD n = 1, + for all b ranging from 1 to n such that b and + n are relatively prime, i.e, gcd(b, n) = 1 + +Examples of Carmichael N...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/carmichael_number.py
Generate docstrings with examples
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0: return False n...
--- +++ @@ -1,9 +1,44 @@+""" +== 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.org/wiki/Automorphic_number +""" # Author : Akshay...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/automorphic_number.py
Write docstrings for utility functions
PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) def armstrong_number(n: int) -> bool: if not isinstance(n, int) or n < 1: return False # Initialization of sum and number of digits. total = 0 num...
--- +++ @@ -1,9 +1,27 @@+""" +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 3*3*3 + 7*7*7 + 0*0*0 = 370. + +Armstrong numbers are also called Narcissistic numbers and Pluperfect numbers. + +On-Line Encyclop...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/armstrong_numbers.py
Help me document legacy Python code
def bell_numbers(max_set_length: int) -> list[int]: if max_set_length < 0: raise ValueError("max_set_length must be non-negative") bell = [0] * (max_set_length + 1) bell[0] = 1 for i in range(1, max_set_length + 1): for j in range(i): bell[i] += _binomial_coefficient(i - ...
--- +++ @@ -1,6 +1,37 @@+""" +Bell numbers represent the number of ways to partition a set into non-empty +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....
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/bell_numbers.py
Write documentation strings for class attributes
def catalan(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) current_number = 1 for i in ...
--- +++ @@ -1,6 +1,34 @@+""" + +Calculate the nth Catalan number + +Source: + https://en.wikipedia.org/wiki/Catalan_number + +""" 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 pos...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/catalan_number.py
Help me document legacy Python code
def hamming(n_element: int) -> list: n_element = int(n_element) if n_element < 1: my_error = ValueError("n_element 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 <= hammin...
--- +++ @@ -1,6 +1,29 @@+""" +A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some +non-negative integers i, j, and k. They are often referred to as regular numbers. +More info at: https://en.wikipedia.org/wiki/Regular_number. +""" def hamming(n_element: int) -> list: + """ + This functio...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/hamming_numbers.py
Write docstrings for this repository
def int_to_base(number: int, base: int) -> str: if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" if number < 0: raise ValueError("number must be a positive integer") while number ...
--- +++ @@ -1,6 +1,38 @@+""" +A harshad number (or more specifically an n-harshad number) is a number that's +divisible by the sum of its digits in some given base n. +Reference: https://en.wikipedia.org/wiki/Harshad_number +""" def int_to_base(number: int, base: int) -> str: + """ + Convert a given positive...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/harshad_numbers.py
Document classes and their methods
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def hexagonal(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise ValueError("Input must be a positive integer") retu...
--- +++ @@ -1,8 +1,40 @@+""" +== 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.org/wiki/Hexagonal_number...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/hexagonal_number.py
Add docstrings following best practices
def factorial(digit: int) -> int: return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: fact_sum = 0 duplicate = number while duplicate > 0: duplicate, digit = divmod(duplicate, 10) fact_sum += factorial(digit) return fact_sum =...
--- +++ @@ -1,11 +1,37 @@+""" + == 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 +""" def factorial(digit: in...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/krishnamurthy_number.py
Create docstrings for each class method
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def is_pronic(number: int) -> bool: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0 or number % 2 == 1: return False number_sqrt = int(number...
--- +++ @@ -1,8 +1,45 @@+""" +== 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.org/wiki/Pronic_number +""" # Author : Akshay Dubey (https://github.com/i...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/pronic_number.py
Document this module using docstrings
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: ...
--- +++ @@ -1,6 +1,30 @@+""" +Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence +1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, +1 is included. +Given an integer n, we have to find the nth ugly number. + +For more details, refer this article +https://ww...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/ugly_numbers.py
Create simple docstrings for beginners
def triangular_number(position: int) -> int: if position < 0: raise ValueError("param `position` must be non-negative") return position * (position + 1) // 2 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,36 @@+""" +A triangular number or triangle number counts objects arranged in an +equilateral triangle. This module provides a function to generate n'th +triangular number. + +For more information about triangular numbers, refer to: +https://en.wikipedia.org/wiki/Triangular_number +""" def triang...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/triangular_numbers.py