instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add missing documentation to my Python functions
from math import sqrt def factors(number: int) -> list[int]: values = [1] for i in range(2, int(sqrt(number)) + 1, 1): if number % i == 0: values.append(i) if int(number // i) != i: values.append(int(number // i)) return sorted(values) def abundant(n: int) -> bool: return sum(factors(n)) > n def semi_perfect(number: int) -> bool: values = factors(number) r = len(values) subset = [[0 for i in range(number + 1)] for j in range(r + 1)] for i in range(r + 1): subset[i][0] = True for i in range(1, number + 1): subset[0][i] = False for i in range(1, r + 1): for j in range(1, number + 1): if j < values[i - 1]: subset[i][j] = subset[i - 1][j] else: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - values[i - 1]] return subset[r][number] != 0 def weird(number: int) -> bool: return abundant(number) and not semi_perfect(number) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) for number in (69, 70, 71): print(f"{number} is {'' if weird(number) else 'not '}weird.")
--- +++ @@ -1,8 +1,24 @@+""" +https://en.wikipedia.org/wiki/Weird_number + +Fun fact: The set of weird numbers has positive asymptotic density. +""" from math import sqrt def factors(number: int) -> list[int]: + """ + >>> factors(12) + [1, 2, 3, 4, 6] + >>> factors(1) + [1] + >>> factors(100) + [1, 2, 4, 5, 10, 20, 25, 50] + + # >>> factors(-12) + # [1, 2, 3, 4, 6] + """ values = [1] for i in range(2, int(sqrt(number)) + 1, 1): @@ -14,10 +30,38 @@ def abundant(n: int) -> bool: + """ + >>> abundant(0) + True + >>> abundant(1) + False + >>> abundant(12) + True + >>> abundant(13) + False + >>> abundant(20) + True + + # >>> abundant(-12) + # True + """ return sum(factors(n)) > n def semi_perfect(number: int) -> bool: + """ + >>> semi_perfect(0) + True + >>> semi_perfect(1) + True + >>> semi_perfect(12) + True + >>> semi_perfect(13) + False + + # >>> semi_perfect(-12) + # True + """ values = factors(number) r = len(values) subset = [[0 for i in range(number + 1)] for j in range(r + 1)] @@ -38,6 +82,14 @@ def weird(number: int) -> bool: + """ + >>> weird(0) + False + >>> weird(70) + True + >>> weird(77) + False + """ return abundant(number) and not semi_perfect(number) @@ -46,4 +98,4 @@ doctest.testmod(verbose=True) for number in (69, 70, 71): - print(f"{number} is {'' if weird(number) else 'not '}weird.")+ print(f"{number} is {'' if weird(number) else 'not '}weird.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/weird_number.py
Include argument descriptions in docstrings
def sum_of_digits(n: int) -> int: n = abs(n) res = 0 while n > 0: res += n % 10 n //= 10 return res def sum_of_digits_recursion(n: int) -> int: n = abs(n) return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: return sum(int(c) for c in str(abs(n))) def benchmark() -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") print(f"{call:56} = {func(value)} -- {timing:.4f} seconds") for value in (262144, 1125899906842624, 1267650600228229401496703205376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
--- +++ @@ -1,4 +1,15 @@ def sum_of_digits(n: int) -> int: + """ + Find the sum of digits of a number. + >>> sum_of_digits(12345) + 15 + >>> sum_of_digits(123) + 6 + >>> sum_of_digits(-123) + 6 + >>> sum_of_digits(0) + 0 + """ n = abs(n) res = 0 while n > 0: @@ -8,15 +19,40 @@ def sum_of_digits_recursion(n: int) -> int: + """ + Find the sum of digits of a number using recursion + >>> sum_of_digits_recursion(12345) + 15 + >>> sum_of_digits_recursion(123) + 6 + >>> sum_of_digits_recursion(-123) + 6 + >>> sum_of_digits_recursion(0) + 0 + """ n = abs(n) return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: + """ + Find the sum of digits of a number + >>> sum_of_digits_compact(12345) + 15 + >>> sum_of_digits_compact(123) + 6 + >>> sum_of_digits_compact(-123) + 6 + >>> sum_of_digits_compact(0) + 0 + """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: + """ + Benchmark multiple functions, with three different length int values. + """ from collections.abc import Callable from timeit import timeit @@ -35,4 +71,4 @@ import doctest doctest.testmod() - benchmark()+ benchmark()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sum_of_digits.py
Document all public functions with docstrings
import math def proth(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) elif number == 1: return 3 elif number == 2: return 5 else: """ +1 for binary starting at 0 i.e. 2^0, 2^1, etc. +1 to start the sequence at the 3rd Proth number Hence, we have a +2 in the below statement """ block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for _ in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] def is_proth_number(number: int) -> bool: if not isinstance(number, int): message = f"Input value of [{number=}] must be an integer" raise TypeError(message) if number <= 0: message = f"Input value of [{number=}] must be > 0" raise ValueError(message) if number == 1: return False number -= 1 n = 0 while number % 2 == 0: n += 1 number //= 2 return number < 2**n if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}") for number in [1, 2, 3, 4, 5, 9, 13, 49, 57, 193, 241, 163, 201]: if is_proth_number(number): print(f"{number} is a Proth number") else: print(f"{number} is not a Proth number")
--- +++ @@ -1,8 +1,32 @@+""" +Calculate the nth Proth number +Source: + https://handwiki.org/wiki/Proth_number +""" import math def proth(number: int) -> int: + """ + :param number: nth number to calculate in the sequence + :return: the nth number in Proth number + Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3 + >>> proth(6) + 25 + >>> proth(0) + Traceback (most recent call last): + ... + ValueError: Input value of [number=0] must be > 0 + >>> proth(-1) + Traceback (most recent call last): + ... + ValueError: Input value of [number=-1] must be > 0 + >>> proth(6.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=6.0] must be an integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" @@ -36,6 +60,30 @@ def is_proth_number(number: int) -> bool: + """ + :param number: positive integer number + :return: true if number is a Proth number, false otherwise + >>> is_proth_number(1) + False + >>> is_proth_number(2) + False + >>> is_proth_number(3) + True + >>> is_proth_number(4) + False + >>> is_proth_number(5) + True + >>> is_proth_number(34) + False + >>> is_proth_number(-1) + Traceback (most recent call last): + ... + ValueError: Input value of [number=-1] must be > 0 + >>> is_proth_number(6.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=6.0] must be an integer + """ if not isinstance(number, int): message = f"Input value of [{number=}] must be an integer" raise TypeError(message) @@ -74,4 +122,4 @@ if is_proth_number(number): print(f"{number} is a Proth number") else: - print(f"{number} is not a Proth number")+ print(f"{number} is not a Proth number")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/proth_number.py
Document all public functions with docstrings
def perfect(number: int) -> bool: if not isinstance(number, int): raise ValueError("number must be an integer") if number <= 0: return False return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": from doctest import testmod testmod() print("Program to check whether a number is a Perfect number or not...") try: number = int(input("Enter a positive integer: ").strip()) except ValueError: msg = "number must be an integer" print(msg) raise ValueError(msg) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
--- +++ @@ -1,6 +1,62 @@+""" +== Perfect Number == +In number theory, a perfect number is a positive integer that is equal to the sum of +its positive divisors, excluding the number itself. +For example: 6 ==> divisors[1, 2, 3, 6] + Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 + So, 6 is a Perfect Number + +Other examples of Perfect Numbers: 28, 486, ... + +https://en.wikipedia.org/wiki/Perfect_number +""" def perfect(number: int) -> bool: + """ + Check if a number is a perfect number. + + A perfect number is a positive integer that is equal to the sum of its proper + divisors (excluding itself). + + Args: + number: The number to be checked. + + Returns: + True if the number is a perfect number, False otherwise. + + Start from 1 because dividing by 0 will raise ZeroDivisionError. + A number at most can be divisible by the half of the number except the number + itself. For example, 6 is at most can be divisible by 3 except by 6 itself. + + Examples: + >>> perfect(27) + False + >>> perfect(28) + True + >>> perfect(29) + False + >>> perfect(6) + True + >>> perfect(12) + False + >>> perfect(496) + True + >>> perfect(8128) + True + >>> perfect(0) + False + >>> perfect(-1) + False + >>> perfect(12.34) + Traceback (most recent call last): + ... + ValueError: number must be an integer + >>> perfect("Hello") + Traceback (most recent call last): + ... + ValueError: number must be an integer + """ if not isinstance(number, int): raise ValueError("number must be an integer") if number <= 0: @@ -20,4 +76,4 @@ print(msg) raise ValueError(msg) - print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")+ print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/special_numbers/perfect_number.py
Create documentation for each function signature
def sumset(set_a: set, set_b: set) -> set: assert isinstance(set_a, set), f"The input value of [set_a={set_a}] is not a set" assert isinstance(set_b, set), f"The input value of [set_b={set_b}] is not a set" return {a + b for a in set_a for b in set_b} if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -1,6 +1,30 @@+""" + +Calculates the SumSet of two sets of numbers (A and B) + +Source: + https://en.wikipedia.org/wiki/Sumset + +""" def sumset(set_a: set, set_b: set) -> set: + """ + :param first set: a set of numbers + :param second set: a set of numbers + :return: the nth number in Sylvester's sequence + + >>> sumset({1, 2, 3}, {4, 5, 6}) + {5, 6, 7, 8, 9} + + >>> sumset({1, 2, 3}, {4, 5, 6, 7}) + {5, 6, 7, 8, 9, 10} + + >>> sumset({1, 2, 3, 4}, 3) + Traceback (most recent call last): + ... + AssertionError: The input value of [set_b=3] is not a set + """ assert isinstance(set_a, set), f"The input value of [set_a={set_a}] is not a set" assert isinstance(set_b, set), f"The input value of [set_b={set_b}] is not a set" @@ -10,4 +34,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sumset.py
Add docstrings including usage examples
def trapezoidal_rule(boundary, steps): h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 2.0) * f(a) for i in x_i: y += h * f(i) y += (h / 2.0) * f(b) return y def make_points(a, b, h): x = a + h while x <= (b - h): yield x x += h def f(x): return x**2 def main(): a = 0.0 b = 1.0 steps = 10.0 boundary = [a, b] y = trapezoidal_rule(boundary, steps) print(f"y = {y}") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -1,6 +1,26 @@+""" +Numerical integration or quadrature for a smooth function f with known values at x_i +""" def trapezoidal_rule(boundary, steps): + """ + Implements the extended trapezoidal rule for numerical integration. + The function f(x) is provided below. + + :param boundary: List containing the lower and upper bounds of integration [a, b] + :param steps: The number of steps (intervals) used in the approximation + :return: The numerical approximation of the integral + + >>> abs(trapezoidal_rule([0, 1], 10) - 0.33333) < 0.01 + True + >>> abs(trapezoidal_rule([0, 1], 100) - 0.33333) < 0.01 + True + >>> abs(trapezoidal_rule([0, 2], 1000) - 2.66667) < 0.01 + True + >>> abs(trapezoidal_rule([1, 2], 1000) - 2.33333) < 0.01 + True + """ h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] @@ -14,6 +34,28 @@ def make_points(a, b, h): + """ + Generates points between a and b with step size h for trapezoidal integration. + + :param a: The lower bound of integration + :param b: The upper bound of integration + :param h: The step size + :yield: The next x-value in the range (a, b) + + >>> list(make_points(0, 1, 0.1)) # doctest: +NORMALIZE_WHITESPACE + [0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, \ + 0.8999999999999999] + >>> list(make_points(0, 10, 2.5)) + [2.5, 5.0, 7.5] + >>> list(make_points(0, 10, 2)) + [2, 4, 6, 8] + >>> list(make_points(1, 21, 5)) + [6, 11, 16] + >>> list(make_points(1, 5, 2)) + [3] + >>> list(make_points(1, 4, 3)) + [] + """ x = a + h while x <= (b - h): yield x @@ -21,10 +63,33 @@ def f(x): + """ + This is the function to integrate, f(x) = (x - 0)^2 = x^2. + + :param x: The input value + :return: The value of f(x) + + >>> f(0) + 0 + >>> f(1) + 1 + >>> f(0.5) + 0.25 + """ return x**2 def main(): + """ + Main function to test the trapezoidal rule. + :a: Lower bound of integration + :b: Upper bound of integration + :steps: define number of steps or resolution + :boundary: define boundary of integration + + >>> main() + y = 0.3349999999999999 + """ a = 0.0 b = 1.0 steps = 10.0 @@ -37,4 +102,4 @@ import doctest doctest.testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/trapezoidal_rule.py
Document my Python code with docstrings
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 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 if __name__ == "__main__": def f(x): return x**3 print("f(x) = x^3") print("The area between the curve, x = -10, x = 10 and the x axis is:") i = 10 while i <= 100000: area = trapezoidal_area(f, -5, 5, i) print(f"with {i} steps: {area}") i *= 10
--- +++ @@ -1,3 +1,6 @@+""" +Approximates the area under the curve using the trapezoidal rule +""" from __future__ import annotations @@ -10,6 +13,28 @@ x_end: float, steps: int = 100, ) -> float: + """ + Treats curve as a collection of linear lines and sums the area of the + trapezium shape they form + :param fnc: a function which defines a curve + :param x_start: left end point to indicate the start of line segment + :param x_end: right end point to indicate end of line segment + :param steps: an accuracy gauge; more steps increases the accuracy + :return: a float representing the length of the curve + + >>> def f(x): + ... return 5 + >>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000) + '10.000' + + >>> def f(x): + ... return 9*x**2 + >>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000) + '192.0000' + + >>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000) + '384.0000' + """ x1 = x_start fx1 = fnc(x_start) area = 0.0 @@ -38,4 +63,4 @@ while i <= 100000: area = trapezoidal_area(f, -5, 5, i) print(f"with {i} steps: {area}") - i *= 10+ i *= 10
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/numerical_integration.py
Add docstrings including usage examples
def three_sum(nums: list[int]) -> list[list[int]]: nums.sort() ans = [] for i in range(len(nums) - 2): if i == 0 or (nums[i] != nums[i - 1]): low, high, c = i + 1, len(nums) - 1, 0 - nums[i] while low < high: if nums[low] + nums[high] == c: ans.append([nums[i], nums[low], nums[high]]) while low < high and nums[low] == nums[low + 1]: low += 1 while low < high and nums[high] == nums[high - 1]: high -= 1 low += 1 high -= 1 elif nums[low] + nums[high] < c: low += 1 else: high -= 1 return ans if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,23 @@+""" +https://en.wikipedia.org/wiki/3SUM +""" def three_sum(nums: list[int]) -> list[list[int]]: + """ + Find all unique triplets in a sorted array of integers that sum up to zero. + + Args: + nums: A sorted list of integers. + + Returns: + A list of lists containing unique triplets that sum up to zero. + + >>> three_sum([-1, 0, 1, 2, -1, -4]) + [[-1, -1, 2], [-1, 0, 1]] + >>> three_sum([1, 2, 3, 4]) + [] + """ nums.sort() ans = [] for i in range(len(nums) - 2): @@ -27,4 +44,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/three_sum.py
Add minimal docstrings for each function
import numpy as np def tangent_hyperbolic(vector: np.ndarray) -> np.ndarray: return (2 / (1 + np.exp(-2 * vector))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,38 @@+""" +This script demonstrates the implementation of the tangent hyperbolic +or tanh function. + +The function takes a vector of K real numbers as input and +then (e^x - e^(-x))/(e^x + e^(-x)). After through tanh, the +element of the vector mostly -1 between 1. + +Script inspired from its corresponding Wikipedia article +https://en.wikipedia.org/wiki/Activation_function +""" import numpy as np def tangent_hyperbolic(vector: np.ndarray) -> np.ndarray: + """ + Implements the tanh function + + Parameters: + vector: np.ndarray + + Returns: + tanh (np.array): The input numpy array after applying tanh. + + mathematically (e^x - e^(-x))/(e^x + e^(-x)) can be written as (2/(1+e^(-2x))-1 + + Examples: + >>> tangent_hyperbolic(np.array([1,5,6,-0.67])) + array([ 0.76159416, 0.9999092 , 0.99998771, -0.58497988]) + + >>> tangent_hyperbolic(np.array([8,10,2,-0.98,13])) + array([ 0.99999977, 1. , 0.96402758, -0.7530659 , 1. ]) + + """ return (2 / (1 + np.exp(-2 * vector))) - 1 @@ -10,4 +40,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/tanh.py
Write docstrings for utility functions
from __future__ import annotations def two_pointer(nums: list[int], target: int) -> list[int]: i = 0 j = len(nums) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: i = i + 1 else: j = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_pointer([2, 7, 11, 15], 9) = }")
--- +++ @@ -1,8 +1,45 @@+""" +Given a sorted array of integers, return indices of the two numbers such +that they add up to a specific target using the two pointers technique. + +You may assume that each input would have exactly one solution, and you +may not use the same element twice. + +This is an alternative solution of the two-sum problem, which uses a +map to solve the problem. Hence can not solve the issue if there is a +constraint not use the same index twice. [1] + +Example: +Given nums = [2, 7, 11, 15], target = 9, + +Because nums[0] + nums[1] = 2 + 7 = 9, +return [0, 1]. + +[1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py +""" from __future__ import annotations def two_pointer(nums: list[int], target: int) -> list[int]: + """ + >>> two_pointer([2, 7, 11, 15], 9) + [0, 1] + >>> two_pointer([2, 7, 11, 15], 17) + [0, 3] + >>> two_pointer([2, 7, 11, 15], 18) + [1, 2] + >>> two_pointer([2, 7, 11, 15], 26) + [2, 3] + >>> two_pointer([1, 3, 3], 6) + [1, 2] + >>> two_pointer([2, 7, 11, 15], 8) + [] + >>> two_pointer([3 * i for i in range(10)], 19) + [] + >>> two_pointer([1, 2, 3], 6) + [] + """ i = 0 j = len(nums) - 1 @@ -21,4 +58,4 @@ import doctest doctest.testmod() - print(f"{two_pointer([2, 7, 11, 15], 9) = }")+ print(f"{two_pointer([2, 7, 11, 15], 9) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/two_pointer.py
Generate missing documentation strings
def generate_large_matrix() -> list[list[int]]: return [list(range(1000 - i, -1000 - i, -1)) for i in range(1000)] grid = generate_large_matrix() test_grids = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def validate_grid(grid: list[list[int]]) -> None: assert all(row == sorted(row, reverse=True) for row in grid) assert all(list(col) == sorted(col, reverse=True) for col in zip(*grid)) def find_negative_index(array: list[int]) -> int: left = 0 right = len(array) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: mid = (left + right) // 2 num = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: left = mid + 1 else: right = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(array) def count_negatives_binary_search(grid: list[list[int]]) -> int: total = 0 bound = len(grid[0]) for i in range(len(grid)): bound = find_negative_index(grid[i][:bound]) total += bound return (len(grid) * len(grid[0])) - total def count_negatives_brute_force(grid: list[list[int]]) -> int: return len([number for row in grid for number in row if number < 0]) def count_negatives_brute_force_with_break(grid: list[list[int]]) -> int: total = 0 for row in grid: for i, number in enumerate(row): if number < 0: total += len(row) - i break return total def benchmark() -> None: from timeit import timeit print("Running benchmarks") setup = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): time = timeit(f"{func}(grid=grid)", setup=setup, number=500) print(f"{func}() took {time:0.4f} seconds") if __name__ == "__main__": import doctest doctest.testmod() benchmark()
--- +++ @@ -1,6 +1,16 @@+""" +Given an matrix of numbers in which all rows and all columns are sorted in decreasing +order, return the number of negative numbers in grid. + +Reference: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix +""" def generate_large_matrix() -> list[list[int]]: + """ + >>> generate_large_matrix() # doctest: +ELLIPSIS + [[1000, ..., -999], [999, ..., -1001], ..., [2, ..., -1998]] + """ return [list(range(1000 - i, -1000 - i, -1)) for i in range(1000)] @@ -15,11 +25,40 @@ def validate_grid(grid: list[list[int]]) -> None: + """ + Validate that the rows and columns of the grid is sorted in decreasing order. + >>> for grid in test_grids: + ... validate_grid(grid) + """ assert all(row == sorted(row, reverse=True) for row in grid) assert all(list(col) == sorted(col, reverse=True) for col in zip(*grid)) def find_negative_index(array: list[int]) -> int: + """ + Find the smallest negative index + + >>> find_negative_index([0,0,0,0]) + 4 + >>> find_negative_index([4,3,2,-1]) + 3 + >>> find_negative_index([1,0,-1,-10]) + 2 + >>> find_negative_index([0,0,0,-1]) + 3 + >>> find_negative_index([11,8,7,-3,-5,-9]) + 3 + >>> find_negative_index([-1,-1,-2,-3]) + 0 + >>> find_negative_index([5,1,0]) + 3 + >>> find_negative_index([-5,-5,-5]) + 0 + >>> find_negative_index([0]) + 1 + >>> find_negative_index([]) + 0 + """ left = 0 right = len(array) - 1 @@ -44,6 +83,13 @@ def count_negatives_binary_search(grid: list[list[int]]) -> int: + """ + An O(m logn) solution that uses binary search in order to find the boundary between + positive and negative numbers + + >>> [count_negatives_binary_search(grid) for grid in test_grids] + [8, 0, 0, 3, 1498500] + """ total = 0 bound = len(grid[0]) @@ -54,10 +100,23 @@ def count_negatives_brute_force(grid: list[list[int]]) -> int: + """ + This solution is O(n^2) because it iterates through every column and row. + + >>> [count_negatives_brute_force(grid) for grid in test_grids] + [8, 0, 0, 3, 1498500] + """ return len([number for row in grid for number in row if number < 0]) def count_negatives_brute_force_with_break(grid: list[list[int]]) -> int: + """ + Similar to the brute force solution above but uses break in order to reduce the + number of iterations. + + >>> [count_negatives_brute_force_with_break(grid) for grid in test_grids] + [8, 0, 0, 3, 1498500] + """ total = 0 for row in grid: for i, number in enumerate(row): @@ -68,6 +127,7 @@ def benchmark() -> None: + """Benchmark our functions next to each other""" from timeit import timeit print("Running benchmarks") @@ -88,4 +148,4 @@ import doctest doctest.testmod() - benchmark()+ benchmark()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/count_negative_numbers_in_sorted_matrix.py
Generate docstrings with parameter types
from __future__ import annotations from math import pi, pow # noqa: A004 def vol_cube(side_length: float) -> float: if side_length < 0: raise ValueError("vol_cube() only accepts non-negative values") return pow(side_length, 3) def vol_spherical_cap(height: float, radius: float) -> float: if height < 0 or radius < 0: raise ValueError("vol_spherical_cap() only accepts non-negative values") # Volume is 1/3 pi * height squared * (3 * radius - height) return 1 / 3 * pi * pow(height, 2) * (3 * radius - height) def vol_spheres_intersect( radius_1: float, radius_2: float, centers_distance: float ) -> float: if radius_1 < 0 or radius_2 < 0 or centers_distance < 0: raise ValueError("vol_spheres_intersect() only accepts non-negative values") if centers_distance == 0: return vol_sphere(min(radius_1, radius_2)) h1 = ( (radius_1 - radius_2 + centers_distance) * (radius_1 + radius_2 - centers_distance) / (2 * centers_distance) ) h2 = ( (radius_2 - radius_1 + centers_distance) * (radius_2 + radius_1 - centers_distance) / (2 * centers_distance) ) return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1) def vol_spheres_union( radius_1: float, radius_2: float, centers_distance: float ) -> float: if radius_1 <= 0 or radius_2 <= 0 or centers_distance < 0: raise ValueError( "vol_spheres_union() only accepts non-negative values, non-zero radius" ) if centers_distance == 0: return vol_sphere(max(radius_1, radius_2)) return ( vol_sphere(radius_1) + vol_sphere(radius_2) - vol_spheres_intersect(radius_1, radius_2, centers_distance) ) def vol_cuboid(width: float, height: float, length: float) -> float: if width < 0 or height < 0 or length < 0: raise ValueError("vol_cuboid() only accepts non-negative values") return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: if height < 0 or area_of_base < 0: raise ValueError("vol_cone() only accepts non-negative values") return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: if height < 0 or radius < 0: raise ValueError("vol_right_circ_cone() only accepts non-negative values") return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: if height < 0 or area_of_base < 0: raise ValueError("vol_prism() only accepts non-negative values") return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: if height < 0 or area_of_base < 0: raise ValueError("vol_pyramid() only accepts non-negative values") return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: if radius < 0: raise ValueError("vol_sphere() only accepts non-negative values") # Volume is 4/3 * pi * radius cubed return 4 / 3 * pi * pow(radius, 3) def vol_hemisphere(radius: float) -> float: if radius < 0: raise ValueError("vol_hemisphere() only accepts non-negative values") # Volume is radius cubed * pi * 2/3 return pow(radius, 3) * pi * 2 / 3 def vol_circular_cylinder(radius: float, height: float) -> float: if height < 0 or radius < 0: raise ValueError("vol_circular_cylinder() only accepts non-negative values") # Volume is radius squared * height * pi return pow(radius, 2) * height * pi 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 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) ) def vol_torus(torus_radius: float, tube_radius: float) -> float: if torus_radius < 0 or tube_radius < 0: raise ValueError("vol_torus() only accepts non-negative values") return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2) def vol_icosahedron(tri_side: float) -> float: if tri_side < 0: raise ValueError("vol_icosahedron() only accepts non-negative values") return tri_side**3 * (3 + 5**0.5) * 5 / 12 def main(): print("Volumes:") print(f"Cube: {vol_cube(2) = }") # = 8 print(f"Cuboid: {vol_cuboid(2, 2, 2) = }") # = 8 print(f"Cone: {vol_cone(2, 2) = }") # ~= 1.33 print(f"Right Circular Cone: {vol_right_circ_cone(2, 2) = }") # ~= 8.38 print(f"Prism: {vol_prism(2, 2) = }") # = 4 print(f"Pyramid: {vol_pyramid(2, 2) = }") # ~= 1.33 print(f"Sphere: {vol_sphere(2) = }") # ~= 33.5 print(f"Hemisphere: {vol_hemisphere(2) = }") # ~= 16.75 print(f"Circular Cylinder: {vol_circular_cylinder(2, 2) = }") # ~= 25.1 print(f"Torus: {vol_torus(2, 2) = }") # ~= 157.9 print(f"Conical Frustum: {vol_conical_frustum(2, 2, 4) = }") # ~= 58.6 print(f"Spherical cap: {vol_spherical_cap(1, 2) = }") # ~= 5.24 print(f"Spheres intersection: {vol_spheres_intersect(2, 2, 1) = }") # ~= 21.21 print(f"Spheres union: {vol_spheres_union(2, 2, 1) = }") # ~= 45.81 print( f"Hollow Circular Cylinder: {vol_hollow_circular_cylinder(1, 2, 3) = }" ) # ~= 28.3 print(f"Icosahedron: {vol_icosahedron(2.5) = }") # ~=34.09 if __name__ == "__main__": main()
--- +++ @@ -1,3 +1,9 @@+""" +Find the volume of various shapes. + +* https://en.wikipedia.org/wiki/Volume +* https://en.wikipedia.org/wiki/Spherical_cap +""" from __future__ import annotations @@ -5,12 +11,46 @@ def vol_cube(side_length: float) -> float: + """ + Calculate the Volume of a Cube. + + >>> vol_cube(1) + 1.0 + >>> vol_cube(3) + 27.0 + >>> vol_cube(0) + 0.0 + >>> vol_cube(1.6) + 4.096000000000001 + >>> vol_cube(-1) + Traceback (most recent call last): + ... + ValueError: vol_cube() only accepts non-negative values + """ if side_length < 0: raise ValueError("vol_cube() only accepts non-negative values") return pow(side_length, 3) def vol_spherical_cap(height: float, radius: float) -> float: + """ + Calculate the volume of the spherical cap. + + >>> vol_spherical_cap(1, 2) + 5.235987755982988 + >>> vol_spherical_cap(1.6, 2.6) + 16.621119532592402 + >>> vol_spherical_cap(0, 0) + 0.0 + >>> vol_spherical_cap(-1, 2) + Traceback (most recent call last): + ... + ValueError: vol_spherical_cap() only accepts non-negative values + >>> vol_spherical_cap(1, -2) + Traceback (most recent call last): + ... + ValueError: vol_spherical_cap() only accepts non-negative values + """ 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) @@ -20,6 +60,48 @@ def vol_spheres_intersect( radius_1: float, radius_2: float, centers_distance: float ) -> float: + r""" + Calculate the volume of the intersection of two spheres. + + The intersection is composed by two spherical caps and therefore its volume is the + sum of the volumes of the spherical caps. + First, it calculates the heights :math:`(h_1, h_2)` of the spherical caps, + then the two volumes and it returns the sum. + The height formulas are + + .. math:: + h_1 = \frac{(radius_1 - radius_2 + centers\_distance) + \cdot (radius_1 + radius_2 - centers\_distance)} + {2 \cdot centers\_distance} + + h_2 = \frac{(radius_2 - radius_1 + centers\_distance) + \cdot (radius_2 + radius_1 - centers\_distance)} + {2 \cdot centers\_distance} + + if `centers_distance` is 0 then it returns the volume of the smallers sphere + + :return: ``vol_spherical_cap`` (:math:`h_1`, :math:`radius_2`) + + ``vol_spherical_cap`` (:math:`h_2`, :math:`radius_1`) + + >>> vol_spheres_intersect(2, 2, 1) + 21.205750411731103 + >>> vol_spheres_intersect(2.6, 2.6, 1.6) + 40.71504079052372 + >>> vol_spheres_intersect(0, 0, 0) + 0.0 + >>> vol_spheres_intersect(-2, 2, 1) + Traceback (most recent call last): + ... + ValueError: vol_spheres_intersect() only accepts non-negative values + >>> vol_spheres_intersect(2, -2, 1) + Traceback (most recent call last): + ... + ValueError: vol_spheres_intersect() only accepts non-negative values + >>> vol_spheres_intersect(2, 2, -1) + Traceback (most recent call last): + ... + ValueError: vol_spheres_intersect() only accepts non-negative values + """ 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: @@ -42,6 +124,36 @@ def vol_spheres_union( radius_1: float, radius_2: float, centers_distance: float ) -> float: + r""" + Calculate the volume of the union of two spheres that possibly intersect. + + It is the sum of sphere :math:`A` and sphere :math:`B` minus their intersection. + First, it calculates the volumes :math:`(v_1, v_2)` of the spheres, + then the volume of the intersection :math:`i` and + it returns the sum :math:`v_1 + v_2 - i`. + If `centers_distance` is 0 then it returns the volume of the larger sphere + + :return: ``vol_sphere`` (:math:`radius_1`) + ``vol_sphere`` (:math:`radius_2`) + - ``vol_spheres_intersect`` + (:math:`radius_1`, :math:`radius_2`, :math:`centers\_distance`) + + >>> vol_spheres_union(2, 2, 1) + 45.814892864851146 + >>> vol_spheres_union(1.56, 2.2, 1.4) + 48.77802773671288 + >>> vol_spheres_union(0, 2, 1) + Traceback (most recent call last): + ... + ValueError: vol_spheres_union() only accepts non-negative values, non-zero radius + >>> vol_spheres_union('1.56', '2.2', '1.4') + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'str' and 'int' + >>> vol_spheres_union(1, None, 1) + Traceback (most recent call last): + ... + TypeError: '<=' not supported between instances of 'NoneType' and 'int' + """ if radius_1 <= 0 or radius_2 <= 0 or centers_distance < 0: raise ValueError( @@ -59,36 +171,171 @@ def vol_cuboid(width: float, height: float, length: float) -> float: + """ + Calculate the Volume of a Cuboid. + + :return: multiple of `width`, `length` and `height` + + >>> vol_cuboid(1, 1, 1) + 1.0 + >>> vol_cuboid(1, 2, 3) + 6.0 + >>> vol_cuboid(1.6, 2.6, 3.6) + 14.976 + >>> vol_cuboid(0, 0, 0) + 0.0 + >>> vol_cuboid(-1, 2, 3) + Traceback (most recent call last): + ... + ValueError: vol_cuboid() only accepts non-negative values + >>> vol_cuboid(1, -2, 3) + Traceback (most recent call last): + ... + ValueError: vol_cuboid() only accepts non-negative values + >>> vol_cuboid(1, 2, -3) + Traceback (most recent call last): + ... + ValueError: vol_cuboid() only accepts non-negative values + """ if width < 0 or height < 0 or length < 0: raise ValueError("vol_cuboid() only accepts non-negative values") return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: + r""" + | Calculate the Volume of a Cone. + | Wikipedia reference: https://en.wikipedia.org/wiki/Cone + + :return: :math:`\frac{1}{3} \cdot area\_of\_base \cdot height` + + >>> vol_cone(10, 3) + 10.0 + >>> vol_cone(1, 1) + 0.3333333333333333 + >>> vol_cone(1.6, 1.6) + 0.8533333333333335 + >>> vol_cone(0, 0) + 0.0 + >>> vol_cone(-1, 1) + Traceback (most recent call last): + ... + ValueError: vol_cone() only accepts non-negative values + >>> vol_cone(1, -1) + Traceback (most recent call last): + ... + ValueError: vol_cone() only accepts non-negative values + """ if height < 0 or area_of_base < 0: raise ValueError("vol_cone() only accepts non-negative values") return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: + r""" + | Calculate the Volume of a Right Circular Cone. + | Wikipedia reference: https://en.wikipedia.org/wiki/Cone + + :return: :math:`\frac{1}{3} \cdot \pi \cdot radius^2 \cdot height` + + >>> vol_right_circ_cone(2, 3) + 12.566370614359172 + >>> vol_right_circ_cone(0, 0) + 0.0 + >>> vol_right_circ_cone(1.6, 1.6) + 4.289321169701265 + >>> vol_right_circ_cone(-1, 1) + Traceback (most recent call last): + ... + ValueError: vol_right_circ_cone() only accepts non-negative values + >>> vol_right_circ_cone(1, -1) + Traceback (most recent call last): + ... + ValueError: vol_right_circ_cone() only accepts non-negative values + """ if height < 0 or radius < 0: raise ValueError("vol_right_circ_cone() only accepts non-negative values") return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: + r""" + | Calculate the Volume of a Prism. + | Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) + + :return: :math:`V = B \cdot h` + + >>> vol_prism(10, 2) + 20.0 + >>> vol_prism(11, 1) + 11.0 + >>> vol_prism(1.6, 1.6) + 2.5600000000000005 + >>> vol_prism(0, 0) + 0.0 + >>> vol_prism(-1, 1) + Traceback (most recent call last): + ... + ValueError: vol_prism() only accepts non-negative values + >>> vol_prism(1, -1) + Traceback (most recent call last): + ... + ValueError: vol_prism() only accepts non-negative values + """ if height < 0 or area_of_base < 0: raise ValueError("vol_prism() only accepts non-negative values") return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: + r""" + | Calculate the Volume of a Pyramid. + | Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) + + :return: :math:`\frac{1}{3} \cdot B \cdot h` + + >>> vol_pyramid(10, 3) + 10.0 + >>> vol_pyramid(1.5, 3) + 1.5 + >>> vol_pyramid(1.6, 1.6) + 0.8533333333333335 + >>> vol_pyramid(0, 0) + 0.0 + >>> vol_pyramid(-1, 1) + Traceback (most recent call last): + ... + ValueError: vol_pyramid() only accepts non-negative values + >>> vol_pyramid(1, -1) + Traceback (most recent call last): + ... + ValueError: vol_pyramid() only accepts non-negative values + """ if height < 0 or area_of_base < 0: raise ValueError("vol_pyramid() only accepts non-negative values") return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: + r""" + | Calculate the Volume of a Sphere. + | Wikipedia reference: https://en.wikipedia.org/wiki/Sphere + + :return: :math:`\frac{4}{3} \cdot \pi \cdot r^3` + + >>> vol_sphere(5) + 523.5987755982989 + >>> vol_sphere(1) + 4.1887902047863905 + >>> vol_sphere(1.6) + 17.15728467880506 + >>> vol_sphere(0) + 0.0 + >>> vol_sphere(-1) + Traceback (most recent call last): + ... + ValueError: vol_sphere() only accepts non-negative values + """ if radius < 0: raise ValueError("vol_sphere() only accepts non-negative values") # Volume is 4/3 * pi * radius cubed @@ -96,6 +343,26 @@ def vol_hemisphere(radius: float) -> float: + r""" + | Calculate the volume of a hemisphere + | Wikipedia reference: https://en.wikipedia.org/wiki/Hemisphere + | Other references: https://www.cuemath.com/geometry/hemisphere + + :return: :math:`\frac{2}{3} \cdot \pi \cdot radius^3` + + >>> vol_hemisphere(1) + 2.0943951023931953 + >>> vol_hemisphere(7) + 718.377520120866 + >>> vol_hemisphere(1.6) + 8.57864233940253 + >>> vol_hemisphere(0) + 0.0 + >>> vol_hemisphere(-1) + Traceback (most recent call last): + ... + ValueError: vol_hemisphere() only accepts non-negative values + """ if radius < 0: raise ValueError("vol_hemisphere() only accepts non-negative values") # Volume is radius cubed * pi * 2/3 @@ -103,6 +370,29 @@ def vol_circular_cylinder(radius: float, height: float) -> float: + r""" + | Calculate the Volume of a Circular Cylinder. + | Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder + + :return: :math:`\pi \cdot radius^2 \cdot height` + + >>> vol_circular_cylinder(1, 1) + 3.141592653589793 + >>> vol_circular_cylinder(4, 3) + 150.79644737231007 + >>> vol_circular_cylinder(1.6, 1.6) + 12.867963509103795 + >>> vol_circular_cylinder(0, 0) + 0.0 + >>> vol_circular_cylinder(-1, 1) + Traceback (most recent call last): + ... + ValueError: vol_circular_cylinder() only accepts non-negative values + >>> vol_circular_cylinder(1, -1) + Traceback (most recent call last): + ... + ValueError: vol_circular_cylinder() only accepts non-negative values + """ if height < 0 or radius < 0: raise ValueError("vol_circular_cylinder() only accepts non-negative values") # Volume is radius squared * height * pi @@ -112,6 +402,34 @@ def vol_hollow_circular_cylinder( inner_radius: float, outer_radius: float, height: float ) -> float: + """ + Calculate the Volume of a Hollow Circular Cylinder. + + >>> vol_hollow_circular_cylinder(1, 2, 3) + 28.274333882308138 + >>> vol_hollow_circular_cylinder(1.6, 2.6, 3.6) + 47.50088092227767 + >>> vol_hollow_circular_cylinder(-1, 2, 3) + Traceback (most recent call last): + ... + ValueError: vol_hollow_circular_cylinder() only accepts non-negative values + >>> vol_hollow_circular_cylinder(1, -2, 3) + Traceback (most recent call last): + ... + ValueError: vol_hollow_circular_cylinder() only accepts non-negative values + >>> vol_hollow_circular_cylinder(1, 2, -3) + Traceback (most recent call last): + ... + ValueError: vol_hollow_circular_cylinder() only accepts non-negative values + >>> vol_hollow_circular_cylinder(2, 1, 3) + Traceback (most recent call last): + ... + ValueError: outer_radius must be greater than inner_radius + >>> vol_hollow_circular_cylinder(0, 0, 0) + Traceback (most recent call last): + ... + ValueError: outer_radius must be greater than inner_radius + """ # Volume - (outer_radius squared - inner_radius squared) * pi * height if inner_radius < 0 or outer_radius < 0 or height < 0: raise ValueError( @@ -123,6 +441,31 @@ def vol_conical_frustum(height: float, radius_1: float, radius_2: float) -> float: + """ + | Calculate the Volume of a Conical Frustum. + | Wikipedia reference: https://en.wikipedia.org/wiki/Frustum + + >>> vol_conical_frustum(45, 7, 28) + 48490.482608158454 + >>> vol_conical_frustum(1, 1, 2) + 7.330382858376184 + >>> vol_conical_frustum(1.6, 2.6, 3.6) + 48.7240076620753 + >>> vol_conical_frustum(0, 0, 0) + 0.0 + >>> vol_conical_frustum(-2, 2, 1) + Traceback (most recent call last): + ... + ValueError: vol_conical_frustum() only accepts non-negative values + >>> vol_conical_frustum(2, -2, 1) + Traceback (most recent call last): + ... + ValueError: vol_conical_frustum() only accepts non-negative values + >>> vol_conical_frustum(2, 2, -1) + Traceback (most recent call last): + ... + ValueError: vol_conical_frustum() only accepts non-negative values + """ # Volume is 1/3 * pi * height * # (radius_1 squared + radius_2 squared + radius_1 * radius_2) if radius_1 < 0 or radius_2 < 0 or height < 0: @@ -137,18 +480,68 @@ def vol_torus(torus_radius: float, tube_radius: float) -> float: + r""" + | Calculate the Volume of a Torus. + | Wikipedia reference: https://en.wikipedia.org/wiki/Torus + + :return: :math:`2 \pi^2 \cdot torus\_radius \cdot tube\_radius^2` + + >>> vol_torus(1, 1) + 19.739208802178716 + >>> vol_torus(4, 3) + 710.6115168784338 + >>> vol_torus(3, 4) + 947.4820225045784 + >>> vol_torus(1.6, 1.6) + 80.85179925372404 + >>> vol_torus(0, 0) + 0.0 + >>> vol_torus(-1, 1) + Traceback (most recent call last): + ... + ValueError: vol_torus() only accepts non-negative values + >>> vol_torus(1, -1) + Traceback (most recent call last): + ... + ValueError: vol_torus() only accepts non-negative values + """ if torus_radius < 0 or tube_radius < 0: raise ValueError("vol_torus() only accepts non-negative values") return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2) def vol_icosahedron(tri_side: float) -> float: + """ + | Calculate the Volume of an Icosahedron. + | Wikipedia reference: https://en.wikipedia.org/wiki/Regular_icosahedron + + >>> from math import isclose + >>> isclose(vol_icosahedron(2.5), 34.088984228514256) + True + >>> isclose(vol_icosahedron(10), 2181.694990624912374) + True + >>> isclose(vol_icosahedron(5), 272.711873828114047) + True + >>> isclose(vol_icosahedron(3.49), 92.740688412033628) + True + >>> vol_icosahedron(0) + 0.0 + >>> vol_icosahedron(-1) + Traceback (most recent call last): + ... + ValueError: vol_icosahedron() only accepts non-negative values + >>> vol_icosahedron(-0.2) + Traceback (most recent call last): + ... + ValueError: vol_icosahedron() only accepts non-negative values + """ if tri_side < 0: raise ValueError("vol_icosahedron() only accepts non-negative values") return tri_side**3 * (3 + 5**0.5) * 5 / 12 def main(): + """Print the Results of Various Volume Calculations.""" print("Volumes:") print(f"Cube: {vol_cube(2) = }") # = 8 print(f"Cuboid: {vol_cuboid(2, 2, 2) = }") # = 8 @@ -171,4 +564,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/volume.py
Can you add docstrings to this Python file?
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_check import is_prime def twin_prime(number: int) -> int: if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if is_prime(number) and is_prime(number + 2): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,9 +1,36 @@+""" +== Twin Prime == +A number n+2 is said to be a Twin prime of number n if +both n and n+2 are prime. + +Examples of Twin pairs: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), ... +https://en.wikipedia.org/wiki/Twin_prime +""" # Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_check import is_prime def twin_prime(number: int) -> int: + """ + # doctest: +NORMALIZE_WHITESPACE + This functions takes an integer number as input. + returns n+2 if n and n+2 are prime numbers and -1 otherwise. + >>> twin_prime(3) + 5 + >>> twin_prime(4) + -1 + >>> twin_prime(5) + 7 + >>> twin_prime(17) + 19 + >>> twin_prime(0) + -1 + >>> twin_prime(6.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=6.0] must be an integer + """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) @@ -16,4 +43,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/twin_prime.py
Create structured documentation for my script
from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: chk_map: dict[int, int] = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: return [chk_map[compl], index] chk_map[val] = index return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_sum([2, 7, 11, 15], 9) = }")
--- +++ @@ -1,8 +1,37 @@+""" +Given an array of integers, return indices of the two numbers such that they add up to +a specific target. + +You may assume that each input would have exactly one solution, and you may not use the +same element twice. + +Example: +Given nums = [2, 7, 11, 15], target = 9, + +Because nums[0] + nums[1] = 2 + 7 = 9, +return [0, 1]. +""" from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: + """ + >>> two_sum([2, 7, 11, 15], 9) + [0, 1] + >>> two_sum([15, 2, 11, 7], 13) + [1, 2] + >>> two_sum([2, 7, 11, 15], 17) + [0, 3] + >>> two_sum([7, 15, 11, 2], 18) + [0, 2] + >>> two_sum([2, 7, 11, 15], 26) + [2, 3] + >>> two_sum([2, 7, 11, 15], 8) + [] + >>> two_sum([3 * i for i in range(10)], 19) + [] + """ chk_map: dict[int, int] = {} for index, val in enumerate(nums): compl = target - val @@ -16,4 +45,4 @@ import doctest doctest.testmod() - print(f"{two_sum([2, 7, 11, 15], 9) = }")+ print(f"{two_sum([2, 7, 11, 15], 9) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/two_sum.py
Add docstrings that explain logic
def binary_search(array: list, lower_bound: int, upper_bound: int, value: int) -> int: r = int((lower_bound + upper_bound) // 2) if array[r] == value: return r if lower_bound >= upper_bound: return -1 if array[r] < value: return binary_search(array, r + 1, upper_bound, value) else: return binary_search(array, lower_bound, r - 1, value) def mat_bin_search(value: int, matrix: list) -> list: index = 0 if matrix[index][0] == value: return [index, 0] while index < len(matrix) and matrix[index][0] < value: r = binary_search(matrix[index], 0, len(matrix[index]) - 1, value) if r != -1: return [index, r] index += 1 return [-1, -1] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,4 +1,15 @@ def binary_search(array: list, lower_bound: int, upper_bound: int, value: int) -> int: + """ + This function carries out Binary search on a 1d array and + return -1 if it do not exist + array: A 1d sorted array + value : the value meant to be searched + >>> matrix = [1, 4, 7, 11, 15] + >>> binary_search(matrix, 0, len(matrix) - 1, 1) + 0 + >>> binary_search(matrix, 0, len(matrix) - 1, 23) + -1 + """ r = int((lower_bound + upper_bound) // 2) if array[r] == value: @@ -12,6 +23,23 @@ def mat_bin_search(value: int, matrix: list) -> list: + """ + This function loops over a 2d matrix and calls binarySearch on + the selected 1d array and returns [-1, -1] is it do not exist + value : value meant to be searched + matrix = a sorted 2d matrix + >>> matrix = [[1, 4, 7, 11, 15], + ... [2, 5, 8, 12, 19], + ... [3, 6, 9, 16, 22], + ... [10, 13, 14, 17, 24], + ... [18, 21, 23, 26, 30]] + >>> target = 1 + >>> mat_bin_search(target, matrix) + [0, 0] + >>> target = 34 + >>> mat_bin_search(target, matrix) + [-1, -1] + """ index = 0 if matrix[index][0] == value: return [index, 0] @@ -26,4 +54,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/binary_search_matrix.py
Generate docstrings for each module
def depth_first_search(grid: list[list[int]], row: int, col: int, visit: set) -> int: row_length, col_length = len(grid), len(grid[0]) if ( min(row, col) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col)) count = 0 count += depth_first_search(grid, row + 1, col, visit) count += depth_first_search(grid, row - 1, col, visit) count += depth_first_search(grid, row, col + 1, visit) count += depth_first_search(grid, row, col - 1, visit) visit.remove((row, col)) return count if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,50 @@+""" +Given a grid, where you start from the top left position [0, 0], +you want to find how many paths you can take to get to the bottom right position. + +start here -> 0 0 0 0 + 1 1 0 0 + 0 0 0 1 + 0 1 0 0 <- finish here +how many 'distinct' paths can you take to get to the finish? +Using a recursive depth-first search algorithm below, you are able to +find the number of distinct unique paths (count). + +'*' will demonstrate a path +In the example above, there are two distinct paths: +1. 2. + * * * 0 * * * * + 1 1 * 0 1 1 * * + 0 0 * 1 0 0 * 1 + 0 1 * * 0 1 * * +""" def depth_first_search(grid: list[list[int]], row: int, col: int, visit: set) -> int: + """ + Recursive Backtracking Depth First Search Algorithm + + Starting from top left of a matrix, count the number of + paths that can reach the bottom right of a matrix. + 1 represents a block (inaccessible) + 0 represents a valid space (accessible) + + 0 0 0 0 + 1 1 0 0 + 0 0 0 1 + 0 1 0 0 + >>> grid = [[0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]] + >>> depth_first_search(grid, 0, 0, set()) + 2 + + 0 0 0 0 0 + 0 1 1 1 0 + 0 1 1 1 0 + 0 0 0 0 0 + >>> grid = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] + >>> depth_first_search(grid, 0, 0, set()) + 2 + """ row_length, col_length = len(grid), len(grid[0]) if ( min(row, col) < 0 @@ -28,4 +72,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/count_paths.py
Insert docstrings into my code
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def make_dataset() -> tuple[list[int], int]: arr = [randint(-1000, 1000) for i in range(10)] r = randint(-5000, 5000) return (arr, r) dataset = make_dataset() def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]: for triplet in permutations(arr, 3): if sum(triplet) == target: return tuple(sorted(triplet)) return (0, 0, 0) def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]: arr.sort() n = len(arr) for i in range(n - 1): left, right = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def solution_times() -> tuple[float, float]: setup_code = """ from __main__ import dataset, triplet_sum1, triplet_sum2 """ test_code1 = """ triplet_sum1(*dataset) """ test_code2 = """ triplet_sum2(*dataset) """ times1 = repeat(setup=setup_code, stmt=test_code1, repeat=5, number=10000) times2 = repeat(setup=setup_code, stmt=test_code2, repeat=5, number=10000) return (min(times1), min(times2)) if __name__ == "__main__": from doctest import testmod testmod() times = solution_times() print(f"The time for naive implementation is {times[0]}.") print(f"The time for optimized implementation is {times[1]}.")
--- +++ @@ -1,3 +1,8 @@+""" +Given an array of integers and another integer target, +we are required to find a triplet from the array such that it's sum is equal to +the target. +""" from __future__ import annotations @@ -16,6 +21,18 @@ def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]: + """ + Returns a triplet in the array with sum equal to target, + else (0, 0, 0). + >>> triplet_sum1([13, 29, 7, 23, 5], 35) + (5, 7, 23) + >>> triplet_sum1([37, 9, 19, 50, 44], 65) + (9, 19, 37) + >>> arr = [6, 47, 27, 1, 15] + >>> target = 11 + >>> triplet_sum1(arr, target) + (0, 0, 0) + """ for triplet in permutations(arr, 3): if sum(triplet) == target: return tuple(sorted(triplet)) @@ -23,6 +40,18 @@ def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]: + """ + Returns a triplet in the array with sum equal to target, + else (0, 0, 0). + >>> triplet_sum2([13, 29, 7, 23, 5], 35) + (5, 7, 23) + >>> triplet_sum2([37, 9, 19, 50, 44], 65) + (9, 19, 37) + >>> arr = [6, 47, 27, 1, 15] + >>> target = 11 + >>> triplet_sum2(arr, target) + (0, 0, 0) + """ arr.sort() n = len(arr) for i in range(n - 1): @@ -58,4 +87,4 @@ testmod() times = solution_times() print(f"The time for naive implementation is {times[0]}.") - print(f"The time for optimized implementation is {times[1]}.")+ print(f"The time for optimized implementation is {times[1]}.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/triplet_sum.py
Add return value explanations in docstrings
def largest_square_area_in_matrix_top_down_approch( rows: int, cols: int, mat: list[list[int]] ) -> int: def update_area_of_max_square(row: int, col: int) -> int: # BASE CASE if row >= rows or col >= cols: return 0 right = update_area_of_max_square(row, col + 1) diagonal = update_area_of_max_square(row + 1, col + 1) down = update_area_of_max_square(row + 1, col) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) return sub_problem_sol else: return 0 largest_square_area = [0] update_area_of_max_square(0, 0) return largest_square_area[0] def largest_square_area_in_matrix_top_down_approch_with_dp( rows: int, cols: int, mat: list[list[int]] ) -> int: def update_area_of_max_square_using_dp_array( row: int, col: int, dp_array: list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] right = update_area_of_max_square_using_dp_array(row, col + 1, dp_array) diagonal = update_area_of_max_square_using_dp_array(row + 1, col + 1, dp_array) down = update_area_of_max_square_using_dp_array(row + 1, col, dp_array) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) dp_array[row][col] = sub_problem_sol return sub_problem_sol else: return 0 largest_square_area = [0] dp_array = [[-1] * cols for _ in range(rows)] update_area_of_max_square_using_dp_array(0, 0, dp_array) return largest_square_area[0] def largest_square_area_in_matrix_bottom_up( rows: int, cols: int, mat: list[list[int]] ) -> int: dp_array = [[0] * (cols + 1) for _ in range(rows + 1)] largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = dp_array[row][col + 1] diagonal = dp_array[row + 1][col + 1] bottom = dp_array[row + 1][col] if mat[row][col] == 1: dp_array[row][col] = 1 + min(right, diagonal, bottom) largest_square_area = max(dp_array[row][col], largest_square_area) else: dp_array[row][col] = 0 return largest_square_area def largest_square_area_in_matrix_bottom_up_space_optimization( rows: int, cols: int, mat: list[list[int]] ) -> int: current_row = [0] * (cols + 1) next_row = [0] * (cols + 1) largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = current_row[col + 1] diagonal = next_row[col + 1] bottom = next_row[col] if mat[row][col] == 1: current_row[col] = 1 + min(right, diagonal, bottom) largest_square_area = max(current_row[col], largest_square_area) else: current_row[col] = 0 next_row = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
--- +++ @@ -1,8 +1,62 @@+""" +Question: +Given a binary matrix mat of size n * m, find out the maximum size square +sub-matrix with all 1s. + +--- +Example 1: + +Input: +n = 2, m = 2 +mat = [[1, 1], + [1, 1]] + +Output: +2 + +Explanation: The maximum size of the square +sub-matrix is 2. The matrix itself is the +maximum sized sub-matrix in this case. +--- +Example 2 + +Input: +n = 2, m = 2 +mat = [[0, 0], + [0, 0]] +Output: 0 + +Explanation: There is no 1 in the matrix. + + +Approach: +We initialize another matrix (dp) with the same dimensions +as the original one initialized with all 0's. + +dp_array(i,j) represents the side length of the maximum square whose +bottom right corner is the cell with index (i,j) in the original matrix. + +Starting from index (0,0), for every 1 found in the original matrix, +we update the value of the current element as + +dp_array(i,j)=dp_array(dp(i-1,j),dp_array(i-1,j-1),dp_array(i,j-1)) + 1. +""" def largest_square_area_in_matrix_top_down_approch( rows: int, cols: int, mat: list[list[int]] ) -> int: + """ + Function updates the largest_square_area[0], if recursive call found + square with maximum area. + + We aren't using dp_array here, so the time complexity would be exponential. + + >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[1,1], [1,1]]) + 2 + >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[0,0], [0,0]]) + 0 + """ def update_area_of_max_square(row: int, col: int) -> int: # BASE CASE @@ -28,6 +82,17 @@ def largest_square_area_in_matrix_top_down_approch_with_dp( rows: int, cols: int, mat: list[list[int]] ) -> int: + """ + Function updates the largest_square_area[0], if recursive call found + square with maximum area. + + We are using dp_array here, so the time complexity would be O(N^2). + + >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[1,1], [1,1]]) + 2 + >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[0,0], [0,0]]) + 0 + """ def update_area_of_max_square_using_dp_array( row: int, col: int, dp_array: list[list[int]] @@ -59,6 +124,15 @@ def largest_square_area_in_matrix_bottom_up( rows: int, cols: int, mat: list[list[int]] ) -> int: + """ + Function updates the largest_square_area, using bottom up approach. + + >>> largest_square_area_in_matrix_bottom_up(2, 2, [[1,1], [1,1]]) + 2 + >>> largest_square_area_in_matrix_bottom_up(2, 2, [[0,0], [0,0]]) + 0 + + """ dp_array = [[0] * (cols + 1) for _ in range(rows + 1)] largest_square_area = 0 for row in range(rows - 1, -1, -1): @@ -79,6 +153,15 @@ def largest_square_area_in_matrix_bottom_up_space_optimization( rows: int, cols: int, mat: list[list[int]] ) -> int: + """ + Function updates the largest_square_area, using bottom up + approach. with space optimization. + + >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[1,1], [1,1]]) + 2 + >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[0,0], [0,0]]) + 0 + """ current_row = [0] * (cols + 1) next_row = [0] * (cols + 1) largest_square_area = 0 @@ -102,4 +185,4 @@ import doctest doctest.testmod() - print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))+ print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/largest_square_area_in_matrix.py
Add docstrings to improve collaboration
matrix = [ [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], ] def is_safe(row: int, col: int, rows: int, cols: int) -> bool: return 0 <= row < rows and 0 <= col < cols def depth_first_search(row: int, col: int, seen: set, mat: list[list[int]]) -> int: rows = len(mat) cols = len(mat[0]) if is_safe(row, col, rows, cols) and (row, col) not in seen and mat[row][col] == 1: seen.add((row, col)) return ( 1 + depth_first_search(row + 1, col, seen, mat) + depth_first_search(row - 1, col, seen, mat) + depth_first_search(row, col + 1, seen, mat) + depth_first_search(row, col - 1, seen, mat) ) else: return 0 def find_max_area(mat: list[list[int]]) -> int: seen: set = set() max_area = 0 for row, line in enumerate(mat): for col, item in enumerate(line): if item == 1 and (row, col) not in seen: # Maximizing the area max_area = max(max_area, depth_first_search(row, col, seen, mat)) return max_area if __name__ == "__main__": import doctest print(find_max_area(matrix)) # Output -> 6 """ Explanation: We are allowed to move in four directions (horizontal or vertical) so the possible in a matrix if we are at x and y position the possible moving are Directions are [(x, y+1), (x, y-1), (x+1, y), (x-1, y)] but we need to take care of boundary cases as well which are x and y can not be smaller than 0 and greater than the number of rows and columns respectively. Visualization mat = [ [0,0,A,0,0,0,0,B,0,0,0,0,0], [0,0,0,0,0,0,0,B,B,B,0,0,0], [0,C,C,0,D,0,0,0,0,0,0,0,0], [0,C,0,0,D,D,0,0,E,0,E,0,0], [0,C,0,0,D,D,0,0,E,E,E,0,0], [0,0,0,0,0,0,0,0,0,0,E,0,0], [0,0,0,0,0,0,0,F,F,F,0,0,0], [0,0,0,0,0,0,0,F,F,0,0,0,0] ] For visualization, I have defined the connected island with letters by observation, we can see that A island is of area 1 B island is of area 4 C island is of area 4 D island is of area 5 E island is of area 6 and F island is of area 5 it has 6 unique islands of mentioned areas and the maximum of all of them is 6 so we return 6. """ doctest.testmod()
--- +++ @@ -1,3 +1,10 @@+""" +Given an two dimensional binary matrix grid. An island is a group of 1's (representing +land) connected 4-directionally (horizontal or vertical.) You may assume all four edges +of the grid are surrounded by water. The area of an island is the number of cells with +a value 1 in the island. Return the maximum area of an island in a grid. If there is no +island, return 0. +""" matrix = [ [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], @@ -12,10 +19,24 @@ def is_safe(row: int, col: int, rows: int, cols: int) -> bool: + """ + Checking whether coordinate (row, col) is valid or not. + + >>> is_safe(0, 0, 5, 5) + True + >>> is_safe(-1,-1, 5, 5) + False + """ return 0 <= row < rows and 0 <= col < cols def depth_first_search(row: int, col: int, seen: set, mat: list[list[int]]) -> int: + """ + Returns the current area of the island + + >>> depth_first_search(0, 0, set(), matrix) + 0 + """ rows = len(mat) cols = len(mat[0]) if is_safe(row, col, rows, cols) and (row, col) not in seen and mat[row][col] == 1: @@ -32,6 +53,12 @@ def find_max_area(mat: list[list[int]]) -> int: + """ + Finds the area of all islands and returns the maximum area. + + >>> find_max_area(matrix) + 6 + """ seen: set = set() max_area = 0 @@ -82,4 +109,4 @@ and the maximum of all of them is 6 so we return 6. """ - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/max_area_of_island.py
Add docstrings to meet PEP guidelines
from __future__ import annotations from typing import Any def add(*matrix_s: list[list[int]]) -> list[list[int]]: if all(_check_not_integer(m) for m in matrix_s): for i in matrix_s[1:]: _verify_matrix_sizes(matrix_s[0], i) return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)] raise TypeError("Expected a matrix, got int/list instead") def subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: if ( _check_not_integer(matrix_a) and _check_not_integer(matrix_b) and _verify_matrix_sizes(matrix_a, matrix_b) ): return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)] raise TypeError("Expected a matrix, got int/list instead") def scalar_multiply(matrix: list[list[int]], n: float) -> list[list[float]]: return [[x * n for x in row] for row in matrix] def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) if cols[0] != rows[1]: msg = ( "Cannot multiply matrix of dimensions " f"({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})" ) raise ValueError(msg) return [ [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a ] def identity(n: int) -> list[list[int]]: n = int(n) return [[int(row == column) for column in range(n)] for row in range(n)] def transpose( matrix: list[list[int]], return_map: bool = True ) -> list[list[int]] | map[list[int]]: if _check_not_integer(matrix): if return_map: return map(list, zip(*matrix)) else: return list(map(list, zip(*matrix))) raise TypeError("Expected a matrix, got int/list instead") def minor(matrix: list[list[int]], row: int, column: int) -> list[list[int]]: minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor] def determinant(matrix: list[list[int]]) -> Any: if len(matrix) == 1: return matrix[0][0] return sum( x * determinant(minor(matrix, 0, i)) * (-1) ** i for i, x in enumerate(matrix[0]) ) def inverse(matrix: list[list[int]]) -> list[list[float]] | None: # https://stackoverflow.com/questions/20047519/python-doctests-test-for-none det = determinant(matrix) if det == 0: return None matrix_minor = [ [determinant(minor(matrix, i, j)) for j in range(len(matrix))] for i in range(len(matrix)) ] cofactors = [ [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] for row in range(len(matrix)) ] adjugate = list(transpose(cofactors)) return scalar_multiply(adjugate, 1 / det) def _check_not_integer(matrix: list[list[int]]) -> bool: return not isinstance(matrix, int) and not isinstance(matrix[0], int) def _shape(matrix: list[list[int]]) -> tuple[int, int]: return len(matrix), len(matrix[0]) def _verify_matrix_sizes( matrix_a: list[list[int]], matrix_b: list[list[int]] ) -> tuple[tuple[int, int], tuple[int, int]]: shape = _shape(matrix_a) + _shape(matrix_b) if shape[0] != shape[3] or shape[1] != shape[2]: msg = ( "operands could not be broadcast together with shape " f"({shape[0], shape[1]}), ({shape[2], shape[3]})" ) raise ValueError(msg) return (shape[0], shape[2]), (shape[1], shape[3]) def main() -> None: matrix_a = [[12, 10], [3, 9]] matrix_b = [[3, 4], [7, 4]] matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] print(f"Add Operation, {add(matrix_a, matrix_b) = } \n") print(f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n") print(f"Identity: {identity(5)}\n") print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n") print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n") print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -1,3 +1,6 @@+""" +Functions for 2D matrix operations +""" from __future__ import annotations @@ -5,6 +8,18 @@ def add(*matrix_s: list[list[int]]) -> list[list[int]]: + """ + >>> add([[1,2],[3,4]],[[2,3],[4,5]]) + [[3, 5], [7, 9]] + >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]]) + [[3.2, 5.4], [7, 9]] + >>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]]) + [[7, 14], [12, 16]] + >>> add([3], [4, 5]) + Traceback (most recent call last): + ... + TypeError: Expected a matrix, got int/list instead + """ if all(_check_not_integer(m) for m in matrix_s): for i in matrix_s[1:]: _verify_matrix_sizes(matrix_s[0], i) @@ -13,6 +28,16 @@ def subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: + """ + >>> subtract([[1,2],[3,4]],[[2,3],[4,5]]) + [[-1, -1], [-1, -1]] + >>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]]) + [[-1, -0.5], [-1, -1.5]] + >>> subtract([3], [4, 5]) + Traceback (most recent call last): + ... + TypeError: Expected a matrix, got int/list instead + """ if ( _check_not_integer(matrix_a) and _check_not_integer(matrix_b) @@ -23,10 +48,24 @@ def scalar_multiply(matrix: list[list[int]], n: float) -> list[list[float]]: + """ + >>> scalar_multiply([[1,2],[3,4]],5) + [[5, 10], [15, 20]] + >>> scalar_multiply([[1.4,2.3],[3,4]],5) + [[7.0, 11.5], [15, 20]] + """ return [[x * n for x in row] for row in matrix] def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: + """ + >>> multiply([[1,2],[3,4]],[[5,5],[7,5]]) + [[19, 15], [43, 35]] + >>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]]) + [[22.5, 17.5], [46.5, 37.5]] + >>> multiply([[1, 2, 3]], [[2], [3], [4]]) + [[20]] + """ if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) @@ -42,6 +81,13 @@ def identity(n: int) -> list[list[int]]: + """ + :param n: dimension for nxn matrix + :type n: int + :return: Identity matrix of shape [n, n] + >>> identity(3) + [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + """ n = int(n) return [[int(row == column) for column in range(n)] for row in range(n)] @@ -49,6 +95,16 @@ def transpose( matrix: list[list[int]], return_map: bool = True ) -> list[list[int]] | map[list[int]]: + """ + >>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS + <map object at ... + >>> transpose([[1,2],[3,4]], return_map=False) + [[1, 3], [2, 4]] + >>> transpose([1, [2, 3]]) + Traceback (most recent call last): + ... + TypeError: Expected a matrix, got int/list instead + """ if _check_not_integer(matrix): if return_map: return map(list, zip(*matrix)) @@ -58,11 +114,21 @@ def minor(matrix: list[list[int]], row: int, column: int) -> list[list[int]]: + """ + >>> minor([[1, 2], [3, 4]], 1, 1) + [[1]] + """ minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor] def determinant(matrix: list[list[int]]) -> Any: + """ + >>> determinant([[1, 2], [3, 4]]) + -2 + >>> determinant([[1.5, 2.5], [3, 4]]) + -1.5 + """ if len(matrix) == 1: return matrix[0][0] @@ -73,6 +139,11 @@ def inverse(matrix: list[list[int]]) -> list[list[float]] | None: + """ + >>> inverse([[1, 2], [3, 4]]) + [[-2.0, 1.0], [1.5, -0.5]] + >>> inverse([[1, 1], [1, 1]]) + """ # https://stackoverflow.com/questions/20047519/python-doctests-test-for-none det = determinant(matrix) if det == 0: @@ -129,4 +200,4 @@ import doctest doctest.testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/matrix_operation.py
Create documentation strings for testing functions
# @Author : ojas-wani # @File : matrix_multiplication_recursion.py # @Date : 10/06/2023 # type Matrix = list[list[int]] # psf/black currenttly fails on this line Matrix = list[list[int]] matrix_1_to_4 = [ [1, 2], [3, 4], ] matrix_5_to_8 = [ [5, 6], [7, 8], ] matrix_5_to_9_high = [ [5, 6], [7, 8], [9], ] matrix_5_to_9_wide = [ [5, 6], [7, 8, 9], ] matrix_count_up = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] matrix_unordered = [ [5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1], [2, 6, 10, 14], ] matrices = ( matrix_1_to_4, matrix_5_to_8, matrix_5_to_9_high, matrix_5_to_9_wide, matrix_count_up, matrix_unordered, ) def is_square(matrix: Matrix) -> bool: len_matrix = len(matrix) return all(len(row) == len_matrix for row in matrix) def matrix_multiply(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: return [ [sum(a * b for a, b in zip(row, col)) for col in zip(*matrix_b)] for row in matrix_a ] def matrix_multiply_recursive(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: if not matrix_a or not matrix_b: return [] if not all( (len(matrix_a) == len(matrix_b), is_square(matrix_a), is_square(matrix_b)) ): raise ValueError("Invalid matrix dimensions") # Initialize the result matrix with zeros result = [[0] * len(matrix_b[0]) for _ in range(len(matrix_a))] # Recursive multiplication of matrices def multiply( i_loop: int, j_loop: int, k_loop: int, matrix_a: Matrix, matrix_b: Matrix, result: Matrix, ) -> None: if i_loop >= len(matrix_a): return if j_loop >= len(matrix_b[0]): return multiply(i_loop + 1, 0, 0, matrix_a, matrix_b, result) if k_loop >= len(matrix_b): return multiply(i_loop, j_loop + 1, 0, matrix_a, matrix_b, result) result[i_loop][j_loop] += matrix_a[i_loop][k_loop] * matrix_b[k_loop][j_loop] return multiply(i_loop, j_loop, k_loop + 1, matrix_a, matrix_b, result) # Perform the recursive matrix multiplication multiply(0, 0, 0, matrix_a, matrix_b, result) return result if __name__ == "__main__": from doctest import testmod failure_count, test_count = testmod() if not failure_count: matrix_a = matrices[0] for matrix_b in matrices[1:]: print("Multiplying:") for row in matrix_a: print(row) print("By:") for row in matrix_b: print(row) print("Result:") try: result = matrix_multiply_recursive(matrix_a, matrix_b) for row in result: print(row) assert result == matrix_multiply(matrix_a, matrix_b) except ValueError as e: print(f"{e!r}") print() matrix_a = matrix_b print("Benchmark:") from functools import partial from timeit import timeit mytimeit = partial(timeit, globals=globals(), number=100_000) for func in ("matrix_multiply", "matrix_multiply_recursive"): print(f"{func:>25}(): {mytimeit(f'{func}(matrix_count_up, matrix_unordered)')}")
--- +++ @@ -3,6 +3,10 @@ # @Date : 10/06/2023 +""" +Perform matrix multiplication using a recursive algorithm. +https://en.wikipedia.org/wiki/Matrix_multiplication +""" # type Matrix = list[list[int]] # psf/black currenttly fails on this line Matrix = list[list[int]] @@ -52,11 +56,23 @@ def is_square(matrix: Matrix) -> bool: + """ + >>> is_square([]) + True + >>> is_square(matrix_1_to_4) + True + >>> is_square(matrix_5_to_9_high) + False + """ len_matrix = len(matrix) return all(len(row) == len_matrix for row in matrix) def matrix_multiply(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: + """ + >>> matrix_multiply(matrix_1_to_4, matrix_5_to_8) + [[19, 22], [43, 50]] + """ return [ [sum(a * b for a, b in zip(row, col)) for col in zip(*matrix_b)] for row in matrix_a @@ -64,6 +80,31 @@ def matrix_multiply_recursive(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: + """ + :param matrix_a: A square Matrix. + :param matrix_b: Another square Matrix with the same dimensions as matrix_a. + :return: Result of matrix_a * matrix_b. + :raises ValueError: If the matrices cannot be multiplied. + + >>> matrix_multiply_recursive([], []) + [] + >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_8) + [[19, 22], [43, 50]] + >>> matrix_multiply_recursive(matrix_count_up, matrix_unordered) + [[37, 61, 74, 61], [105, 165, 166, 129], [173, 269, 258, 197], [241, 373, 350, 265]] + >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_wide) + Traceback (most recent call last): + ... + ValueError: Invalid matrix dimensions + >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_high) + Traceback (most recent call last): + ... + ValueError: Invalid matrix dimensions + >>> matrix_multiply_recursive(matrix_1_to_4, matrix_count_up) + Traceback (most recent call last): + ... + ValueError: Invalid matrix dimensions + """ if not matrix_a or not matrix_b: return [] if not all( @@ -83,6 +124,16 @@ matrix_b: Matrix, result: Matrix, ) -> None: + """ + :param matrix_a: A square Matrix. + :param matrix_b: Another square Matrix with the same dimensions as matrix_a. + :param result: Result matrix + :param i: Index used for iteration during multiplication. + :param j: Index used for iteration during multiplication. + :param k: Index used for iteration during multiplication. + >>> 0 > 1 # Doctests in inner functions are never run + True + """ if i_loop >= len(matrix_a): return if j_loop >= len(matrix_b[0]): @@ -127,4 +178,4 @@ mytimeit = partial(timeit, globals=globals(), number=100_000) for func in ("matrix_multiply", "matrix_multiply_recursive"): - print(f"{func:>25}(): {mytimeit(f'{func}(matrix_count_up, matrix_unordered)')}")+ print(f"{func:>25}(): {mytimeit(f'{func}(matrix_count_up, matrix_unordered)')}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/matrix_multiplication_recursion.py
Generate docstrings for this script
def median(matrix: list[list[int]]) -> int: # Flatten the matrix into a sorted 1D list linear = sorted(num for row in matrix for num in row) # Calculate the middle index mid = (len(linear) - 1) // 2 # Return the median return linear[mid] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,27 @@+""" +https://en.wikipedia.org/wiki/Median +""" def median(matrix: list[list[int]]) -> int: + """ + Calculate the median of a sorted matrix. + + Args: + matrix: A 2D matrix of integers. + + Returns: + The median value of the matrix. + + Examples: + >>> matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]] + >>> median(matrix) + 5 + + >>> matrix = [[1, 2, 3], [4, 5, 6]] + >>> median(matrix) + 3 + """ # Flatten the matrix into a sorted 1D list linear = sorted(num for row in matrix for num in row) @@ -14,4 +35,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/median_matrix.py
Add docstrings explaining edge cases
from __future__ import annotations def make_matrix(row_size: int = 4) -> list[list[int]]: row_size = abs(row_size) or 4 return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] def rotate_90(matrix: list[list[int]]) -> list[list[int]]: return reverse_row(transpose(matrix)) # OR.. transpose(reverse_column(matrix)) def rotate_180(matrix: list[list[int]]) -> list[list[int]]: return reverse_row(reverse_column(matrix)) # OR.. reverse_column(reverse_row(matrix)) def rotate_270(matrix: list[list[int]]) -> list[list[int]]: return reverse_column(transpose(matrix)) # OR.. transpose(reverse_row(matrix)) def transpose(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [list(x) for x in zip(*matrix)] return matrix def reverse_row(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = matrix[::-1] return matrix def reverse_column(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [x[::-1] for x in matrix] return matrix def print_matrix(matrix: list[list[int]]) -> None: for i in matrix: print(*i) if __name__ == "__main__": matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_90(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_180(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_270(matrix))
--- +++ @@ -1,25 +1,61 @@+""" +In this problem, we want to rotate the matrix elements by 90, 180, 270 +(counterclockwise) +Discussion in stackoverflow: +https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array +""" from __future__ import annotations def make_matrix(row_size: int = 4) -> list[list[int]]: + """ + >>> make_matrix() + [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] + >>> make_matrix(1) + [[1]] + >>> make_matrix(-2) + [[1, 2], [3, 4]] + >>> make_matrix(3) + [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + >>> make_matrix() == make_matrix(4) + True + """ row_size = abs(row_size) or 4 return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] def rotate_90(matrix: list[list[int]]) -> list[list[int]]: + """ + >>> rotate_90(make_matrix()) + [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] + >>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix())) + True + """ return reverse_row(transpose(matrix)) # OR.. transpose(reverse_column(matrix)) def rotate_180(matrix: list[list[int]]) -> list[list[int]]: + """ + >>> rotate_180(make_matrix()) + [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] + >>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix())) + True + """ return reverse_row(reverse_column(matrix)) # OR.. reverse_column(reverse_row(matrix)) def rotate_270(matrix: list[list[int]]) -> list[list[int]]: + """ + >>> rotate_270(make_matrix()) + [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] + >>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix())) + True + """ return reverse_column(transpose(matrix)) # OR.. transpose(reverse_row(matrix)) @@ -62,4 +98,4 @@ print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") - print_matrix(rotate_270(matrix))+ print_matrix(rotate_270(matrix))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/rotate_matrix.py
Add docstrings that explain purpose and usage
def check_matrix(matrix: list[list[int]]) -> bool: # must be matrix = [list(row) for row in matrix] if matrix and isinstance(matrix, list): if isinstance(matrix[0], list): prev_len = 0 for row in matrix: if prev_len == 0: prev_len = len(row) result = True else: result = prev_len == len(row) else: result = True else: result = False return result def spiral_print_clockwise(a: list[list[int]]) -> None: if check_matrix(a) and len(a) > 0: a = [list(row) for row in a] mat_row = len(a) if isinstance(a[0], list): mat_col = len(a[0]) else: for dat in a: print(dat) return # horizotal printing increasing for i in range(mat_col): print(a[0][i]) # vertical printing down for i in range(1, mat_row): print(a[i][mat_col - 1]) # horizotal printing decreasing if mat_row > 1: for i in range(mat_col - 2, -1, -1): print(a[mat_row - 1][i]) # vertical printing up for i in range(mat_row - 2, 0, -1): print(a[i][0]) remain_mat = [row[1 : mat_col - 1] for row in a[1 : mat_row - 1]] if len(remain_mat) > 0: spiral_print_clockwise(remain_mat) else: return else: print("Not a valid matrix") return # Other Easy to understand Approach def spiral_traversal(matrix: list[list]) -> list[int]: if matrix: return list(matrix.pop(0)) + spiral_traversal( [list(row) for row in zip(*matrix)][::-1] ) else: return [] # driver code if __name__ == "__main__": import doctest doctest.testmod() a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] spiral_print_clockwise(a)
--- +++ @@ -1,3 +1,10 @@+""" +This program print the matrix in spiral form. +This problem has been solved through recursive way. + Matrix must satisfy below conditions + i) matrix should be only one or two dimensional + ii) number of column of all rows should be equal +""" def check_matrix(matrix: list[list[int]]) -> bool: @@ -21,6 +28,21 @@ def spiral_print_clockwise(a: list[list[int]]) -> None: + """ + >>> spiral_print_clockwise([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) + 1 + 2 + 3 + 4 + 8 + 12 + 11 + 10 + 9 + 5 + 6 + 7 + """ if check_matrix(a) and len(a) > 0: a = [list(row) for row in a] mat_row = len(a) @@ -58,6 +80,41 @@ def spiral_traversal(matrix: list[list]) -> list[int]: + """ + >>> spiral_traversal([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) + [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + + Example: + matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] + Algorithm: + Step 1. first pop the 0 index list. (which is [1,2,3,4] and concatenate the + output of [step 2]) + Step 2. Now perform matrix's Transpose operation (Change rows to column + and vice versa) and reverse the resultant matrix. + Step 3. Pass the output of [2nd step], to same recursive function till + base case hits. + Dry Run: + Stage 1. + [1, 2, 3, 4] + spiral_traversal([ + [8, 12], [7, 11], [6, 10], [5, 9]] + ]) + Stage 2. + [1, 2, 3, 4, 8, 12] + spiral_traversal([ + [11, 10, 9], [7, 6, 5] + ]) + Stage 3. + [1, 2, 3, 4, 8, 12, 11, 10, 9] + spiral_traversal([ + [5], [6], [7] + ]) + Stage 4. + [1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([ + [5], [6], [7] + ]) + Stage 5. + [1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([[6, 7]]) + Stage 6. + [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + spiral_traversal([]) + """ if matrix: return list(matrix.pop(0)) + spiral_traversal( [list(row) for row in zip(*matrix)][::-1] @@ -73,4 +130,4 @@ doctest.testmod() a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] - spiral_print_clockwise(a)+ spiral_print_clockwise(a)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/spiral_print.py
Add docstrings for internal functions
def print_pascal_triangle(num_rows: int) -> None: triangle = generate_pascal_triangle(num_rows) for row_idx in range(num_rows): # Print left spaces for _ in range(num_rows - row_idx - 1): print(end=" ") # Print row values for col_idx in range(row_idx + 1): if col_idx != row_idx: print(triangle[row_idx][col_idx], end=" ") else: print(triangle[row_idx][col_idx], end="") print() def generate_pascal_triangle(num_rows: int) -> list[list[int]]: if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) triangle: list[list[int]] = [] for current_row_idx in range(num_rows): current_row = populate_current_row(triangle, current_row_idx) triangle.append(current_row) return triangle def populate_current_row(triangle: list[list[int]], current_row_idx: int) -> list[int]: current_row = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 current_row[0], current_row[-1] = 1, 1 for current_col_idx in range(1, current_row_idx): calculate_current_element( triangle, current_row, current_row_idx, current_col_idx ) return current_row def calculate_current_element( triangle: list[list[int]], current_row: list[int], current_row_idx: int, current_col_idx: int, ) -> None: above_to_left_elt = triangle[current_row_idx - 1][current_col_idx - 1] above_to_right_elt = triangle[current_row_idx - 1][current_col_idx] current_row[current_col_idx] = above_to_left_elt + above_to_right_elt def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]: if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) result: list[list[int]] = [[1]] for row_index in range(1, num_rows): temp_row = [0] + result[-1] + [0] row_length = row_index + 1 # Calculate the number of distinct elements in a row distinct_elements = sum(divmod(row_length, 2)) row_first_half = [ temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1) ] row_second_half = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() row = row_first_half + row_second_half result.append(row) return result def benchmark() -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f"{call:38} -- {timing:.4f} seconds") for value in range(15): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
--- +++ @@ -1,6 +1,23 @@+""" +This implementation demonstrates how to generate the elements of a Pascal's triangle. +The element havingva row index of r and column index of c can be derivedvas follows: +triangle[r][c] = triangle[r-1][c-1]+triangle[r-1][c] + +A Pascal's triangle is a triangular array containing binomial coefficients. +https://en.wikipedia.org/wiki/Pascal%27s_triangle +""" def print_pascal_triangle(num_rows: int) -> None: + """ + Print Pascal's triangle for different number of rows + >>> print_pascal_triangle(5) + 1 + 1 1 + 1 2 1 + 1 3 3 1 + 1 4 6 4 1 + """ triangle = generate_pascal_triangle(num_rows) for row_idx in range(num_rows): # Print left spaces @@ -16,6 +33,29 @@ def generate_pascal_triangle(num_rows: int) -> list[list[int]]: + """ + Create Pascal's triangle for different number of rows + >>> generate_pascal_triangle(0) + [] + >>> generate_pascal_triangle(1) + [[1]] + >>> generate_pascal_triangle(2) + [[1], [1, 1]] + >>> generate_pascal_triangle(3) + [[1], [1, 1], [1, 2, 1]] + >>> generate_pascal_triangle(4) + [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] + >>> generate_pascal_triangle(5) + [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] + >>> generate_pascal_triangle(-5) + Traceback (most recent call last): + ... + ValueError: The input value of 'num_rows' should be greater than or equal to 0 + >>> generate_pascal_triangle(7.89) + Traceback (most recent call last): + ... + TypeError: The input value of 'num_rows' should be 'int' + """ if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") @@ -35,6 +75,11 @@ def populate_current_row(triangle: list[list[int]], current_row_idx: int) -> list[int]: + """ + >>> triangle = [[1]] + >>> populate_current_row(triangle, 1) + [1, 1] + """ current_row = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 current_row[0], current_row[-1] = 1, 1 @@ -51,12 +96,44 @@ current_row_idx: int, current_col_idx: int, ) -> None: + """ + >>> triangle = [[1], [1, 1]] + >>> current_row = [1, -1, 1] + >>> calculate_current_element(triangle, current_row, 2, 1) + >>> current_row + [1, 2, 1] + """ above_to_left_elt = triangle[current_row_idx - 1][current_col_idx - 1] above_to_right_elt = triangle[current_row_idx - 1][current_col_idx] current_row[current_col_idx] = above_to_left_elt + above_to_right_elt def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]: + """ + This function returns a matrix representing the corresponding pascal's triangle + according to the given input of number of rows of Pascal's triangle to be generated. + It reduces the operations done to generate a row by half + by eliminating redundant calculations. + + :param num_rows: Integer specifying the number of rows in the Pascal's triangle + :return: 2-D List (matrix) representing the Pascal's triangle + + Return the Pascal's triangle of given rows + >>> generate_pascal_triangle_optimized(3) + [[1], [1, 1], [1, 2, 1]] + >>> generate_pascal_triangle_optimized(1) + [[1]] + >>> generate_pascal_triangle_optimized(0) + [] + >>> generate_pascal_triangle_optimized(-5) + Traceback (most recent call last): + ... + ValueError: The input value of 'num_rows' should be greater than or equal to 0 + >>> generate_pascal_triangle_optimized(7.89) + Traceback (most recent call last): + ... + TypeError: The input value of 'num_rows' should be 'int' + """ if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") @@ -87,6 +164,9 @@ def benchmark() -> None: + """ + Benchmark multiple functions, with three different length int values. + """ from collections.abc import Callable from timeit import timeit @@ -106,4 +186,4 @@ import doctest doctest.testmod() - benchmark()+ benchmark()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/pascal_triangle.py
Provide clean and structured docstrings
import numpy as np def exponential_linear_unit(vector: np.ndarray, alpha: float) -> np.ndarray: return np.where(vector > 0, vector, (alpha * (np.exp(vector) - 1))) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,40 @@+""" +Implements the Exponential Linear Unit or ELU function. + +The function takes a vector of K real numbers and a real number alpha as +input and then applies the ELU function to each element of the vector. + +Script inspired from its corresponding Wikipedia article +https://en.wikipedia.org/wiki/Rectifier_(neural_networks) +""" import numpy as np def exponential_linear_unit(vector: np.ndarray, alpha: float) -> np.ndarray: + """ + Implements the ELU activation function. + Parameters: + vector: the array containing input of elu activation + alpha: hyper-parameter + return: + elu (np.array): The input numpy array after applying elu. + + Mathematically, f(x) = x, x>0 else (alpha * (e^x -1)), x<=0, alpha >=0 + + Examples: + >>> exponential_linear_unit(vector=np.array([2.3,0.6,-2,-3.8]), alpha=0.3) + array([ 2.3 , 0.6 , -0.25939942, -0.29328877]) + + >>> exponential_linear_unit(vector=np.array([-9.2,-0.3,0.45,-4.56]), alpha=0.067) + array([-0.06699323, -0.01736518, 0.45 , -0.06629904]) + + + """ return np.where(vector > 0, vector, (alpha * (np.exp(vector) - 1))) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/exponential_linear_unit.py
Add docstrings to clarify complex logic
def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n: int) -> list[list[int]]: return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n: int) -> int: if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n: int) -> int: if n <= 1: return n fib0 = 0 fib1 = 1 for _ in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main() -> None: for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -1,3 +1,19 @@+""" +Implementation of finding nth fibonacci number using matrix exponentiation. +Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix +multiplication of size 2 by 2. +And on the other hand complexity of bruteforce solution is O(n). +As we know + f[n] = f[n-1] + f[n-1] +Converting to matrix, + [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] +-> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] + ... + ... +-> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] +So we just need the n times multiplication of the matrix [1,1],[1,0]]. +We can decrease the n times multiplication by following the divide and conquer approach. +""" def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: @@ -19,6 +35,12 @@ def nth_fibonacci_matrix(n: int) -> int: + """ + >>> nth_fibonacci_matrix(100) + 354224848179261915075 + >>> nth_fibonacci_matrix(-100) + -100 + """ if n <= 1: return n res_matrix = identity(2) @@ -33,6 +55,12 @@ def nth_fibonacci_bruteforce(n: int) -> int: + """ + >>> nth_fibonacci_bruteforce(100) + 354224848179261915075 + >>> nth_fibonacci_bruteforce(-100) + -100 + """ if n <= 1: return n fib0 = 0 @@ -63,4 +91,4 @@ import doctest doctest.testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/nth_fibonacci_using_matrix_exponentiation.py
Generate consistent docstrings
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-vector)) def gaussian_error_linear_unit(vector: np.ndarray) -> np.ndarray: return vector * sigmoid(1.702 * vector) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,16 +1,51 @@+""" +This script demonstrates an implementation of the Gaussian Error Linear Unit function. +* https://en.wikipedia.org/wiki/Activation_function#Comparison_of_activation_functions + +The function takes a vector of K real numbers as input and returns x * sigmoid(1.702*x). +Gaussian Error Linear Unit (GELU) is a high-performing neural network activation +function. + +This script is inspired by a corresponding research paper. +* https://arxiv.org/abs/1606.08415 +""" import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: + """ + Mathematical function sigmoid takes a vector x of K real numbers as input and + returns 1/ (1 + e^-x). + https://en.wikipedia.org/wiki/Sigmoid_function + + >>> sigmoid(np.array([-1.0, 1.0, 2.0])) + array([0.26894142, 0.73105858, 0.88079708]) + """ return 1 / (1 + np.exp(-vector)) def gaussian_error_linear_unit(vector: np.ndarray) -> np.ndarray: + """ + Implements the Gaussian Error Linear Unit (GELU) function + + Parameters: + vector (np.ndarray): A numpy array of shape (1, n) consisting of real values + + Returns: + gelu_vec (np.ndarray): The input numpy array, after applying gelu + + Examples: + >>> gaussian_error_linear_unit(np.array([-1.0, 1.0, 2.0])) + array([-0.15420423, 0.84579577, 1.93565862]) + + >>> gaussian_error_linear_unit(np.array([-3])) + array([-0.01807131]) + """ return vector * sigmoid(1.702 * vector) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/gaussian_error_linear_unit.py
Auto-generate documentation strings for this file
graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def breadth_first_search(graph: list, source: int, sink: int, parents: list) -> bool: visited = [False] * len(graph) # Mark all nodes as not visited queue = [] # breadth-first search queue # Source node queue.append(source) visited[source] = True while queue: u = queue.pop(0) # Pop the front node # Traverse all adjacent nodes of u for ind, node in enumerate(graph[u]): if visited[ind] is False and node > 0: queue.append(ind) visited[ind] = True parents[ind] = u return visited[sink] def ford_fulkerson(graph: list, source: int, sink: int) -> int: # This array is filled by breadth-first search and to store path parent = [-1] * (len(graph)) max_flow = 0 # While there is a path from source to sink while breadth_first_search(graph, source, sink, parent): path_flow = int(1e9) # Infinite value s = sink while s != source: # Find the minimum value in the selected path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] return max_flow if __name__ == "__main__": from doctest import testmod testmod() print(f"{ford_fulkerson(graph, source=0, sink=5) = }")
--- +++ @@ -1,3 +1,11 @@+""" +Ford-Fulkerson Algorithm for Maximum Flow Problem +* https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm + +Description: + (1) Start with initial flow as 0 + (2) Choose the augmenting path from source to sink and add the path to flow +""" graph = [ [0, 16, 13, 0, 0, 0], @@ -10,6 +18,25 @@ def breadth_first_search(graph: list, source: int, sink: int, parents: list) -> bool: + """ + This function returns True if there is a node that has not iterated. + + Args: + graph: Adjacency matrix of graph + source: Source + sink: Sink + parents: Parent list + + Returns: + True if there is a node that has not iterated. + + >>> breadth_first_search(graph, 0, 5, [-1, -1, -1, -1, -1, -1]) + True + >>> breadth_first_search(graph, 0, 6, [-1, -1, -1, -1, -1, -1]) + Traceback (most recent call last): + ... + IndexError: list index out of range + """ visited = [False] * len(graph) # Mark all nodes as not visited queue = [] # breadth-first search queue @@ -29,6 +56,30 @@ def ford_fulkerson(graph: list, source: int, sink: int) -> int: + """ + This function returns the maximum flow from source to sink in the given graph. + + CAUTION: This function changes the given graph. + + Args: + graph: Adjacency matrix of graph + source: Source + sink: Sink + + Returns: + Maximum flow + + >>> test_graph = [ + ... [0, 16, 13, 0, 0, 0], + ... [0, 0, 10, 12, 0, 0], + ... [0, 4, 0, 0, 14, 0], + ... [0, 0, 9, 0, 0, 20], + ... [0, 0, 0, 7, 0, 4], + ... [0, 0, 0, 0, 0, 0], + ... ] + >>> ford_fulkerson(test_graph, 0, 5) + 23 + """ # This array is filled by breadth-first search and to store path parent = [-1] * (len(graph)) max_flow = 0 @@ -59,4 +110,4 @@ from doctest import testmod testmod() - print(f"{ford_fulkerson(graph, source=0, sink=5) = }")+ print(f"{ford_fulkerson(graph, source=0, sink=5) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/networking_flow/ford_fulkerson.py
Add docstrings that explain purpose and usage
import numpy as np def binary_step(vector: np.ndarray) -> np.ndarray: return np.where(vector >= 0, 1, 0) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,30 @@+""" +This script demonstrates the implementation of the Binary Step function. + +It's an activation function in which the neuron is activated if the input is positive +or 0, else it is deactivated + +It's a simple activation function which is mentioned in this wikipedia article: +https://en.wikipedia.org/wiki/Activation_function +""" import numpy as np def binary_step(vector: np.ndarray) -> np.ndarray: + """ + Implements the binary step function + + Parameters: + vector (ndarray): A vector that consists of numeric values + + Returns: + vector (ndarray): Input vector after applying binary step function + + >>> vector = np.array([-1.2, 0, 2, 1.45, -3.7, 0.3]) + >>> binary_step(vector) + array([0, 1, 1, 1, 0, 1]) + """ return np.where(vector >= 0, 1, 0) @@ -10,4 +32,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/binary_step.py
Generate missing documentation strings
from __future__ import annotations import numpy as np def relu(vector: list[float]): # compare two arrays and then return element-wise maxima. return np.maximum(0, vector) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
--- +++ @@ -1,3 +1,14 @@+""" +This script demonstrates the implementation of the ReLU function. + +It's a kind of activation function defined as the positive part of its argument in the +context of neural network. +The function takes a vector of K real numbers as input and then argmax(x, 0). +After through ReLU, the element of the vector always 0 or real number. + +Script inspired from its corresponding Wikipedia article +https://en.wikipedia.org/wiki/Rectifier_(neural_networks) +""" from __future__ import annotations @@ -5,10 +16,26 @@ def relu(vector: list[float]): + """ + Implements the relu function + + Parameters: + vector (np.array,list,tuple): A numpy array of shape (1,n) + consisting of real values or a similar list,tuple + + + Returns: + relu_vec (np.array): The input numpy array, after applying + relu. + + >>> vec = np.array([-1, 0, 5]) + >>> relu(vec) + array([0, 0, 5]) + """ # compare two arrays and then return element-wise maxima. return np.maximum(0, vector) if __name__ == "__main__": - print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]+ print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/rectified_linear_unit.py
Create docstrings for reusable components
import numpy as np def leaky_rectified_linear_unit(vector: np.ndarray, alpha: float) -> np.ndarray: return np.where(vector > 0, vector, alpha * vector) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,39 @@+""" +Leaky Rectified Linear Unit (Leaky ReLU) + +Use Case: Leaky ReLU addresses the problem of the vanishing gradient. +For more detailed information, you can refer to the following link: +https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Leaky_ReLU +""" import numpy as np def leaky_rectified_linear_unit(vector: np.ndarray, alpha: float) -> np.ndarray: + """ + Implements the LeakyReLU activation function. + + Parameters: + vector (np.ndarray): The input array for LeakyReLU activation. + alpha (float): The slope for negative values. + + Returns: + np.ndarray: The input array after applying the LeakyReLU activation. + + Formula: f(x) = x if x > 0 else f(x) = alpha * x + + Examples: + >>> leaky_rectified_linear_unit(vector=np.array([2.3,0.6,-2,-3.8]), alpha=0.3) + array([ 2.3 , 0.6 , -0.6 , -1.14]) + + >>> leaky_rectified_linear_unit(np.array([-9.2, -0.3, 0.45, -4.56]), alpha=0.067) + array([-0.6164 , -0.0201 , 0.45 , -0.30552]) + + """ return np.where(vector > 0, vector, alpha * vector) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/leaky_rectified_linear_unit.py
Generate docstrings for exported functions
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-vector)) def sigmoid_linear_unit(vector: np.ndarray) -> np.ndarray: return vector * sigmoid(vector) def swish(vector: np.ndarray, trainable_parameter: int) -> np.ndarray: return vector * sigmoid(trainable_parameter * vector) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,20 +1,75 @@+""" +This script demonstrates the implementation of the Sigmoid Linear Unit (SiLU) +or swish function. +* https://en.wikipedia.org/wiki/Rectifier_(neural_networks) +* https://en.wikipedia.org/wiki/Swish_function + +The function takes a vector x of K real numbers as input and returns x * sigmoid(x). +Swish is a smooth, non-monotonic function defined as f(x) = x * sigmoid(x). +Extensive experiments shows that Swish consistently matches or outperforms ReLU +on deep networks applied to a variety of challenging domains such as +image classification and machine translation. + +This script is inspired by a corresponding research paper. +* https://arxiv.org/abs/1710.05941 +* https://blog.paperspace.com/swish-activation-function/ +""" import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: + """ + Mathematical function sigmoid takes a vector x of K real numbers as input and + returns 1/ (1 + e^-x). + https://en.wikipedia.org/wiki/Sigmoid_function + + >>> sigmoid(np.array([-1.0, 1.0, 2.0])) + array([0.26894142, 0.73105858, 0.88079708]) + """ return 1 / (1 + np.exp(-vector)) def sigmoid_linear_unit(vector: np.ndarray) -> np.ndarray: + """ + Implements the Sigmoid Linear Unit (SiLU) or swish function + + Parameters: + vector (np.ndarray): A numpy array consisting of real values + + Returns: + swish_vec (np.ndarray): The input numpy array, after applying swish + + Examples: + >>> sigmoid_linear_unit(np.array([-1.0, 1.0, 2.0])) + array([-0.26894142, 0.73105858, 1.76159416]) + + >>> sigmoid_linear_unit(np.array([-2])) + array([-0.23840584]) + """ return vector * sigmoid(vector) def swish(vector: np.ndarray, trainable_parameter: int) -> np.ndarray: + """ + Parameters: + vector (np.ndarray): A numpy array consisting of real values + trainable_parameter: Use to implement various Swish Activation Functions + + Returns: + swish_vec (np.ndarray): The input numpy array, after applying swish + + Examples: + >>> swish(np.array([-1.0, 1.0, 2.0]), 2) + array([-0.11920292, 0.88079708, 1.96402758]) + + >>> swish(np.array([-2]), 1) + array([-0.23840584]) + """ return vector * sigmoid(trainable_parameter * vector) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/swish.py
Improve documentation using docstrings
from collections.abc import Callable from math import sqrt import numpy as np def runge_kutta_gills( func: Callable[[float, float], float], x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros(n + 1) y[0] = y_initial for i in range(n): k1 = step_size * func(x_initial, y[i]) k2 = step_size * func(x_initial + step_size / 2, y[i] + k1 / 2) k3 = step_size * func( x_initial + step_size / 2, y[i] + (-0.5 + 1 / sqrt(2)) * k1 + (1 - 1 / sqrt(2)) * k2, ) k4 = step_size * func( x_initial + step_size, y[i] - (1 / sqrt(2)) * k2 + (1 + 1 / sqrt(2)) * k3 ) y[i + 1] = y[i] + (k1 + (2 - sqrt(2)) * k2 + (2 + sqrt(2)) * k3 + k4) / 6 x_initial += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,9 @@+""" +Use the Runge-Kutta-Gill's method of order 4 to solve Ordinary Differential Equations. + +https://www.geeksforgeeks.org/gills-4th-order-method-to-solve-differential-equations/ +Author : Ravi Kumar +""" from collections.abc import Callable from math import sqrt @@ -12,6 +18,45 @@ step_size: float, x_final: float, ) -> np.ndarray: + """ + Solve an Ordinary Differential Equations using Runge-Kutta-Gills Method of order 4. + + args: + func: An ordinary differential equation (ODE) as function of x and y. + x_initial: The initial value of x. + y_initial: The initial value of y. + step_size: The increment value of x. + x_final: The final value of x. + + Returns: + Solution of y at each nodal point + + >>> def f(x, y): + ... return (x-y)/2 + >>> y = runge_kutta_gills(f, 0, 3, 0.2, 5) + >>> float(y[-1]) + 3.4104259225717537 + + >>> def f(x,y): + ... return x + >>> y = runge_kutta_gills(f, -1, 0, 0.2, 0) + >>> y + array([ 0. , -0.18, -0.32, -0.42, -0.48, -0.5 ]) + + >>> def f(x, y): + ... return x + y + >>> y = runge_kutta_gills(f, 0, 0, 0.2, -1) + Traceback (most recent call last): + ... + ValueError: The final value of x must be greater than initial value of x. + + >>> def f(x, y): + ... return x + >>> y = runge_kutta_gills(f, -1, 0, -0.2, 0) + Traceback (most recent call last): + ... + ValueError: Step size must be positive. + """ if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." @@ -42,4 +87,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/numerical_analysis/runge_kutta_gills.py
Generate docstrings for exported functions
import numpy as np def soboleva_modified_hyperbolic_tangent( vector: np.ndarray, a_value: float, b_value: float, c_value: float, d_value: float ) -> np.ndarray: # Separate the numerator and denominator for simplicity # Calculate the numerator and denominator element-wise numerator = np.exp(a_value * vector) - np.exp(-b_value * vector) denominator = np.exp(c_value * vector) + np.exp(-d_value * vector) # Calculate and return the final result element-wise return numerator / denominator if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,12 @@+""" +This script implements the Soboleva Modified Hyperbolic Tangent function. + +The function applies the Soboleva Modified Hyperbolic Tangent function +to each element of the vector. + +More details about the activation function can be found on: +https://en.wikipedia.org/wiki/Soboleva_modified_hyperbolic_tangent +""" import numpy as np @@ -5,6 +14,24 @@ def soboleva_modified_hyperbolic_tangent( vector: np.ndarray, a_value: float, b_value: float, c_value: float, d_value: float ) -> np.ndarray: + """ + Implements the Soboleva Modified Hyperbolic Tangent function + + Parameters: + vector (ndarray): A vector that consists of numeric values + a_value (float): parameter a of the equation + b_value (float): parameter b of the equation + c_value (float): parameter c of the equation + d_value (float): parameter d of the equation + + Returns: + vector (ndarray): Input array after applying SMHT function + + >>> vector = np.array([5.4, -2.4, 6.3, -5.23, 3.27, 0.56]) + >>> soboleva_modified_hyperbolic_tangent(vector, 0.2, 0.4, 0.6, 0.8) + array([ 0.11075085, -0.28236685, 0.07861169, -0.1180085 , 0.22999056, + 0.1566043 ]) + """ # Separate the numerator and denominator for simplicity # Calculate the numerator and denominator element-wise @@ -18,4 +45,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py
Write Python docstrings for this snippet
from __future__ import annotations from typing import Any class Matrix: def __init__(self, row: int, column: int, default_value: float = 0) -> None: self.row, self.column = row, column self.array = [[default_value for _ in range(column)] for _ in range(row)] def __str__(self) -> str: # Prefix s = f"Matrix consist of {self.row} rows and {self.column} columns\n" # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = f"%{max_element_length}s" # Make string and return def single_line(row_vector: list[float]) -> str: nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self) -> str: return str(self) def validate_indices(self, loc: tuple[int, int]) -> bool: if not (isinstance(loc, (list, tuple)) and len(loc) == 2): # noqa: SIM114 return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple[int, int]) -> Any: assert self.validate_indices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple[int, int], value: float) -> None: assert self.validate_indices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another: Matrix) -> Matrix: # Validation assert isinstance(another, Matrix) assert self.row == another.row assert self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self) -> Matrix: result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another: Matrix) -> Matrix: return self + (-another) def __mul__(self, another: float | Matrix) -> Matrix: if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: msg = f"Unsupported type given for another ({type(another)})" raise TypeError(msg) def transpose(self) -> Matrix: result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def sherman_morrison(self, u: Matrix, v: Matrix) -> Any: # Size validation assert isinstance(u, Matrix) assert isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate v_t = v.transpose() numerator_factor = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertible return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1() -> None: # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print(f"uv^T is {u * v.transpose()}") # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.sherman_morrison(u, v)}") def test2() -> None: import doctest doctest.testmod() test2()
--- +++ @@ -4,13 +4,31 @@ class Matrix: + """ + <class Matrix> + Matrix structure. + """ def __init__(self, row: int, column: int, default_value: float = 0) -> None: + """ + <method Matrix.__init__> + Initialize matrix with given size and default value. + Example: + >>> a = Matrix(2, 3, 1) + >>> a + Matrix consist of 2 rows and 3 columns + [1, 1, 1] + [1, 1, 1] + """ self.row, self.column = row, column self.array = [[default_value for _ in range(column)] for _ in range(row)] def __str__(self) -> str: + """ + <method Matrix.__str__> + Return string representation of this matrix. + """ # Prefix s = f"Matrix consist of {self.row} rows and {self.column} columns\n" @@ -37,6 +55,16 @@ return str(self) def validate_indices(self, loc: tuple[int, int]) -> bool: + """ + <method Matrix.validate_indicies> + Check if given indices are valid to pick element from matrix. + Example: + >>> a = Matrix(2, 6, 0) + >>> a.validate_indices((2, 7)) + False + >>> a.validate_indices((0, 0)) + True + """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): # noqa: SIM114 return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): @@ -45,14 +73,44 @@ return True def __getitem__(self, loc: tuple[int, int]) -> Any: + """ + <method Matrix.__getitem__> + Return array[row][column] where loc = (row, column). + Example: + >>> a = Matrix(3, 2, 7) + >>> a[1, 0] + 7 + """ assert self.validate_indices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple[int, int], value: float) -> None: + """ + <method Matrix.__setitem__> + Set array[row][column] = value where loc = (row, column). + Example: + >>> a = Matrix(2, 3, 1) + >>> a[1, 2] = 51 + >>> a + Matrix consist of 2 rows and 3 columns + [ 1, 1, 1] + [ 1, 1, 51] + """ assert self.validate_indices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another: Matrix) -> Matrix: + """ + <method Matrix.__add__> + Return self + another. + Example: + >>> a = Matrix(2, 1, -4) + >>> b = Matrix(2, 1, 3) + >>> a+b + Matrix consist of 2 rows and 1 columns + [-1] + [-1] + """ # Validation assert isinstance(another, Matrix) @@ -67,6 +125,17 @@ return result def __neg__(self) -> Matrix: + """ + <method Matrix.__neg__> + Return -self. + Example: + >>> a = Matrix(2, 2, 3) + >>> a[0, 1] = a[1, 0] = -2 + >>> -a + Matrix consist of 2 rows and 2 columns + [-3, 2] + [ 2, -3] + """ result = Matrix(self.row, self.column) for r in range(self.row): @@ -78,6 +147,17 @@ return self + (-another) def __mul__(self, another: float | Matrix) -> Matrix: + """ + <method Matrix.__mul__> + Return self * another. + Example: + >>> a = Matrix(2, 3, 1) + >>> a[0,2] = a[1,2] = 3 + >>> a * -2 + Matrix consist of 2 rows and 3 columns + [-2, -2, -6] + [-2, -2, -6] + """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) @@ -98,6 +178,21 @@ raise TypeError(msg) def transpose(self) -> Matrix: + """ + <method Matrix.transpose> + Return self^T. + Example: + >>> a = Matrix(2, 3) + >>> for r in range(2): + ... for c in range(3): + ... a[r,c] = r*c + ... + >>> a.transpose() + Matrix consist of 3 rows and 2 columns + [0, 0] + [0, 1] + [0, 2] + """ result = Matrix(self.column, self.row) for r in range(self.row): @@ -106,6 +201,29 @@ return result def sherman_morrison(self, u: Matrix, v: Matrix) -> Any: + """ + <method Matrix.sherman_morrison> + Apply Sherman-Morrison formula in O(n^2). + To learn this formula, please look this: + https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula + This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's + impossible to calculate. + Warning: This method doesn't check if self is invertible. + Make sure self is invertible before execute this method. + Example: + >>> ainv = Matrix(3, 3, 0) + >>> for i in range(3): ainv[i,i] = 1 + ... + >>> u = Matrix(3, 1, 0) + >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 + >>> v = Matrix(3, 1, 0) + >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 + >>> ainv.sherman_morrison(u, v) + Matrix consist of 3 rows and 3 columns + [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] + [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] + [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] + """ # Size validation assert isinstance(u, Matrix) @@ -146,4 +264,4 @@ doctest.testmod() - test2()+ test2()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/sherman_morrison.py
Add docstrings for internal functions
def validate_matrix_size(size: int) -> None: if not isinstance(size, int) or size <= 0: raise ValueError("Matrix size must be a positive integer.") def validate_matrix_content(matrix: list[str], size: int) -> None: print(matrix) if len(matrix) != size: raise ValueError("The matrix dont match with size.") for row in matrix: if len(row) != size: msg = f"Each row in the matrix must have exactly {size} characters." raise ValueError(msg) if not all(char.isalnum() for char in row): raise ValueError("Matrix rows can only contain letters and numbers.") def validate_moves(moves: list[tuple[int, int]], size: int) -> None: for move in moves: x, y = move if not (0 <= x < size and 0 <= y < size): raise ValueError("Move is out of bounds for a matrix.") def parse_moves(input_str: str) -> list[tuple[int, int]]: moves = [] for pair in input_str.split(","): parts = pair.strip().split() if len(parts) != 2: raise ValueError("Each move must have exactly two numbers.") x, y = map(int, parts) moves.append((x, y)) return moves def find_repeat( matrix_g: list[list[str]], row: int, column: int, size: int ) -> set[tuple[int, int]]: column = size - 1 - column visited = set() repeated = set() if (color := matrix_g[column][row]) != "-": def dfs(row_n: int, column_n: int) -> None: if row_n < 0 or row_n >= size or column_n < 0 or column_n >= size: return if (row_n, column_n) in visited: return visited.add((row_n, column_n)) if matrix_g[row_n][column_n] == color: repeated.add((row_n, column_n)) dfs(row_n - 1, column_n) dfs(row_n + 1, column_n) dfs(row_n, column_n - 1) dfs(row_n, column_n + 1) dfs(column, row) return repeated def increment_score(count: int) -> int: return int(count * (count + 1) / 2) def move_x(matrix_g: list[list[str]], column: int, size: int) -> list[list[str]]: new_list = [] for row in range(size): if matrix_g[row][column] != "-": new_list.append(matrix_g[row][column]) else: new_list.insert(0, matrix_g[row][column]) for row in range(size): matrix_g[row][column] = new_list[row] return matrix_g def move_y(matrix_g: list[list[str]], size: int) -> list[list[str]]: empty_columns = [] for column in range(size - 1, -1, -1): if all(matrix_g[row][column] == "-" for row in range(size)): empty_columns.append(column) for column in empty_columns: for col in range(column + 1, size): for row in range(size): matrix_g[row][col - 1] = matrix_g[row][col] for row in range(size): matrix_g[row][-1] = "-" return matrix_g def play( matrix_g: list[list[str]], pos_x: int, pos_y: int, size: int ) -> tuple[list[list[str]], int]: same_colors = find_repeat(matrix_g, pos_x, pos_y, size) if len(same_colors) != 0: for pos in same_colors: matrix_g[pos[0]][pos[1]] = "-" for column in range(size): matrix_g = move_x(matrix_g, column, size) matrix_g = move_y(matrix_g, size) return (matrix_g, increment_score(len(same_colors))) def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) -> int: game_matrix = [list(row) for row in matrix] total_score = 0 for move in moves: pos_x, pos_y = move game_matrix, score = play(game_matrix, pos_x, pos_y, size) total_score += score return total_score if __name__ == "__main__": import doctest doctest.testmod(verbose=True) try: size = int(input("Enter the size of the matrix: ")) validate_matrix_size(size) print(f"Enter the {size} rows of the matrix:") matrix = [input(f"Row {i + 1}: ") for i in range(size)] validate_matrix_content(matrix, size) moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ") moves = parse_moves(moves_input) validate_moves(moves, size) score = process_game(size, matrix, moves) print(f"Total score: {score}") except ValueError as e: print(f"{e}")
--- +++ @@ -1,11 +1,83 @@+""" +Matrix-Based Game Script +========================= +This script implements a matrix-based game where players interact with a grid of +elements. The primary goals are to: +- Identify connected elements of the same type from a selected position. +- Remove those elements, adjust the matrix by simulating gravity, and reorganize empty + columns. +- Calculate and display the score based on the number of elements removed in each move. + +Functions: +----------- +1. `find_repeat`: Finds all connected elements of the same type. +2. `increment_score`: Calculates the score for a given move. +3. `move_x`: Simulates gravity in a column. +4. `move_y`: Reorganizes the matrix by shifting columns leftward when a column becomes + empty. +5. `play`: Executes a single move, updating the matrix and returning the score. + +Input Format: +-------------- +1. Matrix size (`lines`): Integer specifying the size of the matrix (N x N). +2. Matrix content (`matrix`): Rows of the matrix, each consisting of characters. +3. Number of moves (`movs`): Integer indicating the number of moves. +4. List of moves (`movements`): A comma-separated string of coordinates for each move. + +(0,0) position starts from first left column to last right, and below row to up row + + +Example Input: +--------------- +4 +RRBG +RBBG +YYGG +XYGG +2 +0 1,1 1 + +Example (0,0) = X + +Output: +-------- +The script outputs the total score after processing all moves. + +Usage: +------- +Run the script and provide the required inputs as prompted. + +""" def validate_matrix_size(size: int) -> None: + """ + >>> validate_matrix_size(-1) + Traceback (most recent call last): + ... + ValueError: Matrix size must be a positive integer. + """ if not isinstance(size, int) or size <= 0: raise ValueError("Matrix size must be a positive integer.") def validate_matrix_content(matrix: list[str], size: int) -> None: + """ + Validates that the number of elements in the matrix matches the given size. + + >>> validate_matrix_content(['aaaa', 'aaaa', 'aaaa', 'aaaa'], 3) + Traceback (most recent call last): + ... + ValueError: The matrix dont match with size. + >>> validate_matrix_content(['aa%', 'aaa', 'aaa'], 3) + Traceback (most recent call last): + ... + ValueError: Matrix rows can only contain letters and numbers. + >>> validate_matrix_content(['aaa', 'aaa', 'aaaa'], 3) + Traceback (most recent call last): + ... + ValueError: Each row in the matrix must have exactly 3 characters. + """ print(matrix) if len(matrix) != size: raise ValueError("The matrix dont match with size.") @@ -18,6 +90,12 @@ def validate_moves(moves: list[tuple[int, int]], size: int) -> None: + """ + >>> validate_moves([(1, 2), (-1, 0)], 3) + Traceback (most recent call last): + ... + ValueError: Move is out of bounds for a matrix. + """ for move in moves: x, y = move if not (0 <= x < size and 0 <= y < size): @@ -25,6 +103,18 @@ def parse_moves(input_str: str) -> list[tuple[int, int]]: + """ + >>> parse_moves("0 1, 1 1") + [(0, 1), (1, 1)] + >>> parse_moves("0 1, 1 1, 2") + Traceback (most recent call last): + ... + ValueError: Each move must have exactly two numbers. + >>> parse_moves("0 1, 1 1, 2 4 5 6") + Traceback (most recent call last): + ... + ValueError: Each move must have exactly two numbers. + """ moves = [] for pair in input_str.split(","): parts = pair.strip().split() @@ -38,6 +128,14 @@ def find_repeat( matrix_g: list[list[str]], row: int, column: int, size: int ) -> set[tuple[int, int]]: + """ + Finds all connected elements of the same type from a given position. + + >>> find_repeat([['A', 'B', 'A'], ['A', 'B', 'A'], ['A', 'A', 'A']], 0, 0, 3) + {(1, 2), (2, 1), (0, 0), (2, 0), (0, 2), (2, 2), (1, 0)} + >>> find_repeat([['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']], 1, 1, 3) + set() + """ column = size - 1 - column visited = set() @@ -64,10 +162,24 @@ def increment_score(count: int) -> int: + """ + Calculates the score for a move based on the number of elements removed. + + >>> increment_score(3) + 6 + >>> increment_score(0) + 0 + """ return int(count * (count + 1) / 2) def move_x(matrix_g: list[list[str]], column: int, size: int) -> list[list[str]]: + """ + Simulates gravity in a specific column. + + >>> move_x([['-', 'A'], ['-', '-'], ['-', 'C']], 1, 2) + [['-', '-'], ['-', 'A'], ['-', 'C']] + """ new_list = [] @@ -82,6 +194,12 @@ def move_y(matrix_g: list[list[str]], size: int) -> list[list[str]]: + """ + Shifts all columns leftward when an entire column becomes empty. + + >>> move_y([['-', 'A'], ['-', '-'], ['-', 'C']], 2) + [['A', '-'], ['-', '-'], ['-', 'C']] + """ empty_columns = [] @@ -102,6 +220,12 @@ def play( matrix_g: list[list[str]], pos_x: int, pos_y: int, size: int ) -> tuple[list[list[str]], int]: + """ + Processes a single move, updating the matrix and calculating the score. + + >>> play([['R', 'G'], ['R', 'G']], 0, 0, 2) + ([['G', '-'], ['G', '-']], 3) + """ same_colors = find_repeat(matrix_g, pos_x, pos_y, size) @@ -117,6 +241,18 @@ def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) -> int: + """Processes the game logic for the given matrix and moves. + + Args: + size (int): Size of the game board. + matrix (List[str]): Initial game matrix. + moves (List[Tuple[int, int]]): List of moves as (x, y) coordinates. + + Returns: + int: The total score obtained. + >>> process_game(3, ['aaa', 'bbb', 'ccc'], [(0, 0)]) + 6 + """ game_matrix = [list(row) for row in matrix] total_score = 0 @@ -145,4 +281,4 @@ score = process_game(size, matrix, moves) print(f"Total score: {score}") except ValueError as e: - print(f"{e}")+ print(f"{e}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/matrix_based_game.py
Document all public functions with docstrings
import pickle import numpy as np from matplotlib import pyplot as plt class CNN: def __init__( self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2 ): self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 self.conv1 = conv1_get[:2] self.step_conv1 = conv1_get[2] self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t rng = np.random.default_rng() self.w_conv1 = [ np.asmatrix(-1 * rng.random((self.conv1[0], self.conv1[0])) + 0.5) for i in range(self.conv1[1]) ] self.wkj = np.asmatrix(-1 * rng.random((self.num_bp3, self.num_bp2)) + 0.5) self.vji = np.asmatrix(-1 * rng.random((self.num_bp2, self.num_bp1)) + 0.5) self.thre_conv1 = -2 * rng.random(self.conv1[1]) + 1 self.thre_bp2 = -2 * rng.random(self.num_bp2) + 1 self.thre_bp3 = -2 * rng.random(self.num_bp3) + 1 def save_model(self, save_path): # save model dict with pickle model_dic = { "num_bp1": self.num_bp1, "num_bp2": self.num_bp2, "num_bp3": self.num_bp3, "conv1": self.conv1, "step_conv1": self.step_conv1, "size_pooling1": self.size_pooling1, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conv1, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conv1, "thre_bp2": self.thre_bp2, "thre_bp3": self.thre_bp3, } with open(save_path, "wb") as f: pickle.dump(model_dic, f) print(f"Model saved: {save_path}") @classmethod def read_model(cls, model_path): # read saved model with open(model_path, "rb") as f: model_dic = pickle.load(f) # noqa: S301 conv_get = model_dic.get("conv1") conv_get.append(model_dic.get("step_conv1")) size_p1 = model_dic.get("size_pooling1") bp1 = model_dic.get("num_bp1") bp2 = model_dic.get("num_bp2") bp3 = model_dic.get("num_bp3") r_w = model_dic.get("rate_weight") r_t = model_dic.get("rate_thre") # create model instance conv_ins = CNN(conv_get, size_p1, bp1, bp2, bp3, r_w, r_t) # modify model parameter conv_ins.w_conv1 = model_dic.get("w_conv1") conv_ins.wkj = model_dic.get("wkj") conv_ins.vji = model_dic.get("vji") conv_ins.thre_conv1 = model_dic.get("thre_conv1") conv_ins.thre_bp2 = model_dic.get("thre_bp2") conv_ins.thre_bp3 = model_dic.get("thre_bp3") return conv_ins def sig(self, x): return 1 / (1 + np.exp(-1 * x)) def do_round(self, x): return round(x, 3) def convolute(self, data, convs, w_convs, thre_convs, conv_step): # convolution process size_conv = convs[0] num_conv = convs[1] size_data = np.shape(data)[0] # get the data slice of original image data, data_focus data_focus = [] for i_focus in range(0, size_data - size_conv + 1, conv_step): for j_focus in range(0, size_data - size_conv + 1, conv_step): focus = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(focus) # calculate the feature map of every single kernel, and saved as list of matrix data_featuremap = [] size_feature_map = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] for i_focus in range(len(data_focus)): net_focus = ( np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape( size_feature_map, size_feature_map ) data_featuremap.append(featuremap) # expanding the data slice to one dimension focus1_list = [] for each_focus in data_focus: focus1_list.extend(self.Expand_Mat(each_focus)) focus_list = np.asarray(focus1_list) return focus_list, data_featuremap def pooling(self, featuremaps, size_pooling, pooling_type="average_pool"): # pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map / size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): feature_map = featuremaps[i_map] map_pooled = [] for i_focus in range(0, size_map, size_pooling): for j_focus in range(0, size_map, size_pooling): focus = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(focus)) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled) featuremap_pooled.append(map_pooled) return featuremap_pooled def _expand(self, data): # expanding three dimension data to one dimension list data_expanded = [] for i in range(len(data)): shapes = np.shape(data[i]) data_listed = data[i].reshape(1, shapes[0] * shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) data_expanded = np.asarray(data_expanded) return data_expanded def _expand_mat(self, data_mat): # expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) data_expanded = data_mat.reshape(1, shapes[0] * shapes[1]) return data_expanded def _calculate_gradient_from_pool( self, out_map, pd_pool, num_map, size_map, size_pooling ): pd_all = [] i_pool = 0 for i_map in range(num_map): pd_conv1 = np.ones((size_map, size_map)) for i in range(0, size_map, size_pooling): for j in range(0, size_map, size_pooling): pd_conv1[i : i + size_pooling, j : j + size_pooling] = pd_pool[ i_pool ] i_pool = i_pool + 1 pd_conv2 = np.multiply( pd_conv1, np.multiply(out_map[i_map], (1 - out_map[i_map])) ) pd_all.append(pd_conv2) return pd_all def train( self, patterns, datas_train, datas_teach, n_repeat, error_accuracy, draw_e=bool ): # model training print("----------------------Start Training-------------------------") print((" - - Shape: Train_Data ", np.shape(datas_train))) print((" - - Shape: Teach_Data ", np.shape(datas_teach))) rp = 0 all_mse = [] mse = 10000 while rp < n_repeat and mse >= error_accuracy: error_count = 0 print(f"-------------Learning Time {rp}--------------") for p in range(len(datas_train)): # print('------------Learning Image: %d--------------'%p) data_train = np.asmatrix(datas_train[p]) data_teach = np.asarray(datas_teach[p]) data_focus1, data_conved1 = self.convolute( data_train, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) shape_featuremap1 = np.shape(data_conved1) """ print(' -----original shape ', np.shape(data_train)) print(' ---- after convolution ',np.shape(data_conv1)) print(' -----after pooling ',np.shape(data_pooled1)) """ data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = np.dot(bp_out1, self.vji.T) - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = np.dot(bp_out2, self.wkj.T) - self.thre_bp3 bp_out3 = self.sig(bp_net_k) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- pd_k_all = np.multiply( (data_teach - bp_out3), np.multiply(bp_out3, (1 - bp_out3)) ) pd_j_all = np.multiply( np.dot(pd_k_all, self.wkj), np.multiply(bp_out2, (1 - bp_out2)) ) pd_i_all = np.dot(pd_j_all, self.vji) pd_conv1_pooled = pd_i_all / (self.size_pooling1 * self.size_pooling1) pd_conv1_pooled = pd_conv1_pooled.T.getA().tolist() pd_conv1_all = self._calculate_gradient_from_pool( data_conved1, pd_conv1_pooled, shape_featuremap1[0], shape_featuremap1[1], self.size_pooling1, ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conv1[1]): pd_conv_list = self._expand_mat(pd_conv1_all[k_conv]) delta_w = self.rate_weight * np.dot(pd_conv_list, data_focus1) self.w_conv1[k_conv] = self.w_conv1[k_conv] + delta_w.reshape( (self.conv1[0], self.conv1[0]) ) self.thre_conv1[k_conv] = ( self.thre_conv1[k_conv] - np.sum(pd_conv1_all[k_conv]) * self.rate_thre ) # all connected layer self.wkj = self.wkj + pd_k_all.T * bp_out2 * self.rate_weight self.vji = self.vji + pd_j_all.T * bp_out1 * self.rate_weight self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image errors = np.sum(abs(data_teach - bp_out3)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) rp = rp + 1 mse = error_count / patterns all_mse.append(mse) def draw_error(): yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(all_mse, "+-") plt.plot(yplot, "r--") plt.xlabel("Learning Times") plt.ylabel("All_mse") plt.grid(True, alpha=0.5) plt.show() print("------------------Training Complete---------------------") print((" - - Training epoch: ", rp, f" - - Mse: {mse:.6f}")) if draw_e: draw_error() return mse def predict(self, datas_test): # model predict produce_out = [] print("-------------------Start Testing-------------------------") print((" - - Shape: Test_Data ", np.shape(datas_test))) for p in range(len(datas_test)): data_test = np.asmatrix(datas_test[p]) _data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = bp_out1 * self.vji.T - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = bp_out2 * self.wkj.T - self.thre_bp3 bp_out3 = self.sig(bp_net_k) produce_out.extend(bp_out3.getA().tolist()) res = [list(map(self.do_round, each)) for each in produce_out] return np.asarray(res) def convolution(self, data): # return the data of image after convoluting process so we can check it out data_test = np.asmatrix(data) _data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) return data_conved1, data_pooled1 if __name__ == "__main__": """ I will put the example in another file """
--- +++ @@ -1,3 +1,18 @@+""" + - - - - - -- - - - - - - - - - - - - - - - - - - - - - - +Name - - CNN - Convolution Neural Network For Photo Recognizing +Goal - - Recognize Handwriting Word Photo +Detail: Total 5 layers neural network + * Convolution layer + * Pooling layer + * Input layer layer of BP + * Hidden layer of BP + * Output layer of BP +Author: Stephen Lee +Github: 245885195@qq.com +Date: 2017.9.20 +- - - - - -- - - - - - - - - - - - - - - - - - - - - - - +""" import pickle @@ -9,6 +24,15 @@ def __init__( self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2 ): + """ + :param conv1_get: [a,c,d], size, number, step of convolution kernel + :param size_p1: pooling size + :param bp_num1: units number of flatten layer + :param bp_num2: units number of hidden layer + :param bp_num3: units number of output layer + :param rate_w: rate of weight learning + :param rate_t: rate of threshold learning + """ self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 @@ -163,6 +187,12 @@ def _calculate_gradient_from_pool( self, out_map, pd_pool, num_map, size_map, size_pooling ): + """ + calculate the gradient from the data slice of pool layer + pd_pool: list of matrix + out_map: the shape of data slice(size_map*size_map) + return: pd_all: list of matrix, [num, size_map, size_map] + """ pd_all = [] i_pool = 0 for i_map in range(num_map): @@ -324,4 +354,4 @@ if __name__ == "__main__": """ I will put the example in another file - """+ """
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/convolution_neural_network.py
Add docstrings to make code maintainable
import numpy as np from .softplus import softplus def mish(vector: np.ndarray) -> np.ndarray: return vector * np.tanh(softplus(vector)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,10 @@+""" +Mish Activation Function + +Use Case: Improved version of the ReLU activation function used in Computer Vision. +For more detailed information, you can refer to the following link: +https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Mish +""" import numpy as np @@ -5,10 +12,30 @@ def mish(vector: np.ndarray) -> np.ndarray: + """ + Implements the Mish activation function. + + Parameters: + vector (np.ndarray): The input array for Mish activation. + + Returns: + np.ndarray: The input array after applying the Mish activation. + + Formula: + f(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^x)) + + Examples: + >>> mish(vector=np.array([2.3,0.6,-2,-3.8])) + array([ 2.26211893, 0.46613649, -0.25250148, -0.08405831]) + + >>> mish(np.array([-9.2, -0.3, 0.45, -4.56])) + array([-0.00092952, -0.15113318, 0.33152014, -0.04745745]) + + """ return vector * np.tanh(softplus(vector)) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/mish.py
Help me comply with documentation standards
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import gzip import os import typing import urllib import numpy as np from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated class _Datasets(typing.NamedTuple): train: "_DataSet" validation: "_DataSet" test: "_DataSet" # CVDF mirror of http://yann.lecun.com/exdb/mnist/ DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _read32(bytestream): dt = np.dtype(np.uint32).newbyteorder(">") return np.frombuffer(bytestream.read(4), dtype=dt)[0] @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_images(f): print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: msg = f"Invalid magic number {magic} in MNIST image file: {f.name}" raise ValueError(msg) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = np.frombuffer(buf, dtype=np.uint8) data = data.reshape(num_images, rows, cols, 1) return data @deprecated(None, "Please use tf.one_hot on tensors.") def _dense_to_one_hot(labels_dense, num_classes): num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_labels(f, one_hot=False, num_classes=10): print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: msg = f"Invalid magic number {magic} in MNIST label file: {f.name}" raise ValueError(msg) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = np.frombuffer(buf, dtype=np.uint8) if one_hot: return _dense_to_one_hot(labels, num_classes) return labels class _DataSet: @deprecated( None, "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models.", ) def __init__( self, images, labels, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, seed=None, ): seed1, seed2 = random_seed.get_seed(seed) # If op level seed is not set, use whatever graph level seed is returned self._rng = np.random.default_rng(seed1 if seed is None else seed2) dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): msg = f"Invalid image dtype {dtype!r}, expected uint8 or float32" raise TypeError(msg) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else: assert images.shape[0] == labels.shape[0], ( f"images.shape: {images.shape} labels.shape: {labels.shape}" ) self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 images = images.reshape( images.shape[0], images.shape[1] * images.shape[2] ) if dtype == dtypes.float32: # Convert from [0, 255] -> [0.0, 1.0]. images = images.astype(np.float32) images = np.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False, shuffle=True): if fake_data: fake_image = [1] * 784 fake_label = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(batch_size)], [fake_label for _ in range(batch_size)], ) start = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: perm0 = np.arange(self._num_examples) self._rng.shuffle(perm0) self._images = self.images[perm0] self._labels = self.labels[perm0] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch rest_num_examples = self._num_examples - start images_rest_part = self._images[start : self._num_examples] labels_rest_part = self._labels[start : self._num_examples] # Shuffle the data if shuffle: perm = np.arange(self._num_examples) self._rng.shuffle(perm) self._images = self.images[perm] self._labels = self.labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size - rest_num_examples end = self._index_in_epoch images_new_part = self._images[start:end] labels_new_part = self._labels[start:end] return ( np.concatenate((images_rest_part, images_new_part), axis=0), np.concatenate((labels_rest_part, labels_new_part), axis=0), ) else: self._index_in_epoch += batch_size end = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(None, "Please write your own downloading logic.") def _maybe_download(filename, work_directory, source_url): if not gfile.Exists(work_directory): gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not gfile.Exists(filepath): urllib.request.urlretrieve(source_url, filepath) # noqa: S310 with gfile.GFile(filepath) as f: size = f.size() print("Successfully downloaded", filename, size, "bytes.") return filepath @deprecated(None, "Please use alternatives such as: tensorflow_datasets.load('mnist')") def read_data_sets( train_dir, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, validation_size=5000, seed=None, source_url=DEFAULT_SOURCE_URL, ): if fake_data: def fake(): return _DataSet( [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed ) train = fake() validation = fake() test = fake() return _Datasets(train=train, validation=validation, test=test) if not source_url: # empty string check source_url = DEFAULT_SOURCE_URL train_images_file = "train-images-idx3-ubyte.gz" train_labels_file = "train-labels-idx1-ubyte.gz" test_images_file = "t10k-images-idx3-ubyte.gz" test_labels_file = "t10k-labels-idx1-ubyte.gz" local_file = _maybe_download( train_images_file, train_dir, source_url + train_images_file ) with gfile.Open(local_file, "rb") as f: train_images = _extract_images(f) local_file = _maybe_download( train_labels_file, train_dir, source_url + train_labels_file ) with gfile.Open(local_file, "rb") as f: train_labels = _extract_labels(f, one_hot=one_hot) local_file = _maybe_download( test_images_file, train_dir, source_url + test_images_file ) with gfile.Open(local_file, "rb") as f: test_images = _extract_images(f) local_file = _maybe_download( test_labels_file, train_dir, source_url + test_labels_file ) with gfile.Open(local_file, "rb") as f: test_labels = _extract_labels(f, one_hot=one_hot) if not 0 <= validation_size <= len(train_images): msg = ( "Validation size should be between 0 and " f"{len(train_images)}. Received: {validation_size}." ) raise ValueError(msg) validation_images = train_images[:validation_size] validation_labels = train_labels[:validation_size] train_images = train_images[validation_size:] train_labels = train_labels[validation_size:] options = {"dtype": dtype, "reshape": reshape, "seed": seed} train = _DataSet(train_images, train_labels, **options) validation = _DataSet(validation_images, validation_labels, **options) test = _DataSet(test_images, test_labels, **options) return _Datasets(train=train, validation=validation, test=test)
--- +++ @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== +"""Functions for downloading and reading MNIST data (deprecated). + +This module and all its submodules are deprecated. +""" import gzip import os @@ -41,6 +45,18 @@ @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_images(f): + """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. + + Args: + f: A file object that can be passed into a gzip reader. + + Returns: + data: A 4D uint8 numpy array [index, y, x, depth]. + + Raises: + ValueError: If the bytestream does not start with 2051. + + """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) @@ -58,6 +74,7 @@ @deprecated(None, "Please use tf.one_hot on tensors.") def _dense_to_one_hot(labels_dense, num_classes): + """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) @@ -67,6 +84,19 @@ @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_labels(f, one_hot=False, num_classes=10): + """Extract the labels into a 1D uint8 numpy array [index]. + + Args: + f: A file object that can be passed into a gzip reader. + one_hot: Does one hot encoding for the result. + num_classes: Number of classes for the one hot encoding. + + Returns: + labels: a 1D uint8 numpy array. + + Raises: + ValueError: If the bystream doesn't start with 2049. + """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) @@ -82,6 +112,10 @@ class _DataSet: + """Container class for a _DataSet (deprecated). + + THIS CLASS IS DEPRECATED. + """ @deprecated( None, @@ -98,6 +132,23 @@ reshape=True, seed=None, ): + """Construct a _DataSet. + + one_hot arg is used only if fake_data is true. `dtype` can be either + `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into + `[0, 1]`. Seed arg provides for convenient deterministic testing. + + Args: + images: The images + labels: The labels + fake_data: Ignore inages and labels, use fake data. + one_hot: Bool, return the labels as one hot vectors (if True) or ints (if + False). + dtype: Output image dtype. One of [uint8, float32]. `uint8` output has + range [0,255]. float32 output has range [0,1]. + reshape: Bool. If True returned images are returned flattened to vectors. + seed: The random seed to use. + """ seed1, seed2 = random_seed.get_seed(seed) # If op level seed is not set, use whatever graph level seed is returned self._rng = np.random.default_rng(seed1 if seed is None else seed2) @@ -147,6 +198,7 @@ return self._epochs_completed def next_batch(self, batch_size, fake_data=False, shuffle=True): + """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image = [1] * 784 fake_label = [1] + [0] * 9 if self.one_hot else 0 @@ -193,6 +245,16 @@ @deprecated(None, "Please write your own downloading logic.") def _maybe_download(filename, work_directory, source_url): + """Download the data from source url, unless it's already here. + + Args: + filename: string, name of the file in the directory. + work_directory: string, path to working directory. + source_url: url to download from if file doesn't exist. + + Returns: + Path to resulting file. + """ if not gfile.Exists(work_directory): gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) @@ -277,4 +339,4 @@ validation = _DataSet(validation_images, validation_labels, **options) test = _DataSet(test_images, test_labels, **options) - return _Datasets(train=train, validation=validation, test=test)+ return _Datasets(train=train, validation=validation, test=test)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/input_data.py
Add docstrings following best practices
import numpy as np class TwoHiddenLayerNeuralNetwork: def __init__(self, input_array: np.ndarray, output_array: np.ndarray) -> None: # Input values provided for training the model. self.input_array = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. rng = np.random.default_rng() self.input_layer_and_first_hidden_layer_weights = rng.random( (self.input_array.shape[1], 4) ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. self.first_hidden_layer_and_second_hidden_layer_weights = rng.random((4, 3)) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. self.second_hidden_layer_and_output_layer_weights = rng.random((3, 1)) # Real output values provided. self.output_array = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. self.predicted_output = np.zeros(output_array.shape) def feedforward(self) -> np.ndarray: # Layer_between_input_and_first_hidden_layer is the layer connecting the # input nodes with the first hidden layer nodes. self.layer_between_input_and_first_hidden_layer = sigmoid( np.dot(self.input_array, self.input_layer_and_first_hidden_layer_weights) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( np.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. self.layer_between_second_hidden_layer_and_output = sigmoid( np.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return self.layer_between_second_hidden_layer_and_output def back_propagation(self) -> None: updated_second_hidden_layer_and_output_layer_weights = np.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T, 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), ) updated_first_hidden_layer_and_second_hidden_layer_weights = np.dot( self.layer_between_input_and_first_hidden_layer.T, np.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), ) updated_input_layer_and_first_hidden_layer_weights = np.dot( self.input_array.T, np.dot( np.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), self.first_hidden_layer_and_second_hidden_layer_weights.T, ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer), ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def train(self, output: np.ndarray, iterations: int, give_loss: bool) -> None: for iteration in range(1, iterations + 1): self.output = self.feedforward() self.back_propagation() if give_loss: loss = np.mean(np.square(output - self.feedforward())) print(f"Iteration {iteration} Loss: {loss}") def predict(self, input_arr: np.ndarray) -> int: # Input values for which the predictions are to be made. self.array = input_arr self.layer_between_input_and_first_hidden_layer = sigmoid( np.dot(self.array, self.input_layer_and_first_hidden_layer_weights) ) self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( np.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) self.layer_between_second_hidden_layer_and_output = sigmoid( np.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return int((self.layer_between_second_hidden_layer_and_output > 0.6)[0]) def sigmoid(value: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-value)) def sigmoid_derivative(value: np.ndarray) -> np.ndarray: return (value) * (1 - (value)) def example() -> int: # Input values. test_input = np.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ), dtype=np.float64, ) # True output values for the given input values. output = np.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=np.float64) # Calling neural network class. neural_network = TwoHiddenLayerNeuralNetwork( input_array=test_input, output_array=output ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=output, iterations=10, give_loss=False) return neural_network.predict(np.array(([1, 1, 1]), dtype=np.float64)) if __name__ == "__main__": example()
--- +++ @@ -1,9 +1,22 @@+""" +References: + - http://neuralnetworksanddeeplearning.com/chap2.html (Backpropagation) + - https://en.wikipedia.org/wiki/Sigmoid_function (Sigmoid activation function) + - https://en.wikipedia.org/wiki/Feedforward_neural_network (Feedforward) +""" import numpy as np class TwoHiddenLayerNeuralNetwork: def __init__(self, input_array: np.ndarray, output_array: np.ndarray) -> None: + """ + This function initializes the TwoHiddenLayerNeuralNetwork class with random + weights for every layer and initializes predicted output with zeroes. + + input_array : input values for training the neural network (i.e training data) . + output_array : expected output values of the given inputs. + """ # Input values provided for training the model. self.input_array = input_array @@ -38,6 +51,22 @@ self.predicted_output = np.zeros(output_array.shape) def feedforward(self) -> np.ndarray: + """ + The information moves in only one direction i.e. forward from the input nodes, + through the two hidden nodes and to the output nodes. + There are no cycles or loops in the network. + + Return layer_between_second_hidden_layer_and_output + (i.e the last layer of the neural network). + + >>> input_val = np.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) + >>> output_val = np.array(([0], [0], [0]), dtype=float) + >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) + >>> res = nn.feedforward() + >>> array_sum = np.sum(res) + >>> bool(np.isnan(array_sum)) + False + """ # Layer_between_input_and_first_hidden_layer is the layer connecting the # input nodes with the first hidden layer nodes. self.layer_between_input_and_first_hidden_layer = sigmoid( @@ -65,6 +94,20 @@ return self.layer_between_second_hidden_layer_and_output def back_propagation(self) -> None: + """ + Function for fine-tuning the weights of the neural net based on the + error rate obtained in the previous epoch (i.e., iteration). + Updation is done using derivative of sogmoid activation function. + + >>> input_val = np.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) + >>> output_val = np.array(([0], [0], [0]), dtype=float) + >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) + >>> res = nn.feedforward() + >>> nn.back_propagation() + >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights + >>> bool((res == updated_weights).all()) + False + """ updated_second_hidden_layer_and_output_layer_weights = np.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T, @@ -112,6 +155,25 @@ ) def train(self, output: np.ndarray, iterations: int, give_loss: bool) -> None: + """ + Performs the feedforwarding and back propagation process for the + given number of iterations. + Every iteration will update the weights of neural network. + + output : real output values,required for calculating loss. + iterations : number of times the weights are to be updated. + give_loss : boolean value, If True then prints loss for each iteration, + If False then nothing is printed + + >>> input_val = np.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) + >>> output_val = np.array(([0], [1], [1]), dtype=float) + >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) + >>> first_iteration_weights = nn.feedforward() + >>> nn.back_propagation() + >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights + >>> bool((first_iteration_weights == updated_weights).all()) + False + """ for iteration in range(1, iterations + 1): self.output = self.feedforward() self.back_propagation() @@ -120,6 +182,22 @@ print(f"Iteration {iteration} Loss: {loss}") def predict(self, input_arr: np.ndarray) -> int: + """ + Predict's the output for the given input values using + the trained neural network. + + The output value given by the model ranges in-between 0 and 1. + The predict function returns 1 if the model value is greater + than the threshold value else returns 0, + as the real output values are in binary. + + >>> input_val = np.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) + >>> output_val = np.array(([0], [1], [1]), dtype=float) + >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) + >>> nn.train(output_val, 1000, False) + >>> nn.predict([0, 1, 0]) in (0, 1) + True + """ # Input values for which the predictions are to be made. self.array = input_arr @@ -146,14 +224,44 @@ def sigmoid(value: np.ndarray) -> np.ndarray: + """ + Applies sigmoid activation function. + + return normalized values + + >>> sigmoid(np.array(([1, 0, 2], [1, 0, 0]), dtype=np.float64)) + array([[0.73105858, 0.5 , 0.88079708], + [0.73105858, 0.5 , 0.5 ]]) + """ return 1 / (1 + np.exp(-value)) def sigmoid_derivative(value: np.ndarray) -> np.ndarray: + """ + Provides the derivative value of the sigmoid function. + + returns derivative of the sigmoid value + + >>> sigmoid_derivative(np.array(([1, 0, 2], [1, 0, 0]), dtype=np.float64)) + array([[ 0., 0., -2.], + [ 0., 0., 0.]]) + """ return (value) * (1 - (value)) def example() -> int: + """ + Example for "how to use the neural network class and use the + respected methods for the desired output". + Calls the TwoHiddenLayerNeuralNetwork class and + provides the fixed input output values to the model. + Model is trained for a fixed amount of iterations then the predict method is called. + In this example the output is divided into 2 classes i.e. binary classification, + the two classes are represented by '0' and '1'. + + >>> example() in (0, 1) + True + """ # Input values. test_input = np.array( ( @@ -185,4 +293,4 @@ if __name__ == "__main__": - example()+ example()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/two_hidden_layers_neural_network.py
Annotate my code with docstrings
import numpy as np def scaled_exponential_linear_unit( vector: np.ndarray, alpha: float = 1.6732, lambda_: float = 1.0507 ) -> np.ndarray: return lambda_ * np.where(vector > 0, vector, alpha * (np.exp(vector) - 1)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,16 @@+""" +Implements the Scaled Exponential Linear Unit or SELU function. +The function takes a vector of K real numbers and two real numbers +alpha(default = 1.6732) & lambda (default = 1.0507) as input and +then applies the SELU function to each element of the vector. +SELU is a self-normalizing activation function. It is a variant +of the ELU. The main advantage of SELU is that we can be sure +that the output will always be standardized due to its +self-normalizing behavior. That means there is no need to +include Batch-Normalization layers. +References : +https://iq.opengenus.org/scaled-exponential-linear-unit/ +""" import numpy as np @@ -5,10 +18,27 @@ def scaled_exponential_linear_unit( vector: np.ndarray, alpha: float = 1.6732, lambda_: float = 1.0507 ) -> np.ndarray: + """ + Applies the Scaled Exponential Linear Unit function to each element of the vector. + Parameters : + vector : np.ndarray + alpha : float (default = 1.6732) + lambda_ : float (default = 1.0507) + + Returns : np.ndarray + Formula : f(x) = lambda_ * x if x > 0 + lambda_ * alpha * (e**x - 1) if x <= 0 + Examples : + >>> scaled_exponential_linear_unit(vector=np.array([1.3, 3.7, 2.4])) + array([1.36591, 3.88759, 2.52168]) + + >>> scaled_exponential_linear_unit(vector=np.array([1.3, 4.7, 8.2])) + array([1.36591, 4.93829, 8.61574]) + """ return lambda_ * np.where(vector > 0, vector, alpha * (np.exp(vector) - 1)) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/scaled_exponential_linear_unit.py
Generate docstrings for exported functions
from collections import defaultdict NUM_SQUARES = 9 EMPTY_CELL = "." def is_valid_sudoku_board(sudoku_board: list[list[str]]) -> bool: if len(sudoku_board) != NUM_SQUARES or ( any(len(row) != NUM_SQUARES for row in sudoku_board) ): error_message = f"Sudoku boards must be {NUM_SQUARES}x{NUM_SQUARES} squares." raise ValueError(error_message) row_values: defaultdict[int, set[str]] = defaultdict(set) col_values: defaultdict[int, set[str]] = defaultdict(set) box_values: defaultdict[tuple[int, int], set[str]] = defaultdict(set) for row in range(NUM_SQUARES): for col in range(NUM_SQUARES): value = sudoku_board[row][col] if value == EMPTY_CELL: continue box = (row // 3, col // 3) if ( value in row_values[row] or value in col_values[col] or value in box_values[box] ): return False row_values[row].add(value) col_values[col].add(value) box_values[box].add(value) return True if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(timeit("is_valid_sudoku_board(valid_board)", globals=globals())) print(timeit("is_valid_sudoku_board(invalid_board)", globals=globals()))
--- +++ @@ -1,3 +1,23 @@+""" +LeetCode 36. Valid Sudoku +https://leetcode.com/problems/valid-sudoku/ +https://en.wikipedia.org/wiki/Sudoku + +Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be +validated according to the following rules: + +- Each row must contain the digits 1-9 without repetition. +- Each column must contain the digits 1-9 without repetition. +- Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 + without repetition. + +Note: + +A Sudoku board (partially filled) could be valid but is not necessarily +solvable. + +Only the filled cells need to be validated according to the mentioned rules. +""" from collections import defaultdict @@ -6,6 +26,105 @@ def is_valid_sudoku_board(sudoku_board: list[list[str]]) -> bool: + """ + This function validates (but does not solve) a sudoku board. + The board may be valid but unsolvable. + + >>> is_valid_sudoku_board([ + ... ["5","3",".",".","7",".",".",".","."] + ... ,["6",".",".","1","9","5",".",".","."] + ... ,[".","9","8",".",".",".",".","6","."] + ... ,["8",".",".",".","6",".",".",".","3"] + ... ,["4",".",".","8",".","3",".",".","1"] + ... ,["7",".",".",".","2",".",".",".","6"] + ... ,[".","6",".",".",".",".","2","8","."] + ... ,[".",".",".","4","1","9",".",".","5"] + ... ,[".",".",".",".","8",".",".","7","9"] + ... ]) + True + >>> is_valid_sudoku_board([ + ... ["8","3",".",".","7",".",".",".","."] + ... ,["6",".",".","1","9","5",".",".","."] + ... ,[".","9","8",".",".",".",".","6","."] + ... ,["8",".",".",".","6",".",".",".","3"] + ... ,["4",".",".","8",".","3",".",".","1"] + ... ,["7",".",".",".","2",".",".",".","6"] + ... ,[".","6",".",".",".",".","2","8","."] + ... ,[".",".",".","4","1","9",".",".","5"] + ... ,[".",".",".",".","8",".",".","7","9"] + ... ]) + False + >>> is_valid_sudoku_board([ + ... ["1","2","3","4","5","6","7","8","9"] + ... ,["4","5","6","7","8","9","1","2","3"] + ... ,["7","8","9","1","2","3","4","5","6"] + ... ,[".",".",".",".",".",".",".",".","."] + ... ,[".",".",".",".",".",".",".",".","."] + ... ,[".",".",".",".",".",".",".",".","."] + ... ,[".",".",".",".",".",".",".",".","."] + ... ,[".",".",".",".",".",".",".",".","."] + ... ,[".",".",".",".",".",".",".",".","."] + ... ]) + True + >>> is_valid_sudoku_board([ + ... ["1","2","3",".",".",".",".",".","."] + ... ,["4","5","6",".",".",".",".",".","."] + ... ,["7","8","9",".",".",".",".",".","."] + ... ,[".",".",".","4","5","6",".",".","."] + ... ,[".",".",".","7","8","9",".",".","."] + ... ,[".",".",".","1","2","3",".",".","."] + ... ,[".",".",".",".",".",".","7","8","9"] + ... ,[".",".",".",".",".",".","1","2","3"] + ... ,[".",".",".",".",".",".","4","5","6"] + ... ]) + True + >>> is_valid_sudoku_board([ + ... ["1","2","3",".",".",".","5","6","4"] + ... ,["4","5","6",".",".",".","8","9","7"] + ... ,["7","8","9",".",".",".","2","3","1"] + ... ,[".",".",".","4","5","6",".",".","."] + ... ,[".",".",".","7","8","9",".",".","."] + ... ,[".",".",".","1","2","3",".",".","."] + ... ,["3","1","2",".",".",".","7","8","9"] + ... ,["6","4","5",".",".",".","1","2","3"] + ... ,["9","7","8",".",".",".","4","5","6"] + ... ]) + True + >>> is_valid_sudoku_board([ + ... ["1","2","3","4","5","6","7","8","9"] + ... ,["2",".",".",".",".",".",".",".","8"] + ... ,["3",".",".",".",".",".",".",".","7"] + ... ,["4",".",".",".",".",".",".",".","6"] + ... ,["5",".",".",".",".",".",".",".","5"] + ... ,["6",".",".",".",".",".",".",".","4"] + ... ,["7",".",".",".",".",".",".",".","3"] + ... ,["8",".",".",".",".",".",".",".","2"] + ... ,["9","8","7","6","5","4","3","2","1"] + ... ]) + False + >>> is_valid_sudoku_board([ + ... ["1","2","3","8","9","7","5","6","4"] + ... ,["4","5","6","2","3","1","8","9","7"] + ... ,["7","8","9","5","6","4","2","3","1"] + ... ,["2","3","1","4","5","6","9","7","8"] + ... ,["5","6","4","7","8","9","3","1","2"] + ... ,["8","9","7","1","2","3","6","4","5"] + ... ,["3","1","2","6","4","5","7","8","9"] + ... ,["6","4","5","9","7","8","1","2","3"] + ... ,["9","7","8","3","1","2","4","5","6"] + ... ]) + True + >>> is_valid_sudoku_board([["1", "2", "3", "4", "5", "6", "7", "8", "9"]]) + Traceback (most recent call last): + ... + ValueError: Sudoku boards must be 9x9 squares. + >>> is_valid_sudoku_board( + ... [["1"], ["2"], ["3"], ["4"], ["5"], ["6"], ["7"], ["8"], ["9"]] + ... ) + Traceback (most recent call last): + ... + ValueError: Sudoku boards must be 9x9 squares. + """ if len(sudoku_board) != NUM_SQUARES or ( any(len(row) != NUM_SQUARES for row in sudoku_board) ): @@ -45,4 +164,4 @@ testmod() print(timeit("is_valid_sudoku_board(valid_board)", globals=globals())) - print(timeit("is_valid_sudoku_board(invalid_board)", globals=globals()))+ print(timeit("is_valid_sudoku_board(invalid_board)", globals=globals()))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/matrix/validate_sudoku_board.py
Improve my code by adding docstrings
from __future__ import annotations from collections import deque from enum import Enum from math import atan2, degrees from sys import maxsize # traversal from the lowest and the most left point in anti-clockwise direction # if direction gets right, the previous point is not the convex hull. class Direction(Enum): left = 1 straight = 2 right = 3 def __repr__(self): return f"{self.__class__.__name__}.{self.name}" def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float: # sort the points accorgind to the angle from the lowest and the most left point x, y = point return degrees(atan2(y - miny, x - minx)) def check_direction( starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int] ) -> Direction: x0, y0 = starting x1, y1 = via x2, y2 = target via_angle = degrees(atan2(y1 - y0, x1 - x0)) via_angle %= 360 target_angle = degrees(atan2(y2 - y0, x2 - x0)) target_angle %= 360 # t- # \ \ # \ v # \| # s # via_angle is always lower than target_angle, if direction is left. # If they are same, it means they are on a same line of convex hull. if target_angle > via_angle: return Direction.left elif target_angle == via_angle: return Direction.straight else: return Direction.right def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]: if len(points) <= 2: # There is no convex hull raise ValueError("graham_scan: argument must contain more than 3 points.") if len(points) == 3: return points # find the lowest and the most left point minidx = 0 miny, minx = maxsize, maxsize for i, point in enumerate(points): x = point[0] y = point[1] if y < miny: miny = y minx = x minidx = i if y == miny and x < minx: minx = x minidx = i # remove the lowest and the most left point from points for preparing for sort points.pop(minidx) sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny)) # This insert actually costs complexity, # and you should instead add (minx, miny) into stack later. # I'm using insert just for easy understanding. sorted_points.insert(0, (minx, miny)) stack: deque[tuple[int, int]] = deque() stack.append(sorted_points[0]) stack.append(sorted_points[1]) stack.append(sorted_points[2]) # The first 3 points lines are towards the left because we sort them by their angle # from minx, miny. current_direction = Direction.left for i in range(3, len(sorted_points)): while True: starting = stack[-2] via = stack[-1] target = sorted_points[i] next_direction = check_direction(starting, via, target) if next_direction == Direction.left: current_direction = Direction.left break if next_direction == Direction.straight: if current_direction == Direction.left: # We keep current_direction as left. # Because if the straight line keeps as straight, # we want to know if this straight line is towards left. break elif current_direction == Direction.right: # If the straight line is towards right, # every previous points on that straight line is not convex hull. stack.pop() if next_direction == Direction.right: stack.pop() stack.append(sorted_points[i]) return list(stack)
--- +++ @@ -1,3 +1,10 @@+""" +This is a pure Python implementation of the Graham scan algorithm +Source: https://en.wikipedia.org/wiki/Graham_scan + +For doctests run following command: +python3 -m doctest -v graham_scan.py +""" from __future__ import annotations @@ -19,6 +26,23 @@ def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float: + """Return the angle toward to point from (minx, miny) + + :param point: The target point + minx: The starting point's x + miny: The starting point's y + :return: the angle + + Examples: + >>> angle_comparer((1,1), 0, 0) + 45.0 + + >>> angle_comparer((100,1), 10, 10) + -5.710593137499642 + + >>> angle_comparer((5,5), 2, 3) + 33.690067525979785 + """ # sort the points accorgind to the angle from the lowest and the most left point x, y = point return degrees(atan2(y - miny, x - minx)) @@ -27,6 +51,23 @@ def check_direction( starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int] ) -> Direction: + """Return the direction toward to the line from via to target from starting + + :param starting: The starting point + via: The via point + target: The target point + :return: the Direction + + Examples: + >>> check_direction((1,1), (2,2), (3,3)) + Direction.straight + + >>> check_direction((60,1), (-50,199), (30,2)) + Direction.left + + >>> check_direction((0,0), (5,5), (10,0)) + Direction.right + """ x0, y0 = starting x1, y1 = via x2, y2 = target @@ -50,6 +91,24 @@ def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]: + """Pure implementation of graham scan algorithm in Python + + :param points: The unique points on coordinates. + :return: The points on convex hell. + + Examples: + >>> graham_scan([(9, 6), (3, 1), (0, 0), (5, 5), (5, 2), (7, 0), (3, 3), (1, 4)]) + [(0, 0), (7, 0), (9, 6), (5, 5), (1, 4)] + + >>> graham_scan([(0, 0), (1, 0), (1, 1), (0, 1)]) + [(0, 0), (1, 0), (1, 1), (0, 1)] + + >>> graham_scan([(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)]) + [(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)] + + >>> graham_scan([(-100, 20), (99, 3), (1, 10000001), (5133186, -25), (-66, -4)]) + [(5133186, -25), (1, 10000001), (-100, 20), (-66, -4)] + """ if len(points) <= 2: # There is no convex hull @@ -110,4 +169,4 @@ if next_direction == Direction.right: stack.pop() stack.append(sorted_points[i]) - return list(stack)+ return list(stack)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/graham_scan.py
Document all public functions with docstrings
# Python program for generating diamond pattern in Python 3.7+ # Function to print upper half of diamond (pyramid) def floyd(n): result = "" for i in range(n): for _ in range(n - i - 1): # printing spaces result += " " for _ in range(i + 1): # printing stars result += "* " result += "\n" return result # Function to print lower half of diamond (pyramid) def reverse_floyd(n): result = "" for i in range(n, 0, -1): for _ in range(i, 0, -1): # printing stars result += "* " result += "\n" for _ in range(n - i + 1, 0, -1): # printing spaces result += " " return result # Function to print complete diamond pattern of "*" def pretty_print(n): if n <= 0: return " ... .... nothing printing :(" upper_half = floyd(n) # upper half lower_half = reverse_floyd(n) # lower half return upper_half + lower_half if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,40 +1,79 @@-# Python program for generating diamond pattern in Python 3.7+ - - -# Function to print upper half of diamond (pyramid) -def floyd(n): - result = "" - for i in range(n): - for _ in range(n - i - 1): # printing spaces - result += " " - for _ in range(i + 1): # printing stars - result += "* " - result += "\n" - return result - - -# Function to print lower half of diamond (pyramid) -def reverse_floyd(n): - result = "" - for i in range(n, 0, -1): - for _ in range(i, 0, -1): # printing stars - result += "* " - result += "\n" - for _ in range(n - i + 1, 0, -1): # printing spaces - result += " " - return result - - -# Function to print complete diamond pattern of "*" -def pretty_print(n): - if n <= 0: - return " ... .... nothing printing :(" - upper_half = floyd(n) # upper half - lower_half = reverse_floyd(n) # lower half - return upper_half + lower_half - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+# Python program for generating diamond pattern in Python 3.7+ + + +# Function to print upper half of diamond (pyramid) +def floyd(n): + """ + Print the upper half of a diamond pattern with '*' characters. + + Args: + n (int): Size of the pattern. + + Examples: + >>> floyd(3) + ' * \\n * * \\n* * * \\n' + + >>> floyd(5) + ' * \\n * * \\n * * * \\n * * * * \\n* * * * * \\n' + """ + result = "" + for i in range(n): + for _ in range(n - i - 1): # printing spaces + result += " " + for _ in range(i + 1): # printing stars + result += "* " + result += "\n" + return result + + +# Function to print lower half of diamond (pyramid) +def reverse_floyd(n): + """ + Print the lower half of a diamond pattern with '*' characters. + + Args: + n (int): Size of the pattern. + + Examples: + >>> reverse_floyd(3) + '* * * \\n * * \\n * \\n ' + + >>> reverse_floyd(5) + '* * * * * \\n * * * * \\n * * * \\n * * \\n * \\n ' + """ + result = "" + for i in range(n, 0, -1): + for _ in range(i, 0, -1): # printing stars + result += "* " + result += "\n" + for _ in range(n - i + 1, 0, -1): # printing spaces + result += " " + return result + + +# Function to print complete diamond pattern of "*" +def pretty_print(n): + """ + Print a complete diamond pattern with '*' characters. + + Args: + n (int): Size of the pattern. + + Examples: + >>> pretty_print(0) + ' ... .... nothing printing :(' + + >>> pretty_print(3) + ' * \\n * * \\n* * * \\n* * * \\n * * \\n * \\n ' + """ + if n <= 0: + return " ... .... nothing printing :(" + upper_half = floyd(n) # upper half + lower_half = reverse_floyd(n) # lower half + return upper_half + lower_half + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/magicdiamondpattern.py
Add docstrings for internal functions
import math from datetime import UTC, datetime, timedelta def gauss_easter(year: int) -> datetime: metonic_cycle = year % 19 julian_leap_year = year % 4 non_leap_year = year % 7 leap_day_inhibits = math.floor(year / 100) lunar_orbit_correction = math.floor((13 + 8 * leap_day_inhibits) / 25) leap_day_reinstall_number = leap_day_inhibits / 4 secular_moon_shift = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 century_starting_point = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 days_to_add = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon days_from_phm_to_sunday = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(year, 4, 19, tzinfo=UTC) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(year, 4, 18, tzinfo=UTC) else: return datetime(year, 3, 22, tzinfo=UTC) + timedelta( days=int(days_to_add + days_from_phm_to_sunday) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023, 2032, 2100): tense = "will be" if year > datetime.now(tz=UTC).year else "was" print(f"Easter in {year} {tense} {gauss_easter(year)}")
--- +++ @@ -1,9 +1,27 @@+""" +https://en.wikipedia.org/wiki/Computus#Gauss'_Easter_algorithm +""" import math from datetime import UTC, datetime, timedelta def gauss_easter(year: int) -> datetime: + """ + Calculation Gregorian easter date for given year + + >>> gauss_easter(2007) + datetime.datetime(2007, 4, 8, 0, 0, tzinfo=datetime.timezone.utc) + + >>> gauss_easter(2008) + datetime.datetime(2008, 3, 23, 0, 0, tzinfo=datetime.timezone.utc) + + >>> gauss_easter(2020) + datetime.datetime(2020, 4, 12, 0, 0, tzinfo=datetime.timezone.utc) + + >>> gauss_easter(2021) + datetime.datetime(2021, 4, 4, 0, 0, tzinfo=datetime.timezone.utc) + """ metonic_cycle = year % 19 julian_leap_year = year % 4 non_leap_year = year % 7 @@ -39,4 +57,4 @@ if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023, 2032, 2100): tense = "will be" if year > datetime.now(tz=UTC).year else "was" - print(f"Easter in {year} {tense} {gauss_easter(year)}")+ print(f"Easter in {year} {tense} {gauss_easter(year)}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/gauss_easter.py
Document this code for team use
#!/usr/bin/python import numpy as np from matplotlib import pyplot as plt def sigmoid(x: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-x)) class DenseLayer: def __init__( self, units, activation=None, learning_rate=None, is_input_layer=False ): self.units = units self.weight = None self.bias = None self.activation = activation if learning_rate is None: learning_rate = 0.3 self.learn_rate = learning_rate self.is_input_layer = is_input_layer def initializer(self, back_units): rng = np.random.default_rng() self.weight = np.asmatrix(rng.normal(0, 0.5, (self.units, back_units))) self.bias = np.asmatrix(rng.normal(0, 0.5, self.units)).T if self.activation is None: self.activation = sigmoid def cal_gradient(self): # activation function may be sigmoid or linear if self.activation == sigmoid: gradient_mat = np.dot(self.output, (1 - self.output).T) gradient_activation = np.diag(np.diag(gradient_mat)) else: gradient_activation = 1 return gradient_activation def forward_propagation(self, xdata): self.xdata = xdata if self.is_input_layer: # input layer self.wx_plus_b = xdata self.output = xdata return xdata else: self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias self.output = self.activation(self.wx_plus_b) return self.output def back_propagation(self, gradient): gradient_activation = self.cal_gradient() # i * i 维 gradient = np.asmatrix(np.dot(gradient.T, gradient_activation)) self._gradient_weight = np.asmatrix(self.xdata) self._gradient_bias = -1 self._gradient_x = self.weight self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T) self.gradient_bias = gradient * self._gradient_bias self.gradient = np.dot(gradient, self._gradient_x).T # upgrade: the Negative gradient direction self.weight = self.weight - self.learn_rate * self.gradient_weight self.bias = self.bias - self.learn_rate * self.gradient_bias.T # updates the weights and bias according to learning rate (0.3 if undefined) return self.gradient class BPNN: def __init__(self): self.layers = [] self.train_mse = [] self.fig_loss = plt.figure() self.ax_loss = self.fig_loss.add_subplot(1, 1, 1) def add_layer(self, layer): self.layers.append(layer) def build(self): for i, layer in enumerate(self.layers[:]): if i < 1: layer.is_input_layer = True else: layer.initializer(self.layers[i - 1].units) def summary(self): for i, layer in enumerate(self.layers[:]): print(f"------- layer {i} -------") print("weight.shape ", np.shape(layer.weight)) print("bias.shape ", np.shape(layer.bias)) def train(self, xdata, ydata, train_round, accuracy): self.train_round = train_round self.accuracy = accuracy self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) for _ in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row, :]).T _ydata = np.asmatrix(ydata[row, :]).T # forward propagation for layer in self.layers: _xdata = layer.forward_propagation(_xdata) loss, gradient = self.cal_loss(_ydata, _xdata) all_loss = all_loss + loss # back propagation: the input_layer does not upgrade for layer in self.layers[:0:-1]: gradient = layer.back_propagation(gradient) mse = all_loss / x_shape[0] self.train_mse.append(mse) self.plot_loss() if mse < self.accuracy: print("----达到精度----") return mse return None def cal_loss(self, ydata, ydata_): self.loss = np.sum(np.power((ydata - ydata_), 2)) self.loss_gradient = 2 * (ydata_ - ydata) # vector (shape is the same as _ydata.shape) return self.loss, self.loss_gradient def plot_loss(self): if self.ax_loss.lines: self.ax_loss.lines.remove(self.ax_loss.lines[0]) self.ax_loss.plot(self.train_mse, "r-") plt.ion() plt.xlabel("step") plt.ylabel("loss") plt.show() plt.pause(0.1) def example(): rng = np.random.default_rng() x = rng.normal(size=(10, 10)) y = np.asarray( [ [0.8, 0.4], [0.4, 0.3], [0.34, 0.45], [0.67, 0.32], [0.88, 0.67], [0.78, 0.77], [0.55, 0.66], [0.55, 0.43], [0.54, 0.1], [0.1, 0.5], ] ) model = BPNN() for i in (10, 20, 30, 2): model.add_layer(DenseLayer(i)) model.build() model.summary() model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01) if __name__ == "__main__": example()
--- +++ @@ -1,5 +1,22 @@ #!/usr/bin/python +""" + +A Framework of Back Propagation Neural Network (BP) model + +Easy to use: + * add many layers as you want ! ! ! + * clearly see how the loss decreasing +Easy to expand: + * more activation functions + * more loss functions + * more optimization method + +Author: Stephen Lee +Github : https://github.com/RiptideBo +Date: 2017.11.23 + +""" import numpy as np from matplotlib import pyplot as plt @@ -10,10 +27,20 @@ class DenseLayer: + """ + Layers of BP neural network + """ def __init__( self, units, activation=None, learning_rate=None, is_input_layer=False ): + """ + common connected layer of bp network + :param units: numbers of neural units + :param activation: activation function + :param learning_rate: learning rate for paras + :param is_input_layer: whether it is input layer or not + """ self.units = units self.weight = None self.bias = None @@ -70,6 +97,9 @@ class BPNN: + """ + Back Propagation Neural Network model + """ def __init__(self): self.layers = [] @@ -170,4 +200,4 @@ if __name__ == "__main__": - example()+ example()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/back_propagation_neural_network.py
Create docstrings for each class method
#!/usr/bin/env python3 from __future__ import annotations import random from collections.abc import Iterable class Clause: def __init__(self, literals: list[str]) -> None: # Assign all literals to None initially self.literals: dict[str, bool | None] = dict.fromkeys(literals) def __str__(self) -> str: return "{" + " , ".join(self.literals) + "}" def __len__(self) -> int: return len(self.literals) def assign(self, model: dict[str, bool | None]) -> None: for literal in self.literals: symbol = literal[:2] if symbol in model: value = model[symbol] else: continue # Complement assignment if literal is in complemented form if value is not None and literal.endswith("'"): value = not value self.literals[literal] = value def evaluate(self, model: dict[str, bool | None]) -> bool | None: for literal in self.literals: symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'" if symbol in self.literals: return True self.assign(model) for value in self.literals.values(): if value in (True, None): return value return any(self.literals.values()) class Formula: def __init__(self, clauses: Iterable[Clause]) -> None: self.clauses = list(clauses) def __str__(self) -> str: return "{" + " , ".join(str(clause) for clause in self.clauses) + "}" def generate_clause() -> Clause: literals = [] no_of_literals = random.randint(1, 5) base_var = "A" i = 0 while i < no_of_literals: var_no = random.randint(1, 5) var_name = base_var + str(var_no) var_complement = random.randint(0, 1) if var_complement == 1: var_name += "'" if var_name in literals: i -= 1 else: literals.append(var_name) i += 1 return Clause(literals) def generate_formula() -> Formula: clauses: set[Clause] = set() no_of_clauses = random.randint(1, 10) while len(clauses) < no_of_clauses: clauses.add(generate_clause()) return Formula(clauses) def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]: clauses = formula.clauses symbols_set = [] for clause in formula.clauses: for literal in clause.literals: symbol = literal[:2] if symbol not in symbols_set: symbols_set.append(symbol) return clauses, symbols_set def find_pure_symbols( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: pure_symbols = [] assignment: dict[str, bool | None] = {} literals = [] for clause in clauses: if clause.evaluate(model): continue for literal in clause.literals: literals.append(literal) for s in symbols: sym = s + "'" if (s in literals and sym not in literals) or ( s not in literals and sym in literals ): pure_symbols.append(s) for p in pure_symbols: assignment[p] = None for s in pure_symbols: sym = s + "'" if s in literals: assignment[s] = True elif sym in literals: assignment[s] = False return pure_symbols, assignment def find_unit_clauses( clauses: list[Clause], model: dict[str, bool | None], # noqa: ARG001 ) -> tuple[list[str], dict[str, bool | None]]: unit_symbols = [] for clause in clauses: if len(clause) == 1: unit_symbols.append(next(iter(clause.literals.keys()))) else: f_count, n_count = 0, 0 for literal, value in clause.literals.items(): if value is False: f_count += 1 elif value is None: sym = literal n_count += 1 if f_count == len(clause) - 1 and n_count == 1: unit_symbols.append(sym) assignment: dict[str, bool | None] = {} for i in unit_symbols: symbol = i[:2] assignment[symbol] = len(i) == 2 unit_symbols = [i[:2] for i in unit_symbols] return unit_symbols, assignment def dpll_algorithm( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[bool | None, dict[str, bool | None] | None]: check_clause_all_true = True for clause in clauses: clause_check = clause.evaluate(model) if clause_check is False: return False, None elif clause_check is None: check_clause_all_true = False continue if check_clause_all_true: return True, model try: pure_symbols, assignment = find_pure_symbols(clauses, symbols, model) except RecursionError: print("raises a RecursionError and is") return None, {} p = None if len(pure_symbols) > 0: p, value = pure_symbols[0], assignment[pure_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) unit_symbols, assignment = find_unit_clauses(clauses, model) p = None if len(unit_symbols) > 0: p, value = unit_symbols[0], assignment[unit_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) p = symbols[0] rest = symbols[1:] tmp1, tmp2 = model, model tmp1[p], tmp2[p] = True, False return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2) if __name__ == "__main__": import doctest doctest.testmod() formula = generate_formula() print(f"The formula {formula} is", end=" ") clauses, symbols = generate_parameters(formula) solution, model = dpll_algorithm(clauses, symbols, {}) if solution: print(f"satisfiable with the assignment {model}.") else: print("not satisfiable.")
--- +++ @@ -1,5 +1,13 @@ #!/usr/bin/env python3 +""" +Davis-Putnam-Logemann-Loveland (DPLL) algorithm is a complete, backtracking-based +search algorithm for deciding the satisfiability of propositional logic formulae in +conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability +(CNF-SAT) problem. + +For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm +""" from __future__ import annotations @@ -8,18 +16,52 @@ class Clause: + """ + | A clause represented in Conjunctive Normal Form. + | A clause is a set of literals, either complemented or otherwise. + + For example: + * {A1, A2, A3'} is the clause (A1 v A2 v A3') + * {A5', A2', A1} is the clause (A5' v A2' v A1) + + Create model + + >>> clause = Clause(["A1", "A2'", "A3"]) + >>> clause.evaluate({"A1": True}) + True + """ def __init__(self, literals: list[str]) -> None: + """ + Represent the literals and an assignment in a clause." + """ # Assign all literals to None initially self.literals: dict[str, bool | None] = dict.fromkeys(literals) def __str__(self) -> str: + """ + To print a clause as in Conjunctive Normal Form. + + >>> str(Clause(["A1", "A2'", "A3"])) + "{A1 , A2' , A3}" + """ return "{" + " , ".join(self.literals) + "}" def __len__(self) -> int: + """ + To print a clause as in Conjunctive Normal Form. + + >>> len(Clause([])) + 0 + >>> len(Clause(["A1", "A2'", "A3"])) + 3 + """ return len(self.literals) def assign(self, model: dict[str, bool | None]) -> None: + """ + Assign values to literals of the clause as given by model. + """ for literal in self.literals: symbol = literal[:2] if symbol in model: @@ -32,6 +74,16 @@ self.literals[literal] = value def evaluate(self, model: dict[str, bool | None]) -> bool | None: + """ + Evaluates the clause with the assignments in model. + + This has the following steps: + 1. Return ``True`` if both a literal and its complement exist in the clause. + 2. Return ``True`` if a single literal has the assignment ``True``. + 3. Return ``None`` (unable to complete evaluation) + if a literal has no assignment. + 4. Compute disjunction of all values assigned in clause. + """ for literal in self.literals: symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'" if symbol in self.literals: @@ -45,15 +97,34 @@ class Formula: + """ + | A formula represented in Conjunctive Normal Form. + | A formula is a set of clauses. + | For example, + | {{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1)) + """ def __init__(self, clauses: Iterable[Clause]) -> None: + """ + Represent the number of clauses and the clauses themselves. + """ self.clauses = list(clauses) def __str__(self) -> str: + """ + To print a formula as in Conjunctive Normal Form. + + >>> str(Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])) + "{{A1 , A2' , A3} , {A5' , A2' , A1}}" + """ return "{" + " , ".join(str(clause) for clause in self.clauses) + "}" def generate_clause() -> Clause: + """ + | Randomly generate a clause. + | All literals have the name Ax, where x is an integer from ``1`` to ``5``. + """ literals = [] no_of_literals = random.randint(1, 5) base_var = "A" @@ -73,6 +144,9 @@ def generate_formula() -> Formula: + """ + Randomly generate a formula. + """ clauses: set[Clause] = set() no_of_clauses = random.randint(1, 10) while len(clauses) < no_of_clauses: @@ -81,6 +155,22 @@ def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]: + """ + | Return the clauses and symbols from a formula. + | A symbol is the uncomplemented form of a literal. + + For example, + * Symbol of A3 is A3. + * Symbol of A5' is A5. + + >>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]) + >>> clauses, symbols = generate_parameters(formula) + >>> clauses_list = [str(i) for i in clauses] + >>> clauses_list + ["{A1 , A2' , A3}", "{A5' , A2' , A1}"] + >>> symbols + ['A1', 'A2', 'A3', 'A5'] + """ clauses = formula.clauses symbols_set = [] for clause in formula.clauses: @@ -94,6 +184,27 @@ def find_pure_symbols( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: + """ + | Return pure symbols and their values to satisfy clause. + | Pure symbols are symbols in a formula that exist only in one form, + | either complemented or otherwise. + | For example, + | {{A4 , A3 , A5' , A1 , A3'} , {A4} , {A3}} has pure symbols A4, A5' and A1. + + This has the following steps: + 1. Ignore clauses that have already evaluated to be ``True``. + 2. Find symbols that occur only in one form in the rest of the clauses. + 3. Assign value ``True`` or ``False`` depending on whether the symbols occurs + in normal or complemented form respectively. + + >>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]) + >>> clauses, symbols = generate_parameters(formula) + >>> pure_symbols, values = find_pure_symbols(clauses, symbols, {}) + >>> pure_symbols + ['A1', 'A2', 'A3', 'A5'] + >>> values + {'A1': True, 'A2': False, 'A3': True, 'A5': False} + """ pure_symbols = [] assignment: dict[str, bool | None] = {} literals = [] @@ -125,6 +236,29 @@ clauses: list[Clause], model: dict[str, bool | None], # noqa: ARG001 ) -> tuple[list[str], dict[str, bool | None]]: + """ + Returns the unit symbols and their values to satisfy clause. + + Unit symbols are symbols in a formula that are: + - Either the only symbol in a clause + - Or all other literals in that clause have been assigned ``False`` + + This has the following steps: + 1. Find symbols that are the only occurrences in a clause. + 2. Find symbols in a clause where all other literals are assigned ``False``. + 3. Assign ``True`` or ``False`` depending on whether the symbols occurs in + normal or complemented form respectively. + + >>> clause1 = Clause(["A4", "A3", "A5'", "A1", "A3'"]) + >>> clause2 = Clause(["A4"]) + >>> clause3 = Clause(["A3"]) + >>> clauses, symbols = generate_parameters(Formula([clause1, clause2, clause3])) + >>> unit_clauses, values = find_unit_clauses(clauses, {}) + >>> unit_clauses + ['A4', 'A3'] + >>> values + {'A4': True, 'A3': True} + """ unit_symbols = [] for clause in clauses: if len(clause) == 1: @@ -151,6 +285,23 @@ def dpll_algorithm( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[bool | None, dict[str, bool | None] | None]: + """ + Returns the model if the formula is satisfiable, else ``None`` + + This has the following steps: + 1. If every clause in clauses is ``True``, return ``True``. + 2. If some clause in clauses is ``False``, return ``False``. + 3. Find pure symbols. + 4. Find unit symbols. + + >>> formula = Formula([Clause(["A4", "A3", "A5'", "A1", "A3'"]), Clause(["A4"])]) + >>> clauses, symbols = generate_parameters(formula) + >>> soln, model = dpll_algorithm(clauses, symbols, {}) + >>> soln + True + >>> model + {'A4': True} + """ check_clause_all_true = True for clause in clauses: clause_check = clause.evaluate(model) @@ -213,4 +364,4 @@ if solution: print(f"satisfiable with the assignment {model}.") else: - print("not satisfiable.")+ print("not satisfiable.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/davis_putnam_logemann_loveland.py
Write docstrings describing each step
import math import random # Sigmoid def sigmoid_function(value: float, deriv: bool = False) -> float: if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value)) # Initial Value INITIAL_VALUE = 0.02 def forward_propagation(expected: int, number_propagations: int) -> float: # Random weight weight = float(2 * (random.randint(1, 100)) - 1) for _ in range(number_propagations): # Forward propagation layer_1 = sigmoid_function(INITIAL_VALUE * weight) # How much did we miss? layer_1_error = (expected / 100) - layer_1 # Error delta layer_1_delta = layer_1_error * sigmoid_function(layer_1, True) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_1 * 100 if __name__ == "__main__": import doctest doctest.testmod() expected = int(input("Expected value: ")) number_propagations = int(input("Number of propagations: ")) print(forward_propagation(expected, number_propagations))
--- +++ @@ -1,3 +1,7 @@+""" +Forward propagation explanation: +https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250 +""" import math import random @@ -5,6 +9,13 @@ # Sigmoid def sigmoid_function(value: float, deriv: bool = False) -> float: + """Return the sigmoid function of a float. + + >>> sigmoid_function(3.5) + 0.9706877692486436 + >>> sigmoid_function(3.5, True) + -8.75 + """ if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value)) @@ -15,6 +26,16 @@ def forward_propagation(expected: int, number_propagations: int) -> float: + """Return the value found after the forward propagation training. + + >>> res = forward_propagation(32, 450_000) # Was 10_000_000 + >>> res > 31 and res < 33 + True + + >>> res = forward_propagation(32, 1000) + >>> res > 31 and res < 33 + False + """ # Random weight weight = float(2 * (random.randint(1, 100)) - 1) @@ -39,4 +60,4 @@ expected = int(input("Expected value: ")) number_propagations = int(input("Number of propagations: ")) - print(forward_propagation(expected, number_propagations))+ print(forward_propagation(expected, number_propagations))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/simple_neural_network.py
Generate docstrings with examples
def h_index(citations: list[int]) -> int: # validate: if not isinstance(citations, list) or not all( isinstance(item, int) and item >= 0 for item in citations ): raise ValueError("The citations should be a list of non negative integers.") citations.sort() len_citations = len(citations) for i in range(len_citations): if citations[len_citations - 1 - i] <= i: return i return len_citations if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,53 @@+""" +Task: +Given an array of integers citations where citations[i] is the number of +citations a researcher received for their ith paper, return compute the +researcher's h-index. + +According to the definition of h-index on Wikipedia: A scientist has an +index h if h of their n papers have at least h citations each, and the other +n - h papers have no more than h citations each. + +If there are several possible values for h, the maximum one is taken as the +h-index. + +H-Index link: https://en.wikipedia.org/wiki/H-index + +Implementation notes: +Use sorting of array + +Leetcode link: https://leetcode.com/problems/h-index/description/ + +n = len(citations) +Runtime Complexity: O(n * log(n)) +Space Complexity: O(1) + +""" def h_index(citations: list[int]) -> int: + """ + Return H-index of citations + + >>> h_index([3, 0, 6, 1, 5]) + 3 + >>> h_index([1, 3, 1]) + 1 + >>> h_index([1, 2, 3]) + 2 + >>> h_index('test') + Traceback (most recent call last): + ... + ValueError: The citations should be a list of non negative integers. + >>> h_index([1,2,'3']) + Traceback (most recent call last): + ... + ValueError: The citations should be a list of non negative integers. + >>> h_index([1,2,-3]) + Traceback (most recent call last): + ... + ValueError: The citations should be a list of non negative integers. + """ # validate: if not isinstance(citations, list) or not all( @@ -21,4 +68,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/h_index.py
Add docstrings for production code
from __future__ import annotations import sys from collections import deque from typing import TypeVar T = TypeVar("T") class LRUCache[T]: dq_store: deque[T] # Cache store of keys key_reference: set[T] # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache def __init__(self, n: int) -> None: self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x) def display(self) -> None: for k in self.dq_store: print(k) def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}" if __name__ == "__main__": import doctest doctest.testmod() lru_cache: LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
--- +++ @@ -8,12 +8,36 @@ class LRUCache[T]: + """ + Page Replacement Algorithm, Least Recently Used (LRU) Caching. + + >>> lru_cache: LRUCache[str | int] = LRUCache(4) + >>> lru_cache.refer("A") + >>> lru_cache.refer(2) + >>> lru_cache.refer(3) + + >>> lru_cache + LRUCache(4) => [3, 2, 'A'] + + >>> lru_cache.refer("A") + >>> lru_cache + LRUCache(4) => ['A', 3, 2] + + >>> lru_cache.refer(4) + >>> lru_cache.refer(5) + >>> lru_cache + LRUCache(4) => [5, 4, 'A', 3] + + """ dq_store: deque[T] # Cache store of keys key_reference: set[T] # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache def __init__(self, n: int) -> None: + """Creates an empty store and map for the keys. + The LRUCache is set the size n. + """ self.dq_store = deque() self.key_reference = set() if not n: @@ -24,6 +48,11 @@ LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: + """ + Looks for a page in the cache store and adds reference to the set. + Remove the least recently used key if the store is full. + Update store to reflect recent access. + """ if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() @@ -35,6 +64,9 @@ self.key_reference.add(x) def display(self) -> None: + """ + Prints all the elements in the store. + """ for k in self.dq_store: print(k) @@ -57,4 +89,4 @@ lru_cache.display() print(lru_cache) - assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"+ assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/least_recently_used.py
Write docstrings for algorithm functions
"""Prints a maximum set of activities that can be done by a single person, one at a time""" # n --> Total number of activities # start[]--> An array that contains start time of all activities # finish[] --> An array that contains finish time of all activities def print_max_activities(start: list[int], finish: list[int]) -> None: n = len(finish) print("The following activities are selected:") # The first activity is always selected i = 0 print(i, end=",") # Consider rest of the activities for j in range(n): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(j, end=",") i = j if __name__ == "__main__": import doctest doctest.testmod() start = [1, 3, 0, 5, 8, 5] finish = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
--- +++ @@ -1,3 +1,5 @@+"""The following implementation assumes that the activities +are already sorted according to their finish time""" """Prints a maximum set of activities that can be done by a single person, one at a time""" @@ -7,6 +9,13 @@ def print_max_activities(start: list[int], finish: list[int]) -> None: + """ + >>> start = [1, 3, 0, 5, 8, 5] + >>> finish = [2, 4, 6, 7, 9, 9] + >>> print_max_activities(start, finish) + The following activities are selected: + 0,1,3,4, + """ n = len(finish) print("The following activities are selected:") @@ -31,4 +40,4 @@ start = [1, 3, 0, 5, 8, 5] finish = [2, 4, 6, 7, 9, 9] - print_max_activities(start, finish)+ print_max_activities(start, finish)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/activity_selection.py
Write docstrings that follow conventions
def temp_input_value( min_val: int = 10, max_val: int = 1000, option: bool = True ) -> int: assert ( isinstance(min_val, int) and isinstance(max_val, int) and isinstance(option, bool) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def get_avg(number_1: int, number_2: int) -> int: return int((number_1 + number_2) / 2) def guess_the_number(lower: int, higher: int, to_guess: int) -> None: assert ( isinstance(lower, int) and isinstance(higher, int) and isinstance(to_guess, int) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value" ) def answer(number: int) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") last_lowest = lower last_highest = higher last_numbers = [] while True: number = get_avg(last_lowest, last_highest) last_numbers.append(number) if answer(number) == "low": last_lowest = number elif answer(number) == "high": last_highest = number else: break print(f"guess the number : {last_numbers[-1]}") print(f"details : {last_numbers!s}") def main() -> None: lower = int(input("Enter lower value : ").strip()) higher = int(input("Enter high value : ").strip()) guess = int(input("Enter value to guess : ").strip()) guess_the_number(lower, higher, guess) if __name__ == "__main__": main()
--- +++ @@ -1,8 +1,49 @@+""" +guess the number using lower,higher and the value to find or guess + +solution works by dividing lower and higher of number guessed + +suppose lower is 0, higher is 1000 and the number to guess is 355 + +>>> guess_the_number(10, 1000, 17) +started... +guess the number : 17 +details : [505, 257, 133, 71, 40, 25, 17] + +""" def temp_input_value( min_val: int = 10, max_val: int = 1000, option: bool = True ) -> int: + """ + Temporary input values for tests + + >>> temp_input_value(option=True) + 10 + + >>> temp_input_value(option=False) + 1000 + + >>> temp_input_value(min_val=100, option=True) + 100 + + >>> temp_input_value(min_val=100, max_val=50) + Traceback (most recent call last): + ... + ValueError: Invalid value for min_val or max_val (min_value < max_value) + + >>> temp_input_value("ten","fifty",1) + Traceback (most recent call last): + ... + AssertionError: Invalid type of value(s) specified to function! + + >>> temp_input_value(min_val=-100, max_val=500) + -100 + + >>> temp_input_value(min_val=-5100, max_val=-100) + -5100 + """ assert ( isinstance(min_val, int) and isinstance(max_val, int) @@ -15,10 +56,56 @@ def get_avg(number_1: int, number_2: int) -> int: + """ + Return the mid-number(whole) of two integers a and b + + >>> get_avg(10, 15) + 12 + + >>> get_avg(20, 300) + 160 + + >>> get_avg("abcd", 300) + Traceback (most recent call last): + ... + TypeError: can only concatenate str (not "int") to str + + >>> get_avg(10.5,50.25) + 30 + """ return int((number_1 + number_2) / 2) def guess_the_number(lower: int, higher: int, to_guess: int) -> None: + """ + The `guess_the_number` function that guess the number by some operations + and using inner functions + + >>> guess_the_number(10, 1000, 17) + started... + guess the number : 17 + details : [505, 257, 133, 71, 40, 25, 17] + + >>> guess_the_number(-10000, 10000, 7) + started... + guess the number : 7 + details : [0, 5000, 2500, 1250, 625, 312, 156, 78, 39, 19, 9, 4, 6, 7] + + >>> guess_the_number(10, 1000, "a") + Traceback (most recent call last): + ... + AssertionError: argument values must be type of "int" + + >>> guess_the_number(10, 1000, 5) + Traceback (most recent call last): + ... + ValueError: guess value must be within the range of lower and higher value + + >>> guess_the_number(10000, 100, 5) + Traceback (most recent call last): + ... + ValueError: argument value for lower and higher must be(lower > higher) + """ assert ( isinstance(lower, int) and isinstance(higher, int) and isinstance(to_guess, int) ), 'argument values must be type of "int"' @@ -32,6 +119,9 @@ ) def answer(number: int) -> str: + """ + Returns value by comparing with entered `to_guess` number + """ if number > to_guess: return "high" elif number < to_guess: @@ -62,6 +152,9 @@ def main() -> None: + """ + starting point or function of script + """ lower = int(input("Enter lower value : ").strip()) higher = int(input("Enter high value : ").strip()) guess = int(input("Enter value to guess : ").strip()) @@ -69,4 +162,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/guess_the_number_search.py
Improve my code by adding docstrings
from __future__ import annotations from collections.abc import Callable from typing import TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode[T, U]: def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.freq: int = 0 self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return ( f"Node: key: {self.key}, val: {self.val}, freq: {self.freq}, " f"has next: {self.next is not None}, has prev: {self.prev is not None}" ) class DoubleLinkedList[T, U]: def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear node.freq += 1 self._position_node(node) def _position_node(self, node: DoubleLinkedListNode[T, U]) -> None: while node.prev is not None and node.prev.freq > node.freq: # swap node with previous node previous_node = node.prev node.prev = previous_node.prev previous_node.next = node.prev node.next = previous_node previous_node.prev = node def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LFUCache[T, U]: def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current_size={self.num_keys})" ) def __contains__(self, key: T) -> bool: return key in self.cache def get(self, key: T) -> U | None: if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def put(self, key: T, value: U) -> None: if key not in self.cache: if self.num_keys >= self.capacity: # delete first node when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert self.list.remove(first_node) is not None # first_node guaranteed to be in list del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls: type[LFUCache[T, U]], size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: # variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[ Callable[[T], U], LFUCache[T, U] ] = {} def cache_decorator_wrapper(*args: T) -> U: if func not in decorator_function_to_instance_map: decorator_function_to_instance_map[func] = LFUCache(size) result = decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) decorator_function_to_instance_map[func].put(args[0], result) return result def cache_info() -> LFUCache[T, U]: return decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -8,6 +8,13 @@ class DoubleLinkedListNode[T, U]: + """ + Double Linked List Node built specifically for LFU Cache + + >>> node = DoubleLinkedListNode(1,1) + >>> node + Node: key: 1, val: 1, freq: 0, has next: False, has prev: False + """ def __init__(self, key: T | None, val: U | None): self.key = key @@ -24,6 +31,71 @@ class DoubleLinkedList[T, U]: + """ + Double Linked List built specifically for LFU Cache + + >>> dll: DoubleLinkedList = DoubleLinkedList() + >>> dll + DoubleLinkedList, + Node: key: None, val: None, freq: 0, has next: True, has prev: False, + Node: key: None, val: None, freq: 0, has next: False, has prev: True + + >>> first_node = DoubleLinkedListNode(1,10) + >>> first_node + Node: key: 1, val: 10, freq: 0, has next: False, has prev: False + + + >>> dll.add(first_node) + >>> dll + DoubleLinkedList, + Node: key: None, val: None, freq: 0, has next: True, has prev: False, + Node: key: 1, val: 10, freq: 1, has next: True, has prev: True, + Node: key: None, val: None, freq: 0, has next: False, has prev: True + + >>> # node is mutated + >>> first_node + Node: key: 1, val: 10, freq: 1, has next: True, has prev: True + + >>> second_node = DoubleLinkedListNode(2,20) + >>> second_node + Node: key: 2, val: 20, freq: 0, has next: False, has prev: False + + >>> dll.add(second_node) + >>> dll + DoubleLinkedList, + Node: key: None, val: None, freq: 0, has next: True, has prev: False, + Node: key: 1, val: 10, freq: 1, has next: True, has prev: True, + Node: key: 2, val: 20, freq: 1, has next: True, has prev: True, + Node: key: None, val: None, freq: 0, has next: False, has prev: True + + >>> removed_node = dll.remove(first_node) + >>> assert removed_node == first_node + >>> dll + DoubleLinkedList, + Node: key: None, val: None, freq: 0, has next: True, has prev: False, + Node: key: 2, val: 20, freq: 1, has next: True, has prev: True, + Node: key: None, val: None, freq: 0, has next: False, has prev: True + + + >>> # Attempt to remove node not on list + >>> removed_node = dll.remove(first_node) + >>> removed_node is None + True + + >>> # Attempt to remove head or rear + >>> dll.head + Node: key: None, val: None, freq: 0, has next: True, has prev: False + >>> dll.remove(dll.head) is None + True + + >>> # Attempt to remove head or rear + >>> dll.rear + Node: key: None, val: None, freq: 0, has next: False, has prev: True + >>> dll.remove(dll.rear) is None + True + + + """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) @@ -40,6 +112,9 @@ return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: + """ + Adds the given node at the tail of the list and shifting it to proper position + """ previous = self.rear.prev @@ -54,6 +129,9 @@ self._position_node(node) def _position_node(self, node: DoubleLinkedListNode[T, U]) -> None: + """ + Moves node forward to maintain invariant of sort by freq value + """ while node.prev is not None and node.prev.freq > node.freq: # swap node with previous node @@ -67,6 +145,11 @@ def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: + """ + Removes and returns the given node from the list + + Returns None if node.prev or node.next is None + """ if node.prev is None or node.next is None: return None @@ -79,6 +162,39 @@ class LFUCache[T, U]: + """ + LFU Cache to store a given capacity of data. Can be used as a stand-alone object + or as a function decorator. + + >>> cache = LFUCache(2) + >>> cache.put(1, 1) + >>> cache.put(2, 2) + >>> cache.get(1) + 1 + >>> cache.put(3, 3) + >>> cache.get(2) is None + True + >>> cache.put(4, 4) + >>> cache.get(1) is None + True + >>> cache.get(3) + 3 + >>> cache.get(4) + 4 + >>> cache + CacheInfo(hits=3, misses=2, capacity=2, current_size=2) + >>> @LFUCache.decorator(100) + ... def fib(num): + ... if num in (1, 2): + ... return 1 + ... return fib(num - 1) + fib(num - 2) + + >>> for i in range(1, 101): + ... res = fib(i) + + >>> fib.cache_info() + CacheInfo(hits=196, misses=100, capacity=100, current_size=100) + """ def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() @@ -89,6 +205,10 @@ self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: + """ + Return the details for the cache instance + [hits, misses, capacity, current_size] + """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " @@ -96,10 +216,24 @@ ) def __contains__(self, key: T) -> bool: + """ + >>> cache = LFUCache(1) + + >>> 1 in cache + False + + >>> cache.put(1, 1) + >>> 1 in cache + True + """ return key in self.cache def get(self, key: T) -> U | None: + """ + Returns the value for the input key and updates the Double Linked List. Returns + Returns None if key is not present in cache + """ if key in self.cache: self.hits += 1 @@ -115,6 +249,9 @@ return None def put(self, key: T, value: U) -> None: + """ + Sets the value for the input key and updates the Double Linked List + """ if key not in self.cache: if self.num_keys >= self.capacity: @@ -144,6 +281,11 @@ def decorator( cls: type[LFUCache[T, U]], size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: + """ + Decorator version of LFU Cache + + Decorated function must be function of T -> U + """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: # variable to map the decorator functions to their respective instance @@ -174,4 +316,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/lfu_cache.py
Add docstrings to meet PEP guidelines
from __future__ import annotations from collections.abc import Callable from typing import TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode[T, U]: def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return ( f"Node: key: {self.key}, val: {self.val}, " f"has next: {bool(self.next)}, has prev: {bool(self.prev)}" ) class DoubleLinkedList[T, U]: def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LRUCache[T, U]: def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" ) def __contains__(self, key: T) -> bool: return key in self.cache def get(self, key: T) -> U | None: # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def put(self, key: T, value: U) -> None: if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(first_node) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: # bump node to the end of the list, update value node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls, size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: # variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[ Callable[[T], U], LRUCache[T, U] ] = {} def cache_decorator_wrapper(*args: T) -> U: if func not in decorator_function_to_instance_map: decorator_function_to_instance_map[func] = LRUCache(size) result = decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) decorator_function_to_instance_map[func].put(args[0], result) return result def cache_info() -> LRUCache[T, U]: return decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -8,6 +8,12 @@ class DoubleLinkedListNode[T, U]: + """ + Double Linked List Node built specifically for LRU Cache + + >>> DoubleLinkedListNode(1,1) + Node: key: 1, val: 1, has next: False, has prev: False + """ def __init__(self, key: T | None, val: U | None): self.key = key @@ -23,6 +29,71 @@ class DoubleLinkedList[T, U]: + """ + Double Linked List built specifically for LRU Cache + + >>> dll: DoubleLinkedList = DoubleLinkedList() + >>> dll + DoubleLinkedList, + Node: key: None, val: None, has next: True, has prev: False, + Node: key: None, val: None, has next: False, has prev: True + + >>> first_node = DoubleLinkedListNode(1,10) + >>> first_node + Node: key: 1, val: 10, has next: False, has prev: False + + + >>> dll.add(first_node) + >>> dll + DoubleLinkedList, + Node: key: None, val: None, has next: True, has prev: False, + Node: key: 1, val: 10, has next: True, has prev: True, + Node: key: None, val: None, has next: False, has prev: True + + >>> # node is mutated + >>> first_node + Node: key: 1, val: 10, has next: True, has prev: True + + >>> second_node = DoubleLinkedListNode(2,20) + >>> second_node + Node: key: 2, val: 20, has next: False, has prev: False + + >>> dll.add(second_node) + >>> dll + DoubleLinkedList, + Node: key: None, val: None, has next: True, has prev: False, + Node: key: 1, val: 10, has next: True, has prev: True, + Node: key: 2, val: 20, has next: True, has prev: True, + Node: key: None, val: None, has next: False, has prev: True + + >>> removed_node = dll.remove(first_node) + >>> assert removed_node == first_node + >>> dll + DoubleLinkedList, + Node: key: None, val: None, has next: True, has prev: False, + Node: key: 2, val: 20, has next: True, has prev: True, + Node: key: None, val: None, has next: False, has prev: True + + + >>> # Attempt to remove node not on list + >>> removed_node = dll.remove(first_node) + >>> removed_node is None + True + + >>> # Attempt to remove head or rear + >>> dll.head + Node: key: None, val: None, has next: True, has prev: False + >>> dll.remove(dll.head) is None + True + + >>> # Attempt to remove head or rear + >>> dll.rear + Node: key: None, val: None, has next: False, has prev: True + >>> dll.remove(dll.rear) is None + True + + + """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) @@ -39,6 +110,9 @@ return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: + """ + Adds the given node to the end of the list (before rear) + """ previous = self.rear.prev @@ -53,6 +127,11 @@ def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: + """ + Removes and returns the given node from the list + + Returns None if node.prev or node.next is None + """ if node.prev is None or node.next is None: return None @@ -65,6 +144,70 @@ class LRUCache[T, U]: + """ + LRU Cache to store a given capacity of data. Can be used as a stand-alone object + or as a function decorator. + + >>> cache = LRUCache(2) + + >>> cache.put(1, 1) + >>> cache.put(2, 2) + >>> cache.get(1) + 1 + + >>> cache.list + DoubleLinkedList, + Node: key: None, val: None, has next: True, has prev: False, + Node: key: 2, val: 2, has next: True, has prev: True, + Node: key: 1, val: 1, has next: True, has prev: True, + Node: key: None, val: None, has next: False, has prev: True + + >>> cache.cache # doctest: +NORMALIZE_WHITESPACE + {1: Node: key: 1, val: 1, has next: True, has prev: True, \ + 2: Node: key: 2, val: 2, has next: True, has prev: True} + + >>> cache.put(3, 3) + + >>> cache.list + DoubleLinkedList, + Node: key: None, val: None, has next: True, has prev: False, + Node: key: 1, val: 1, has next: True, has prev: True, + Node: key: 3, val: 3, has next: True, has prev: True, + Node: key: None, val: None, has next: False, has prev: True + + >>> cache.cache # doctest: +NORMALIZE_WHITESPACE + {1: Node: key: 1, val: 1, has next: True, has prev: True, \ + 3: Node: key: 3, val: 3, has next: True, has prev: True} + + >>> cache.get(2) is None + True + + >>> cache.put(4, 4) + + >>> cache.get(1) is None + True + + >>> cache.get(3) + 3 + + >>> cache.get(4) + 4 + + >>> cache + CacheInfo(hits=3, misses=2, capacity=2, current size=2) + + >>> @LRUCache.decorator(100) + ... def fib(num): + ... if num in (1, 2): + ... return 1 + ... return fib(num - 1) + fib(num - 2) + + >>> for i in range(1, 100): + ... res = fib(i) + + >>> fib.cache_info() + CacheInfo(hits=194, misses=99, capacity=100, current size=99) + """ def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() @@ -75,6 +218,10 @@ self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: + """ + Return the details for the cache instance + [hits, misses, capacity, current_size] + """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " @@ -82,10 +229,25 @@ ) def __contains__(self, key: T) -> bool: + """ + >>> cache = LRUCache(1) + + >>> 1 in cache + False + + >>> cache.put(1, 1) + + >>> 1 in cache + True + """ return key in self.cache def get(self, key: T) -> U | None: + """ + Returns the value for the input key and updates the Double Linked List. + Returns None if key is not present in cache + """ # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: @@ -102,6 +264,9 @@ return None def put(self, key: T, value: U) -> None: + """ + Sets the value for the input key and updates the Double Linked List + """ if key not in self.cache: if self.num_keys >= self.capacity: @@ -133,6 +298,11 @@ def decorator( cls, size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: + """ + Decorator version of LRU Cache + + Decorated function must be function of T -> U + """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: # variable to map the decorator functions to their respective instance @@ -163,4 +333,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/lru_cache.py
Add detailed documentation for each class
from collections import Counter def majority_vote(votes: list[int], votes_needed_to_win: int) -> list[int]: majority_candidate_counter: Counter[int] = Counter() for vote in votes: majority_candidate_counter[vote] += 1 if len(majority_candidate_counter) == votes_needed_to_win: majority_candidate_counter -= Counter(set(majority_candidate_counter)) majority_candidate_counter = Counter( vote for vote in votes if vote in majority_candidate_counter ) return [ vote for vote in majority_candidate_counter if majority_candidate_counter[vote] > len(votes) / votes_needed_to_win ] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,22 @@+""" +This is Booyer-Moore Majority Vote Algorithm. The problem statement goes like this: +Given an integer array of size n, find all elements that appear more than ⌊ n/k ⌋ times. +We have to solve in O(n) time and O(1) Space. +URL : https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm +""" from collections import Counter def majority_vote(votes: list[int], votes_needed_to_win: int) -> list[int]: + """ + >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 3) + [2] + >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 2) + [] + >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 4) + [1, 2, 3] + """ majority_candidate_counter: Counter[int] = Counter() for vote in votes: majority_candidate_counter[vote] += 1 @@ -21,4 +35,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/majority_vote_algorithm.py
Add docstrings to clarify complex logic
def is_balanced(s: str) -> bool: open_to_closed = {"{": "}", "[": "]", "(": ")"} stack = [] for symbol in s: if symbol in open_to_closed: stack.append(symbol) elif symbol in open_to_closed.values() and ( not stack or open_to_closed[stack.pop()] != symbol ): return False return not stack # stack should be empty def main(): s = input("Enter sequence of brackets: ") print(f"'{s}' is {'' if is_balanced(s) else 'not '}balanced.") if __name__ == "__main__": from doctest import testmod testmod() main()
--- +++ @@ -1,6 +1,54 @@+""" +The nested brackets problem is a problem that determines if a sequence of +brackets are properly nested. A sequence of brackets s is considered properly nested +if any of the following conditions are true: + + - s is empty + - s has the form (U) or [U] or {U} where U is a properly nested string + - s has the form VW where V and W are properly nested strings + +For example, the string "()()[()]" is properly nested but "[(()]" is not. + +The function called is_balanced takes as input a string S which is a sequence of +brackets and returns true if S is nested and false otherwise. +""" def is_balanced(s: str) -> bool: + """ + >>> is_balanced("") + True + >>> is_balanced("()") + True + >>> is_balanced("[]") + True + >>> is_balanced("{}") + True + >>> is_balanced("()[]{}") + True + >>> is_balanced("(())") + True + >>> is_balanced("[[") + False + >>> is_balanced("([{}])") + True + >>> is_balanced("(()[)]") + False + >>> is_balanced("([)]") + False + >>> is_balanced("[[()]]") + True + >>> is_balanced("(()(()))") + True + >>> is_balanced("]") + False + >>> is_balanced("Life is a bowl of cherries.") + True + >>> is_balanced("Life is a bowl of che{}ies.") + True + >>> is_balanced("Life is a bowl of che}{ies.") + False + """ open_to_closed = {"{": "}", "[": "]", "(": ")"} stack = [] for symbol in s: @@ -22,4 +70,4 @@ from doctest import testmod testmod() - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/nested_brackets.py
Fill in missing docstrings in my code
__author__ = "Tobias Carryer" from time import time class LinearCongruentialGenerator: # The default value for **seed** is the result of a function call, which is not # normally recommended and causes ruff to raise a B008 error. However, in this case, # it is acceptable because `LinearCongruentialGenerator.__init__()` will only be # called once per instance and it ensures that each instance will generate a unique # sequence of numbers. def __init__(self, multiplier, increment, modulo, seed=int(time())): # noqa: B008 self.multiplier = multiplier self.increment = increment self.modulo = modulo self.seed = seed def next_number(self): self.seed = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. lcg = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31) while True: print(lcg.next_number())
--- +++ @@ -4,6 +4,9 @@ class LinearCongruentialGenerator: + """ + A pseudorandom number generator. + """ # The default value for **seed** is the result of a function call, which is not # normally recommended and causes ruff to raise a B008 error. However, in this case, @@ -12,12 +15,23 @@ # sequence of numbers. def __init__(self, multiplier, increment, modulo, seed=int(time())): # noqa: B008 + """ + These parameters are saved and used when nextNumber() is called. + + modulo is the largest number that can be generated (exclusive). The most + efficient values are powers of 2. 2^32 is a common value. + """ self.multiplier = multiplier self.increment = increment self.modulo = modulo self.seed = seed def next_number(self): + """ + The smallest number that can be generated is zero. + The largest number that can be generated is modulo-1. modulo is set in the + constructor. + """ self.seed = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed @@ -26,4 +40,4 @@ # Show the LCG in action. lcg = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31) while True: - print(lcg.next_number())+ print(lcg.next_number())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/linear_congruential_generator.py
Improve my code by adding docstrings
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley (bluedistro@github.io), bineykingsley36@gmail.com", # "Date": 28-10-2018 # } from __future__ import annotations import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -4,6 +4,17 @@ # "Author: "Biney Kingsley (bluedistro@github.io), bineykingsley36@gmail.com", # "Date": 28-10-2018 # } +""" +The Banker's algorithm is a resource allocation and deadlock avoidance algorithm +developed by Edsger Dijkstra that tests for safety by simulating the allocation of +predetermined maximum possible amounts of all resources, and then makes a "s-state" +check to test for possible deadlock conditions for all other pending activities, +before deciding whether allocation should be allowed to continue. + +| [Source] Wikipedia +| [Credit] Rosetta Code C implementation helped very much. +| (https://rosettacode.org/wiki/Banker%27s_algorithm) +""" from __future__ import annotations @@ -33,31 +44,116 @@ allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: + """ + :param claim_vector: A nxn/nxm list depicting the amount of each resources + (eg. memory, interface, semaphores, etc.) available. + :param allocated_resources_table: A nxn/nxm list depicting the amount of each + resource each process is currently holding + :param maximum_claim_table: A nxn/nxm list depicting how much of each resource + the system currently has available + """ self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: + """ + Check for allocated resources in line with each resource in the claim vector + """ return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: + """ + Check for available resources in line with each resource in the claim vector + """ return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: + """ + Implement safety checker that calculates the needs by ensuring that + ``max_claim[i][j] - alloc_table[i][j] <= avail[j]`` + """ return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: + """ + This function builds an index control dictionary to track original ids/indices + of processes when altered during execution of method "main" + + :Return: {0: [a: int, b: int], 1: [c: int, d: int]} + + >>> index_control = BankersAlgorithm( + ... test_claim_vector, test_allocated_res_table, test_maximum_claim_table + ... )._BankersAlgorithm__need_index_manager() + >>> {key: [int(x) for x in value] for key, value + ... in index_control.items()} # doctest: +NORMALIZE_WHITESPACE + {0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0], + 4: [2, 0, 0, 3]} + """ return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: + """ + Utilize various methods in this class to simulate the Banker's algorithm + :Return: None + + >>> BankersAlgorithm(test_claim_vector, test_allocated_res_table, + ... test_maximum_claim_table).main(describe=True) + Allocated Resource Table + P1 2 0 1 1 + <BLANKLINE> + P2 0 1 2 1 + <BLANKLINE> + P3 4 0 0 3 + <BLANKLINE> + P4 0 2 1 0 + <BLANKLINE> + P5 1 0 3 0 + <BLANKLINE> + System Resource Table + P1 3 2 1 4 + <BLANKLINE> + P2 0 2 5 2 + <BLANKLINE> + P3 5 1 0 5 + <BLANKLINE> + P4 1 5 3 0 + <BLANKLINE> + P5 3 0 3 3 + <BLANKLINE> + Current Usage by Active Processes: 8 5 9 7 + Initial Available Resources: 1 2 2 2 + __________________________________________________ + <BLANKLINE> + Process 3 is executing. + Updated available resource stack for processes: 5 2 2 5 + The process is in a safe state. + <BLANKLINE> + Process 1 is executing. + Updated available resource stack for processes: 7 2 3 6 + The process is in a safe state. + <BLANKLINE> + Process 2 is executing. + Updated available resource stack for processes: 7 3 5 7 + The process is in a safe state. + <BLANKLINE> + Process 4 is executing. + Updated available resource stack for processes: 7 5 6 7 + The process is in a safe state. + <BLANKLINE> + Process 5 is executing. + Updated available resource stack for processes: 8 5 9 7 + The process is in a safe state. + <BLANKLINE> + """ need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() @@ -99,6 +195,9 @@ break def __pretty_data(self): + """ + Properly align display of the algorithm's solution + """ print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( @@ -126,4 +225,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/bankers_algorithm.py
Document my Python code with docstrings
def get_data(source_data: list[list[float]]) -> list[list[float]]: data_lists: list[list[float]] = [] for data in source_data: for i, el in enumerate(data): if len(data_lists) < i + 1: data_lists.append([]) data_lists[i].append(float(el)) return data_lists def calculate_each_score( data_lists: list[list[float]], weights: list[int] ) -> list[list[float]]: score_lists: list[list[float]] = [] for dlist, weight in zip(data_lists, weights): mind = min(dlist) maxd = max(dlist) score: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind))) except ZeroDivisionError: score.append(1) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind)) except ZeroDivisionError: score.append(0) # weight not 0 or 1 else: msg = f"Invalid weight of {weight:f} provided" raise ValueError(msg) score_lists.append(score) return score_lists def generate_final_scores(score_lists: list[list[float]]) -> list[float]: # initialize final scores final_scores: list[float] = [0 for i in range(len(score_lists[0]))] for slist in score_lists: for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele return final_scores def procentual_proximity( source_data: list[list[float]], weights: list[int] ) -> list[list[float]]: data_lists = get_data(source_data) score_lists = calculate_each_score(data_lists, weights) final_scores = generate_final_scores(score_lists) # append scores to source data for i, ele in enumerate(final_scores): source_data[i].append(ele) return source_data
--- +++ @@ -1,6 +1,34 @@+""" +| developed by: markmelnic +| original repo: https://github.com/markmelnic/Scoring-Algorithm + +Analyse data using a range based percentual proximity algorithm +and calculate the linear maximum likelihood estimation. +The basic principle is that all values supplied will be broken +down to a range from ``0`` to ``1`` and each column's score will be added +up to get the total score. + +Example for data of vehicles +:: + + price|mileage|registration_year + 20k |60k |2012 + 22k |50k |2011 + 23k |90k |2015 + 16k |210k |2010 + +We want the vehicle with the lowest price, +lowest mileage but newest registration year. +Thus the weights for each column are as follows: +``[0, 0, 1]`` +""" def get_data(source_data: list[list[float]]) -> list[list[float]]: + """ + >>> get_data([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]]) + [[20.0, 23.0, 22.0], [60.0, 90.0, 50.0], [2012.0, 2015.0, 2011.0]] + """ data_lists: list[list[float]] = [] for data in source_data: for i, el in enumerate(data): @@ -13,6 +41,11 @@ def calculate_each_score( data_lists: list[list[float]], weights: list[int] ) -> list[list[float]]: + """ + >>> calculate_each_score([[20, 23, 22], [60, 90, 50], [2012, 2015, 2011]], + ... [0, 0, 1]) + [[1.0, 0.0, 0.33333333333333337], [0.75, 0.0, 1.0], [0.25, 1.0, 0.0]] + """ score_lists: list[list[float]] = [] for dlist, weight in zip(data_lists, weights): mind = min(dlist) @@ -45,6 +78,12 @@ def generate_final_scores(score_lists: list[list[float]]) -> list[float]: + """ + >>> generate_final_scores([[1.0, 0.0, 0.33333333333333337], + ... [0.75, 0.0, 1.0], + ... [0.25, 1.0, 0.0]]) + [2.0, 1.0, 1.3333333333333335] + """ # initialize final scores final_scores: list[float] = [0 for i in range(len(score_lists[0]))] @@ -58,6 +97,16 @@ def procentual_proximity( source_data: list[list[float]], weights: list[int] ) -> list[list[float]]: + """ + | `weights` - ``int`` list + | possible values - ``0`` / ``1`` + + * ``0`` if lower values have higher weight in the data set + * ``1`` if higher values have higher weight in the data set + + >>> procentual_proximity([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]], [0, 0, 1]) + [[20, 60, 2012, 2.0], [23, 90, 2015, 1.0], [22, 50, 2011, 1.3333333333333335]] + """ data_lists = get_data(source_data) score_lists = calculate_each_score(data_lists, weights) @@ -67,4 +116,4 @@ for i, ele in enumerate(final_scores): source_data[i].append(ele) - return source_data+ return source_data
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/scoring_algorithm.py
Create docstrings for each class method
class NumberContainer: def __init__(self) -> None: # numbermap keys are the number and its values are lists of indexes sorted # in ascending order self.numbermap: dict[int, list[int]] = {} # indexmap keys are an index and it's values are the number at that index self.indexmap: dict[int, int] = {} def binary_search_delete(self, array: list | str | range, item: int) -> list[int]: if isinstance(array, (range, str)): array = list(array) elif not isinstance(array, list): raise TypeError( "binary_search_delete() only accepts either a list, range or str" ) low = 0 high = len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == item: array.pop(mid) return array elif array[mid] < item: low = mid + 1 else: high = mid - 1 raise ValueError( "Either the item is not in the array or the array was unsorted" ) def binary_search_insert(self, array: list | str | range, index: int) -> list[int]: if isinstance(array, (range, str)): array = list(array) elif not isinstance(array, list): raise TypeError( "binary_search_insert() only accepts either a list, range or str" ) low = 0 high = len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == index: # If the item already exists in the array, # insert it after the existing item array.insert(mid + 1, index) return array elif array[mid] < index: low = mid + 1 else: high = mid - 1 # If the item doesn't exist in the array, insert it at the appropriate position array.insert(low, index) return array def change(self, index: int, number: int) -> None: # Remove previous index if index in self.indexmap: n = self.indexmap[index] if len(self.numbermap[n]) == 1: del self.numbermap[n] else: self.numbermap[n] = self.binary_search_delete(self.numbermap[n], index) # Set new index self.indexmap[index] = number # Number not seen before or empty so insert number value if number not in self.numbermap: self.numbermap[number] = [index] # Here we need to perform a binary search insertion in order to insert # The item in the correct place else: self.numbermap[number] = self.binary_search_insert( self.numbermap[number], index ) def find(self, number: int) -> int: # Simply return the 0th index (smallest) of the indexes found (or -1) return self.numbermap.get(number, [-1])[0] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,12 @@+""" +A number container system that uses binary search to delete and insert values into +arrays with O(log n) write times and O(1) read times. + +This container system holds integers at indexes. + +Further explained in this leetcode problem +> https://leetcode.com/problems/minimum-cost-tree-from-leaf-values +""" class NumberContainer: @@ -9,6 +18,39 @@ self.indexmap: dict[int, int] = {} def binary_search_delete(self, array: list | str | range, item: int) -> list[int]: + """ + Removes the item from the sorted array and returns + the new array. + + >>> NumberContainer().binary_search_delete([1,2,3], 2) + [1, 3] + >>> NumberContainer().binary_search_delete([0, 0, 0], 0) + [0, 0] + >>> NumberContainer().binary_search_delete([-1, -1, -1], -1) + [-1, -1] + >>> NumberContainer().binary_search_delete([-1, 0], 0) + [-1] + >>> NumberContainer().binary_search_delete([-1, 0], -1) + [0] + >>> NumberContainer().binary_search_delete(range(7), 3) + [0, 1, 2, 4, 5, 6] + >>> NumberContainer().binary_search_delete([1.1, 2.2, 3.3], 2.2) + [1.1, 3.3] + >>> NumberContainer().binary_search_delete("abcde", "c") + ['a', 'b', 'd', 'e'] + >>> NumberContainer().binary_search_delete([0, -1, 2, 4], 0) + Traceback (most recent call last): + ... + ValueError: Either the item is not in the array or the array was unsorted + >>> NumberContainer().binary_search_delete([2, 0, 4, -1, 11], -1) + Traceback (most recent call last): + ... + ValueError: Either the item is not in the array or the array was unsorted + >>> NumberContainer().binary_search_delete(125, 1) + Traceback (most recent call last): + ... + TypeError: binary_search_delete() only accepts either a list, range or str + """ if isinstance(array, (range, str)): array = list(array) elif not isinstance(array, list): @@ -33,6 +75,27 @@ ) def binary_search_insert(self, array: list | str | range, index: int) -> list[int]: + """ + Inserts the index into the sorted array + at the correct position. + + >>> NumberContainer().binary_search_insert([1,2,3], 2) + [1, 2, 2, 3] + >>> NumberContainer().binary_search_insert([0,1,3], 2) + [0, 1, 2, 3] + >>> NumberContainer().binary_search_insert([-5, -3, 0, 0, 11, 103], 51) + [-5, -3, 0, 0, 11, 51, 103] + >>> NumberContainer().binary_search_insert([-5, -3, 0, 0, 11, 100, 103], 101) + [-5, -3, 0, 0, 11, 100, 101, 103] + >>> NumberContainer().binary_search_insert(range(10), 4) + [0, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9] + >>> NumberContainer().binary_search_insert("abd", "c") + ['a', 'b', 'c', 'd'] + >>> NumberContainer().binary_search_insert(131, 23) + Traceback (most recent call last): + ... + TypeError: binary_search_insert() only accepts either a list, range or str + """ if isinstance(array, (range, str)): array = list(array) elif not isinstance(array, list): @@ -60,6 +123,15 @@ return array def change(self, index: int, number: int) -> None: + """ + Changes (sets) the index as number + + >>> cont = NumberContainer() + >>> cont.change(0, 10) + >>> cont.change(0, 20) + >>> cont.change(-13, 20) + >>> cont.change(-100030, 20032903290) + """ # Remove previous index if index in self.indexmap: n = self.indexmap[index] @@ -83,6 +155,21 @@ ) def find(self, number: int) -> int: + """ + Returns the smallest index where the number is. + + >>> cont = NumberContainer() + >>> cont.find(10) + -1 + >>> cont.change(0, 10) + >>> cont.find(10) + 0 + >>> cont.change(0, 20) + >>> cont.find(10) + -1 + >>> cont.find(20) + 0 + """ # Simply return the 0th index (smallest) of the indexes found (or -1) return self.numbermap.get(number, [-1])[0] @@ -90,4 +177,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/number_container_system.py
Add standardized docstrings across the file
def apply_table(inp, table): res = "" for i in table: res += inp[i - 1] return res def left_shift(data): return data[1:] + data[0] def xor(a, b): res = "" for i in range(len(a)): if a[i] == b[i]: res += "0" else: res += "1" return res def apply_sbox(s, data): row = int("0b" + data[0] + data[-1], 2) col = int("0b" + data[1:3], 2) return bin(s[row][col])[2:] def function(expansion, s0, s1, key, message): left = message[:4] right = message[4:] temp = apply_table(right, expansion) temp = xor(temp, key) left_bin_str = apply_sbox(s0, temp[:4]) right_bin_str = apply_sbox(s1, temp[4:]) left_bin_str = "0" * (2 - len(left_bin_str)) + left_bin_str right_bin_str = "0" * (2 - len(right_bin_str)) + right_bin_str temp = apply_table(left_bin_str + right_bin_str, p4_table) temp = xor(left, temp) return temp + right if __name__ == "__main__": key = input("Enter 10 bit key: ") message = input("Enter 8 bit message: ") p8_table = [6, 3, 7, 4, 8, 5, 10, 9] p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] p4_table = [2, 4, 3, 1] IP = [2, 6, 3, 1, 4, 8, 5, 7] IP_inv = [4, 1, 3, 5, 7, 2, 8, 6] expansion = [4, 1, 2, 3, 2, 3, 4, 1] s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation temp = apply_table(key, p10_table) left = temp[:5] right = temp[5:] left = left_shift(left) right = left_shift(right) key1 = apply_table(left + right, p8_table) left = left_shift(left) right = left_shift(right) left = left_shift(left) right = left_shift(right) key2 = apply_table(left + right, p8_table) # encryption temp = apply_table(message, IP) temp = function(expansion, s0, s1, key1, temp) temp = temp[4:] + temp[:4] temp = function(expansion, s0, s1, key2, temp) CT = apply_table(temp, IP_inv) print("Cipher text is:", CT) # decryption temp = apply_table(CT, IP) temp = function(expansion, s0, s1, key2, temp) temp = temp[4:] + temp[:4] temp = function(expansion, s0, s1, key1, temp) PT = apply_table(temp, IP_inv) print("Plain text after decypting is:", PT)
--- +++ @@ -1,82 +1,96 @@-def apply_table(inp, table): - res = "" - for i in table: - res += inp[i - 1] - return res - - -def left_shift(data): - return data[1:] + data[0] - - -def xor(a, b): - res = "" - for i in range(len(a)): - if a[i] == b[i]: - res += "0" - else: - res += "1" - return res - - -def apply_sbox(s, data): - row = int("0b" + data[0] + data[-1], 2) - col = int("0b" + data[1:3], 2) - return bin(s[row][col])[2:] - - -def function(expansion, s0, s1, key, message): - left = message[:4] - right = message[4:] - temp = apply_table(right, expansion) - temp = xor(temp, key) - left_bin_str = apply_sbox(s0, temp[:4]) - right_bin_str = apply_sbox(s1, temp[4:]) - left_bin_str = "0" * (2 - len(left_bin_str)) + left_bin_str - right_bin_str = "0" * (2 - len(right_bin_str)) + right_bin_str - temp = apply_table(left_bin_str + right_bin_str, p4_table) - temp = xor(left, temp) - return temp + right - - -if __name__ == "__main__": - key = input("Enter 10 bit key: ") - message = input("Enter 8 bit message: ") - - p8_table = [6, 3, 7, 4, 8, 5, 10, 9] - p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] - p4_table = [2, 4, 3, 1] - IP = [2, 6, 3, 1, 4, 8, 5, 7] - IP_inv = [4, 1, 3, 5, 7, 2, 8, 6] - expansion = [4, 1, 2, 3, 2, 3, 4, 1] - s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] - s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] - - # key generation - temp = apply_table(key, p10_table) - left = temp[:5] - right = temp[5:] - left = left_shift(left) - right = left_shift(right) - key1 = apply_table(left + right, p8_table) - left = left_shift(left) - right = left_shift(right) - left = left_shift(left) - right = left_shift(right) - key2 = apply_table(left + right, p8_table) - - # encryption - temp = apply_table(message, IP) - temp = function(expansion, s0, s1, key1, temp) - temp = temp[4:] + temp[:4] - temp = function(expansion, s0, s1, key2, temp) - CT = apply_table(temp, IP_inv) - print("Cipher text is:", CT) - - # decryption - temp = apply_table(CT, IP) - temp = function(expansion, s0, s1, key2, temp) - temp = temp[4:] + temp[:4] - temp = function(expansion, s0, s1, key1, temp) - PT = apply_table(temp, IP_inv) - print("Plain text after decypting is:", PT)+def apply_table(inp, table): + """ + >>> apply_table("0123456789", list(range(10))) + '9012345678' + >>> apply_table("0123456789", list(range(9, -1, -1))) + '8765432109' + """ + res = "" + for i in table: + res += inp[i - 1] + return res + + +def left_shift(data): + """ + >>> left_shift("0123456789") + '1234567890' + """ + return data[1:] + data[0] + + +def xor(a, b): + """ + >>> xor("01010101", "00001111") + '01011010' + """ + res = "" + for i in range(len(a)): + if a[i] == b[i]: + res += "0" + else: + res += "1" + return res + + +def apply_sbox(s, data): + row = int("0b" + data[0] + data[-1], 2) + col = int("0b" + data[1:3], 2) + return bin(s[row][col])[2:] + + +def function(expansion, s0, s1, key, message): + left = message[:4] + right = message[4:] + temp = apply_table(right, expansion) + temp = xor(temp, key) + left_bin_str = apply_sbox(s0, temp[:4]) + right_bin_str = apply_sbox(s1, temp[4:]) + left_bin_str = "0" * (2 - len(left_bin_str)) + left_bin_str + right_bin_str = "0" * (2 - len(right_bin_str)) + right_bin_str + temp = apply_table(left_bin_str + right_bin_str, p4_table) + temp = xor(left, temp) + return temp + right + + +if __name__ == "__main__": + key = input("Enter 10 bit key: ") + message = input("Enter 8 bit message: ") + + p8_table = [6, 3, 7, 4, 8, 5, 10, 9] + p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] + p4_table = [2, 4, 3, 1] + IP = [2, 6, 3, 1, 4, 8, 5, 7] + IP_inv = [4, 1, 3, 5, 7, 2, 8, 6] + expansion = [4, 1, 2, 3, 2, 3, 4, 1] + s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] + s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] + + # key generation + temp = apply_table(key, p10_table) + left = temp[:5] + right = temp[5:] + left = left_shift(left) + right = left_shift(right) + key1 = apply_table(left + right, p8_table) + left = left_shift(left) + right = left_shift(right) + left = left_shift(left) + right = left_shift(right) + key2 = apply_table(left + right, p8_table) + + # encryption + temp = apply_table(message, IP) + temp = function(expansion, s0, s1, key1, temp) + temp = temp[4:] + temp[:4] + temp = function(expansion, s0, s1, key2, temp) + CT = apply_table(temp, IP_inv) + print("Cipher text is:", CT) + + # decryption + temp = apply_table(CT, IP) + temp = function(expansion, s0, s1, key2, temp) + temp = temp[4:] + temp[:4] + temp = function(expansion, s0, s1, key1, temp) + PT = apply_table(temp, IP_inv) + print("Plain text after decypting is:", PT)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/sdes.py
Provide docstrings following PEP 257
from random import choice, randint, shuffle # The words to display on the word search - # can be made dynamic by randonly selecting a certain number of # words from a predefined word file, while ensuring the character # count fits within the matrix size (n x m) WORDS = ["cat", "dog", "snake", "fish"] WIDTH = 10 HEIGHT = 10 class WordSearch: def __init__(self, words: list[str], width: int, height: int) -> None: self.words = words self.width = width self.height = height # Board matrix holding each letter self.board: list[list[str | None]] = [[None] * width for _ in range(height)] def insert_north(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space above the row to fit in the word if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Only check to be made here is if there are existing letters # above the column that will be overwritten letters_above = [self.board[row - i][col] for i in range(word_length)] if all(letter is None for letter in letters_above): # Successful, insert the word north for i in range(word_length): self.board[row - i][col] = word[i] return def insert_northeast(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word above the row if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word as well as above if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row - i][col + i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word northeast for i in range(word_length): self.board[row - i][col + i] = word[i] return def insert_east(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_left = [self.board[row][col + i] for i in range(word_length)] if all(letter is None for letter in letters_left): # Successful, insert the word east for i in range(word_length): self.board[row][col + i] = word[i] return def insert_southeast(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word below the row if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word as well as below if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row + i][col + i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word southeast for i in range(word_length): self.board[row + i][col + i] = word[i] return def insert_south(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space below the row to fit in the word if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Only check to be made here is if there are existing letters # below the column that will be overwritten letters_below = [self.board[row + i][col] for i in range(word_length)] if all(letter is None for letter in letters_below): # Successful, insert the word south for i in range(word_length): self.board[row + i][col] = word[i] return def insert_southwest(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word below the row if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word as well as below if word_length > col + 1: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row + i][col - i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word southwest for i in range(word_length): self.board[row + i][col - i] = word[i] return def insert_west(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word if word_length > col + 1: continue # Check if there are existing letters # to the left of the column that will be overwritten letters_left = [self.board[row][col - i] for i in range(word_length)] if all(letter is None for letter in letters_left): # Successful, insert the word west for i in range(word_length): self.board[row][col - i] = word[i] return def insert_northwest(self, word: str, rows: list[int], cols: list[int]) -> None: word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word above the row if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word as well as above if word_length > col + 1: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row - i][col - i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word northwest for i in range(word_length): self.board[row - i][col - i] = word[i] return def generate_board(self) -> None: directions = ( self.insert_north, self.insert_northeast, self.insert_east, self.insert_southeast, self.insert_south, self.insert_southwest, self.insert_west, self.insert_northwest, ) for word in self.words: # Shuffle the row order and column order that is used when brute forcing # the insertion of the word rows, cols = list(range(self.height)), list(range(self.width)) shuffle(rows) shuffle(cols) # Insert the word via the direction choice(directions)(word, rows, cols) def visualise_word_search( board: list[list[str | None]] | None = None, *, add_fake_chars: bool = True ) -> None: if board is None: word_search = WordSearch(WORDS, WIDTH, HEIGHT) word_search.generate_board() board = word_search.board result = "" for row in range(len(board)): for col in range(len(board[0])): character = "#" if (letter := board[row][col]) is not None: character = letter # Empty char, so add a fake char elif add_fake_chars: character = chr(randint(97, 122)) result += f"{character} " result += "\n" print(result, end="") if __name__ == "__main__": import doctest doctest.testmod() visualise_word_search()
--- +++ @@ -1,3 +1,9 @@+""" +Creates a random wordsearch with eight different directions +that are best described as compass locations. + +@ https://en.wikipedia.org/wiki/Word_search +""" from random import choice, randint, shuffle @@ -12,6 +18,12 @@ class WordSearch: + """ + >>> ws = WordSearch(WORDS, WIDTH, HEIGHT) + >>> ws.board # doctest: +ELLIPSIS + [[None, ..., None], ..., [None, ..., None]] + >>> ws.generate_board() + """ def __init__(self, words: list[str], width: int, height: int) -> None: self.words = words @@ -22,6 +34,19 @@ self.board: list[list[str | None]] = [[None] * width for _ in range(height)] def insert_north(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_north("cat", [2], [2]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, None, 't'], + [None, None, 'a'], + [None, None, 'c']] + >>> ws.insert_north("at", [0, 1, 2], [2, 1]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, 't', 't'], + [None, 'a', 'a'], + [None, None, 'c']] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -41,6 +66,19 @@ return def insert_northeast(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_northeast("cat", [2], [0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, None, 't'], + [None, 'a', None], + ['c', None, None]] + >>> ws.insert_northeast("at", [0, 1], [2, 1, 0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, 't', 't'], + ['a', 'a', None], + ['c', None, None]] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -66,6 +104,19 @@ return def insert_east(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_east("cat", [1], [0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, None, None], + ['c', 'a', 't'], + [None, None, None]] + >>> ws.insert_east("at", [1, 0], [2, 1, 0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, 'a', 't'], + ['c', 'a', 't'], + [None, None, None]] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -85,6 +136,19 @@ return def insert_southeast(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_southeast("cat", [0], [0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [['c', None, None], + [None, 'a', None], + [None, None, 't']] + >>> ws.insert_southeast("at", [1, 0], [2, 1, 0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [['c', None, None], + ['a', 'a', None], + [None, 't', 't']] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -110,6 +174,19 @@ return def insert_south(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_south("cat", [0], [0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [['c', None, None], + ['a', None, None], + ['t', None, None]] + >>> ws.insert_south("at", [2, 1, 0], [0, 1, 2]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [['c', None, None], + ['a', 'a', None], + ['t', 't', None]] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -129,6 +206,19 @@ return def insert_southwest(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_southwest("cat", [0], [2]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, None, 'c'], + [None, 'a', None], + ['t', None, None]] + >>> ws.insert_southwest("at", [1, 2], [2, 1, 0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, None, 'c'], + [None, 'a', 'a'], + ['t', 't', None]] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -154,6 +244,19 @@ return def insert_west(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_west("cat", [1], [2]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [[None, None, None], + ['t', 'a', 'c'], + [None, None, None]] + >>> ws.insert_west("at", [1, 0], [1, 2, 0]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [['t', 'a', None], + ['t', 'a', 'c'], + [None, None, None]] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -173,6 +276,19 @@ return def insert_northwest(self, word: str, rows: list[int], cols: list[int]) -> None: + """ + >>> ws = WordSearch(WORDS, 3, 3) + >>> ws.insert_northwest("cat", [2], [2]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [['t', None, None], + [None, 'a', None], + [None, None, 'c']] + >>> ws.insert_northwest("at", [1, 2], [0, 1]) + >>> ws.board # doctest: +NORMALIZE_WHITESPACE + [['t', None, None], + ['t', 'a', None], + [None, 'a', 'c']] + """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: @@ -198,6 +314,15 @@ return def generate_board(self) -> None: + """ + Generates a board with a random direction for each word. + + >>> wt = WordSearch(WORDS, WIDTH, HEIGHT) + >>> wt.generate_board() + >>> len(list(filter(lambda word: word is not None, sum(wt.board, start=[]))) + ... ) == sum(map(lambda word: len(word), WORDS)) + True + """ directions = ( self.insert_north, self.insert_northeast, @@ -222,6 +347,27 @@ def visualise_word_search( board: list[list[str | None]] | None = None, *, add_fake_chars: bool = True ) -> None: + """ + Graphically displays the word search in the terminal. + + >>> ws = WordSearch(WORDS, 5, 5) + >>> ws.insert_north("cat", [4], [4]) + >>> visualise_word_search( + ... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE + # # # # # + # # # # # + # # # # t + # # # # a + # # # # c + >>> ws.insert_northeast("snake", [4], [4, 3, 2, 1, 0]) + >>> visualise_word_search( + ... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE + # # # # e + # # # k # + # # a # t + # n # # a + s # # # c + """ if board is None: word_search = WordSearch(WORDS, WIDTH, HEIGHT) word_search.generate_board() @@ -246,4 +392,4 @@ doctest.testmod() - visualise_word_search()+ visualise_word_search()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/word_search.py
Add docstrings for better understanding
def get_altitude_at_pressure(pressure: float) -> float: if pressure > 101325: raise ValueError("Value Higher than Pressure at Sea Level !") if pressure < 0: raise ValueError("Atmospheric Pressure can not be negative !") return 44_330 * (1 - (pressure / 101_325) ** (1 / 5.5255)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,43 @@+""" +Title : Calculate altitude using Pressure + +Description : + The below algorithm approximates the altitude using Barometric formula + + +""" def get_altitude_at_pressure(pressure: float) -> float: + """ + This method calculates the altitude from Pressure wrt to + Sea level pressure as reference .Pressure is in Pascals + https://en.wikipedia.org/wiki/Pressure_altitude + https://community.bosch-sensortec.com/t5/Question-and-answers/How-to-calculate-the-altitude-from-the-pressure-sensor-data/qaq-p/5702 + + H = 44330 * [1 - (P/p0)^(1/5.255) ] + + Where : + H = altitude (m) + P = measured pressure + p0 = reference pressure at sea level 101325 Pa + + Examples: + >>> get_altitude_at_pressure(pressure=100_000) + 105.47836610778828 + >>> get_altitude_at_pressure(pressure=101_325) + 0.0 + >>> get_altitude_at_pressure(pressure=80_000) + 1855.873388064995 + >>> get_altitude_at_pressure(pressure=201_325) + Traceback (most recent call last): + ... + ValueError: Value Higher than Pressure at Sea Level ! + >>> get_altitude_at_pressure(pressure=-80_000) + Traceback (most recent call last): + ... + ValueError: Atmospheric Pressure can not be negative ! + """ if pressure > 101325: raise ValueError("Value Higher than Pressure at Sea Level !") @@ -12,4 +49,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/altitude_pressure.py
Add standardized docstrings across the file
from math import pow, sqrt # noqa: A004 from scipy.constants import G, c, pi def capture_radii( target_body_radius: float, target_body_mass: float, projectile_velocity: float ) -> float: if target_body_mass < 0: raise ValueError("Mass cannot be less than 0") if target_body_radius < 0: raise ValueError("Radius cannot be less than 0") if projectile_velocity > c: raise ValueError("Cannot go beyond speed of light") escape_velocity_squared = (2 * G * target_body_mass) / target_body_radius capture_radius = target_body_radius * sqrt( 1 + escape_velocity_squared / pow(projectile_velocity, 2) ) return round(capture_radius, 0) def capture_area(capture_radius: float) -> float: if capture_radius < 0: raise ValueError("Cannot have a capture radius less than 0") sigma = pi * pow(capture_radius, 2) return round(sigma, 0) if __name__ == "__main__": from doctest import testmod testmod() """ Derivation: Let: Mt=target mass, Rt=target radius, v=projectile_velocity, r_0=radius of projectile at instant 0 to CM of target v_p=v at closest approach, r_p=radius from projectile to target CM at closest approach, R_capture= radius of impact for projectile with velocity v (1)At time=0 the projectile's energy falling from infinity| E=K+U=0.5*m*(v**2)+0 E_initial=0.5*m*(v**2) (2)at time=0 the angular momentum of the projectile relative to CM target| L_initial=m*r_0*v*sin(Θ)->m*r_0*v*(R_capture/r_0)->m*v*R_capture L_i=m*v*R_capture (3)The energy of the projectile at closest approach will be its kinetic energy at closest approach plus gravitational potential energy(-(GMm)/R)| E_p=K_p+U_p->E_p=0.5*m*(v_p**2)-(G*Mt*m)/r_p E_p=0.0.5*m*(v_p**2)-(G*Mt*m)/r_p (4)The angular momentum of the projectile relative to the target at closest approach will be L_p=m*r_p*v_p*sin(Θ), however relative to the target Θ=90° sin(90°)=1| L_p=m*r_p*v_p (5)Using conservation of angular momentum and energy, we can write a quadratic equation that solves for r_p| (a) Ei=Ep-> 0.5*m*(v**2)=0.5*m*(v_p**2)-(G*Mt*m)/r_p-> v**2=v_p**2-(2*G*Mt)/r_p (b) Li=Lp-> m*v*R_capture=m*r_p*v_p-> v*R_capture=r_p*v_p-> v_p=(v*R_capture)/r_p (c) b plugs int a| v**2=((v*R_capture)/r_p)**2-(2*G*Mt)/r_p-> v**2-(v**2)*(R_c**2)/(r_p**2)+(2*G*Mt)/r_p=0-> (v**2)*(r_p**2)+2*G*Mt*r_p-(v**2)*(R_c**2)=0 (d) Using the quadratic formula, we'll solve for r_p then rearrange to solve to R_capture r_p=(-2*G*Mt ± sqrt(4*G^2*Mt^2+ 4(v^4*R_c^2)))/(2*v^2)-> r_p=(-G*Mt ± sqrt(G^2*Mt+v^4*R_c^2))/v^2-> r_p<0 is something we can ignore, as it has no physical meaning for our purposes.-> r_p=(-G*Mt)/v^2 + sqrt(G^2*Mt^2/v^4 + R_c^2) (e)We are trying to solve for R_c. We are looking for impact, so we want r_p=Rt Rt + G*Mt/v^2 = sqrt(G^2*Mt^2/v^4 + R_c^2)-> (Rt + G*Mt/v^2)^2 = G^2*Mt^2/v^4 + R_c^2-> Rt^2 + 2*G*Mt*Rt/v^2 + G^2*Mt^2/v^4 = G^2*Mt^2/v^4 + R_c^2-> Rt**2 + 2*G*Mt*Rt/v**2 = R_c**2-> Rt**2 * (1 + 2*G*Mt/Rt *1/v**2) = R_c**2-> escape velocity = sqrt(2GM/R)= v_escape**2=2GM/R-> Rt**2 * (1 + v_esc**2/v**2) = R_c**2-> (6) R_capture = Rt * sqrt(1 + v_esc**2/v**2) Source: Problem Set 3 #8 c.Fall_2017|Honors Astronomy|Professor Rachel Bezanson Source #2: http://www.nssc.ac.cn/wxzygx/weixin/201607/P020160718380095698873.pdf 8.8 Planetary Rendezvous: Pg.368 """
--- +++ @@ -1,3 +1,16 @@+""" +These two functions will return the radii of impact for a target object +of mass M and radius R as well as it's effective cross sectional area sigma. +That is to say any projectile with velocity v passing within sigma, will impact the +target object with mass M. The derivation of which is given at the bottom +of this file. + +The derivation shows that a projectile does not need to aim directly at the target +body in order to hit it, as R_capture>R_target. Astronomers refer to the effective +cross section for capture as sigma=π*R_capture**2. + +This algorithm does not account for an N-body problem. +""" from math import pow, sqrt # noqa: A004 @@ -7,6 +20,34 @@ def capture_radii( target_body_radius: float, target_body_mass: float, projectile_velocity: float ) -> float: + """ + Input Params: + ------------- + target_body_radius: Radius of the central body SI units: meters | m + target_body_mass: Mass of the central body SI units: kilograms | kg + projectile_velocity: Velocity of object moving toward central body + SI units: meters/second | m/s + Returns: + -------- + >>> capture_radii(6.957e8, 1.99e30, 25000.0) + 17209590691.0 + >>> capture_radii(-6.957e8, 1.99e30, 25000.0) + Traceback (most recent call last): + ... + ValueError: Radius cannot be less than 0 + >>> capture_radii(6.957e8, -1.99e30, 25000.0) + Traceback (most recent call last): + ... + ValueError: Mass cannot be less than 0 + >>> capture_radii(6.957e8, 1.99e30, c+1) + Traceback (most recent call last): + ... + ValueError: Cannot go beyond speed of light + + Returned SI units: + ------------------ + meters | m + """ if target_body_mass < 0: raise ValueError("Mass cannot be less than 0") @@ -23,6 +64,25 @@ def capture_area(capture_radius: float) -> float: + """ + Input Param: + ------------ + capture_radius: The radius of orbital capture and impact for a central body of + mass M and a projectile moving towards it with velocity v + SI units: meters | m + Returns: + -------- + >>> capture_area(17209590691) + 9.304455331329126e+20 + >>> capture_area(-1) + Traceback (most recent call last): + ... + ValueError: Cannot have a capture radius less than 0 + + Returned SI units: + ------------------ + meters*meters | m**2 + """ if capture_radius < 0: raise ValueError("Cannot have a capture radius less than 0") @@ -114,4 +174,4 @@ Source #2: http://www.nssc.ac.cn/wxzygx/weixin/201607/P020160718380095698873.pdf 8.8 Planetary Rendezvous: Pg.368 -"""+"""
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/basic_orbital_capture.py
Help me write clear docstrings
from collections import namedtuple Particle = namedtuple("Particle", "x y z mass") # noqa: PYI024 Coord3D = namedtuple("Coord3D", "x y z") # noqa: PYI024 def center_of_mass(particles: list[Particle]) -> Coord3D: if not particles: raise ValueError("No particles provided") if any(particle.mass <= 0 for particle in particles): raise ValueError("Mass of all particles must be greater than 0") total_mass = sum(particle.mass for particle in particles) center_of_mass_x = round( sum(particle.x * particle.mass for particle in particles) / total_mass, 2 ) center_of_mass_y = round( sum(particle.y * particle.mass for particle in particles) / total_mass, 2 ) center_of_mass_z = round( sum(particle.z * particle.mass for particle in particles) / total_mass, 2 ) return Coord3D(center_of_mass_x, center_of_mass_y, center_of_mass_z) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,29 @@+""" +Calculating the center of mass for a discrete system of particles, given their +positions and masses. + +Description: + +In physics, the center of mass of a distribution of mass in space (sometimes referred +to as the barycenter or balance point) is the unique point at any given time where the +weighted relative position of the distributed mass sums to zero. This is the point to +which a force may be applied to cause a linear acceleration without an angular +acceleration. + +Calculations in mechanics are often simplified when formulated with respect to the +center of mass. It is a hypothetical point where the entire mass of an object may be +assumed to be concentrated to visualize its motion. In other words, the center of mass +is the particle equivalent of a given object for the application of Newton's laws of +motion. + +In the case of a system of particles P_i, i = 1, ..., n , each with mass m_i that are +located in space with coordinates r_i, i = 1, ..., n , the coordinates R of the center +of mass corresponds to: + +R = (Σ(mi * ri) / Σ(mi)) + +Reference: https://en.wikipedia.org/wiki/Center_of_mass +""" from collections import namedtuple @@ -6,6 +32,58 @@ def center_of_mass(particles: list[Particle]) -> Coord3D: + """ + Input Parameters + ---------------- + particles: list(Particle): + A list of particles where each particle is a tuple with it's (x, y, z) position and + it's mass. + + Returns + ------- + Coord3D: + A tuple with the coordinates of the center of mass (Xcm, Ycm, Zcm) rounded to two + decimal places. + + Examples + -------- + >>> center_of_mass([ + ... Particle(1.5, 4, 3.4, 4), + ... Particle(5, 6.8, 7, 8.1), + ... Particle(9.4, 10.1, 11.6, 12) + ... ]) + Coord3D(x=6.61, y=7.98, z=8.69) + + >>> center_of_mass([ + ... Particle(1, 2, 3, 4), + ... Particle(5, 6, 7, 8), + ... Particle(9, 10, 11, 12) + ... ]) + Coord3D(x=6.33, y=7.33, z=8.33) + + >>> center_of_mass([ + ... Particle(1, 2, 3, -4), + ... Particle(5, 6, 7, 8), + ... Particle(9, 10, 11, 12) + ... ]) + Traceback (most recent call last): + ... + ValueError: Mass of all particles must be greater than 0 + + >>> center_of_mass([ + ... Particle(1, 2, 3, 0), + ... Particle(5, 6, 7, 8), + ... Particle(9, 10, 11, 12) + ... ]) + Traceback (most recent call last): + ... + ValueError: Mass of all particles must be greater than 0 + + >>> center_of_mass([]) + Traceback (most recent call last): + ... + ValueError: No particles provided + """ if not particles: raise ValueError("No particles provided") @@ -29,4 +107,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/center_of_mass.py
Write docstrings describing each step
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length)) # ALTERNATIVE METHODS # chars_incl= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(chars_incl: str, i: int) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(chars_incl) quotient = i // 3 remainder = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( chars_incl + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) list_of_chars = list(chars) shuffle(list_of_chars) return "".join(list_of_chars) # random is a generalised function for letters, characters and numbers def random(chars_incl: str, i: int) -> str: return "".join(secrets.choice(chars_incl) for _ in range(i)) def is_strong_password(password: str, min_length: int = 8) -> bool: if len(password) < min_length: return False upper = any(char in ascii_uppercase for char in password) lower = any(char in ascii_lowercase for char in password) num = any(char in digits for char in password) spec_char = any(char in punctuation for char in password) return upper and lower and num and spec_char def main(): length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(chars_incl, length), ) print("[If you are thinking of using this password, You better save it.]") if __name__ == "__main__": main()
--- +++ @@ -4,6 +4,20 @@ def password_generator(length: int = 8) -> str: + """ + Password Generator allows you to generate a random password of length N. + + >>> len(password_generator()) + 8 + >>> len(password_generator(length=16)) + 16 + >>> len(password_generator(257)) + 257 + >>> len(password_generator(length=0)) + 0 + >>> len(password_generator(-1)) + 0 + """ chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length)) @@ -38,6 +52,22 @@ def is_strong_password(password: str, min_length: int = 8) -> bool: + """ + This will check whether a given password is strong or not. The password must be at + least as long as the provided minimum length, and it must contain at least 1 + lowercase letter, 1 uppercase letter, 1 number and 1 special character. + + >>> is_strong_password('Hwea7$2!') + True + >>> is_strong_password('Sh0r1') + False + >>> is_strong_password('Hello123') + False + >>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1') + True + >>> is_strong_password('0') + False + """ if len(password) < min_length: return False @@ -64,4 +94,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/other/password.py
Write proper docstrings for these functions
def coulombs_law(q1: float, q2: float, radius: float) -> float: if radius <= 0: raise ValueError("The radius is always a positive number") return round(((8.9875517923 * 10**9) * q1 * q2) / (radius**2), 2) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,36 @@+""" +Coulomb's law states that the magnitude of the electrostatic force of attraction +or repulsion between two point charges is directly proportional to the product +of the magnitudes of charges and inversely proportional to the square of the +distance between them. + +F = k * q1 * q2 / r^2 + +k is Coulomb's constant and equals 1/(4π*ε0) +q1 is charge of first body (C) +q2 is charge of second body (C) +r is distance between two charged bodies (m) + +Reference: https://en.wikipedia.org/wiki/Coulomb%27s_law +""" def coulombs_law(q1: float, q2: float, radius: float) -> float: + """ + Calculate the electrostatic force of attraction or repulsion + between two point charges + + >>> coulombs_law(15.5, 20, 15) + 12382849136.06 + >>> coulombs_law(1, 15, 5) + 5392531075.38 + >>> coulombs_law(20, -50, 15) + -39944674632.44 + >>> coulombs_law(-5, -8, 10) + 3595020716.92 + >>> coulombs_law(50, 100, 50) + 17975103584.6 + """ if radius <= 0: raise ValueError("The radius is always a positive number") return round(((8.9875517923 * 10**9) * q1 * q2) / (radius**2), 2) @@ -9,4 +39,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/coulombs_law.py
Write docstrings for utility functions
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function REDUCED_PLANCK_CONSTANT = 1.054571817e-34 # unit of ℏ : J * s SPEED_OF_LIGHT = 3e8 # unit of c : m * s^-1 def casimir_force(force: float, area: float, distance: float) -> dict[str, float]: if (force, area, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Magnitude of force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if area < 0: raise ValueError("Area can not be negative") if force == 0: force = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: area = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: distance = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("One and only one argument must be 0") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,39 @@+""" +Title : Finding the value of magnitude of either the Casimir force, the surface area +of one of the plates or distance between the plates provided that the other +two parameters are given. + +Description : In quantum field theory, the Casimir effect is a physical force +acting on the macroscopic boundaries of a confined space which arises from the +quantum fluctuations of the field. It is a physical force exerted between separate +objects, which is due to neither charge, gravity, nor the exchange of particles, +but instead is due to resonance of all-pervasive energy fields in the intervening +space between the objects. Since the strength of the force falls off rapidly with +distance it is only measurable when the distance between the objects is extremely +small. On a submicron scale, this force becomes so strong that it becomes the +dominant force between uncharged conductors. + +Dutch physicist Hendrik B. G. Casimir first proposed the existence of the force, +and he formulated an experiment to detect it in 1948 while participating in research +at Philips Research Labs. The classic form of his experiment used a pair of uncharged +parallel metal plates in a vacuum, and successfully demonstrated the force to within +15% of the value he had predicted according to his theory. + +The Casimir force F for idealized, perfectly conducting plates of surface area +A square meter and placed at a distance of a meter apart with vacuum between +them is expressed as - + +F = - ((Reduced Planck Constant ℏ) * c * Pi^2 * A) / (240 * a^4) + +Here, the negative sign indicates the force is attractive in nature. For the ease +of calculation, only the magnitude of the force is considered. + +Source : +- https://en.wikipedia.org/wiki/Casimir_effect +- https://www.cs.mcgill.ca/~rwest/wikispeedia/wpcd/wp/c/Casimir_effect.htm +- Casimir, H. B. ; Polder, D. (1948) "The Influence of Retardation on the + London-van der Waals Forces", Physical Review, vol. 73, Issue 4, pp. 360-372 +""" from __future__ import annotations @@ -11,6 +47,45 @@ def casimir_force(force: float, area: float, distance: float) -> dict[str, float]: + """ + Input Parameters + ---------------- + force -> Casimir Force : magnitude in Newtons + + area -> Surface area of each plate : magnitude in square meters + + distance -> Distance between two plates : distance in Meters + + Returns + ------- + result : dict name, value pair of the parameter having Zero as it's value + + Returns the value of one of the parameters specified as 0, provided the values of + other parameters are given. + >>> casimir_force(force = 0, area = 4, distance = 0.03) + {'force': 6.4248189174864216e-21} + + >>> casimir_force(force = 2635e-13, area = 0.0023, distance = 0) + {'distance': 1.0323056015031114e-05} + + >>> casimir_force(force = 2737e-21, area = 0, distance = 0.0023746) + {'area': 0.06688838837354052} + + >>> casimir_force(force = 3457e-12, area = 0, distance = 0) + Traceback (most recent call last): + ... + ValueError: One and only one argument must be 0 + + >>> casimir_force(force = 3457e-12, area = 0, distance = -0.00344) + Traceback (most recent call last): + ... + ValueError: Distance can not be negative + + >>> casimir_force(force = -912e-12, area = 0, distance = 0.09374) + Traceback (most recent call last): + ... + ValueError: Magnitude of force can not be negative + """ if (force, area, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") @@ -42,4 +117,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/casimir_effect.py
Add return value explanations in docstrings
def centripetal(mass: float, velocity: float, radius: float) -> float: if mass < 0: raise ValueError("The mass of the body cannot be negative") if radius <= 0: raise ValueError("The radius is always a positive non zero integer") return (mass * (velocity) ** 2) / radius if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
--- +++ @@ -1,6 +1,41 @@+""" +Description : Centripetal force is the force acting on an object in +curvilinear motion directed towards the axis of rotation +or centre of curvature. + +The unit of centripetal force is newton. + +The centripetal force is always directed perpendicular to the +direction of the object's displacement. Using Newton's second +law of motion, it is found that the centripetal force of an object +moving in a circular path always acts towards the centre of the circle. +The Centripetal Force Formula is given as the product of mass (in kg) +and tangential velocity (in meters per second) squared, divided by the +radius (in meters) that implies that on doubling the tangential velocity, +the centripetal force will be quadrupled. Mathematically it is written as: +F = mv²/r +Where, F is the Centripetal force, m is the mass of the object, v is the +speed or velocity of the object and r is the radius. + +Reference: https://byjus.com/physics/centripetal-and-centrifugal-force/ +""" def centripetal(mass: float, velocity: float, radius: float) -> float: + """ + The Centripetal Force formula is given as: (m*v*v)/r + + >>> round(centripetal(15.5,-30,10),2) + 1395.0 + >>> round(centripetal(10,15,5),2) + 450.0 + >>> round(centripetal(20,-50,15),2) + 3333.33 + >>> round(centripetal(12.25,40,25),2) + 784.0 + >>> round(centripetal(50,100,50),2) + 10000.0 + """ if mass < 0: raise ValueError("The mass of the body cannot be negative") if radius <= 0: @@ -11,4 +46,4 @@ if __name__ == "__main__": import doctest - doctest.testmod(verbose=True)+ doctest.testmod(verbose=True)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/centripetal_force.py
Add docstrings to improve code quality
def doppler_effect( org_freq: float, wave_vel: float, obs_vel: float, src_vel: float ) -> float: if wave_vel == src_vel: raise ZeroDivisionError( "Division by zero implies vs=v and observer in front of the source" ) doppler_freq = (org_freq * (wave_vel + obs_vel)) / (wave_vel - src_vel) if doppler_freq <= 0: raise ValueError( "Non-positive frequency implies vs>v or v0>v (in the opposite direction)" ) return doppler_freq if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,90 @@+""" +Doppler's effect + +The Doppler effect (also Doppler shift) is the change in the frequency of a wave in +relation to an observer who is moving relative to the source of the wave. The Doppler +effect is named after the physicist Christian Doppler. A common example of Doppler +shift is the change of pitch heard when a vehicle sounding a horn approaches and +recedes from an observer. + +The reason for the Doppler effect is that when the source of the waves is moving +towards the observer, each successive wave crest is emitted from a position closer to +the observer than the crest of the previous wave. Therefore, each wave takes slightly +less time to reach the observer than the previous wave. Hence, the time between the +arrivals of successive wave crests at the observer is reduced, causing an increase in +the frequency. Similarly, if the source of waves is moving away from the observer, +each wave is emitted from a position farther from the observer than the previous wave, +so the arrival time between successive waves is increased, reducing the frequency. + +If the source of waves is stationary but the observer is moving with respect to the +source, the transmission velocity of the waves changes (ie the rate at which the +observer receives waves) even if the wavelength and frequency emitted from the source +remain constant. + +These results are all summarized by the Doppler formula: + + f = (f0 * (v + v0)) / (v - vs) + +where: + f: frequency of the wave + f0: frequency of the wave when the source is stationary + v: velocity of the wave in the medium + v0: velocity of the observer, positive if the observer is moving towards the source + vs: velocity of the source, positive if the source is moving towards the observer + +Doppler's effect has many applications in physics and engineering, such as radar, +astronomy, medical imaging, and seismology. + +References: +https://en.wikipedia.org/wiki/Doppler_effect + +Now, we will implement a function that calculates the frequency of a wave as a function +of the frequency of the wave when the source is stationary, the velocity of the wave +in the medium, the velocity of the observer and the velocity of the source. +""" def doppler_effect( org_freq: float, wave_vel: float, obs_vel: float, src_vel: float ) -> float: + """ + Input Parameters: + ----------------- + org_freq: frequency of the wave when the source is stationary + wave_vel: velocity of the wave in the medium + obs_vel: velocity of the observer, +ve if the observer is moving towards the source + src_vel: velocity of the source, +ve if the source is moving towards the observer + + Returns: + -------- + f: frequency of the wave as perceived by the observer + + Docstring Tests: + >>> doppler_effect(100, 330, 10, 0) # observer moving towards the source + 103.03030303030303 + >>> doppler_effect(100, 330, -10, 0) # observer moving away from the source + 96.96969696969697 + >>> doppler_effect(100, 330, 0, 10) # source moving towards the observer + 103.125 + >>> doppler_effect(100, 330, 0, -10) # source moving away from the observer + 97.05882352941177 + >>> doppler_effect(100, 330, 10, 10) # source & observer moving towards each other + 106.25 + >>> doppler_effect(100, 330, -10, -10) # source and observer moving away + 94.11764705882354 + >>> doppler_effect(100, 330, 10, 330) # source moving at same speed as the wave + Traceback (most recent call last): + ... + ZeroDivisionError: Division by zero implies vs=v and observer in front of the source + >>> doppler_effect(100, 330, 10, 340) # source moving faster than the wave + Traceback (most recent call last): + ... + ValueError: Non-positive frequency implies vs>v or v0>v (in the opposite direction) + >>> doppler_effect(100, 330, -340, 10) # observer moving faster than the wave + Traceback (most recent call last): + ... + ValueError: Non-positive frequency implies vs>v or v0>v (in the opposite direction) + """ if wave_vel == src_vel: raise ZeroDivisionError( @@ -19,4 +101,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/doppler_frequency.py
Fully document this Python code with docstrings
# Acceleration Constant on Earth (unit m/s^2) g = 9.80665 # Also available in scipy.constants.g def archimedes_principle( fluid_density: float, volume: float, gravity: float = g ) -> float: if fluid_density <= 0: raise ValueError("Impossible fluid density") if volume <= 0: raise ValueError("Impossible object volume") if gravity < 0: raise ValueError("Impossible gravity") return fluid_density * gravity * volume if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,12 @@+""" +Calculate the buoyant force of any body completely or partially submerged in a static +fluid. This principle was discovered by the Greek mathematician Archimedes. + +Equation for calculating buoyant force: +Fb = p * V * g + +https://en.wikipedia.org/wiki/Archimedes%27_principle +""" # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 # Also available in scipy.constants.g @@ -6,6 +15,36 @@ def archimedes_principle( fluid_density: float, volume: float, gravity: float = g ) -> float: + """ + Args: + fluid_density: density of fluid (kg/m^3) + volume: volume of object/liquid being displaced by the object (m^3) + gravity: Acceleration from gravity. Gravitational force on the system, + The default is Earth Gravity + returns: + the buoyant force on an object in Newtons + + >>> archimedes_principle(fluid_density=500, volume=4, gravity=9.8) + 19600.0 + >>> archimedes_principle(fluid_density=997, volume=0.5, gravity=9.8) + 4885.3 + >>> archimedes_principle(fluid_density=997, volume=0.7) + 6844.061035 + >>> archimedes_principle(fluid_density=997, volume=-0.7) + Traceback (most recent call last): + ... + ValueError: Impossible object volume + >>> archimedes_principle(fluid_density=0, volume=0.7) + Traceback (most recent call last): + ... + ValueError: Impossible fluid density + >>> archimedes_principle(fluid_density=997, volume=0.7, gravity=0) + 0.0 + >>> archimedes_principle(fluid_density=997, volume=0.7, gravity=-9.8) + Traceback (most recent call last): + ... + ValueError: Impossible gravity + """ if fluid_density <= 0: raise ValueError("Impossible fluid density") @@ -20,4 +59,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/archimedes_principle_of_buoyant_force.py
Add docstrings that explain purpose and usage
# Importing packages from math import radians as deg_to_rad from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be an integer or float.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Should be an integer or float.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = deg_to_rad(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = deg_to_rad(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = deg_to_rad(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]") print(f"Maximum Height: {max_height(init_vel, angle)!s} [m]") print(f"Total Time: {total_time(init_vel, angle)!s} [s]")
--- +++ @@ -1,3 +1,20 @@+""" +Horizontal Projectile Motion problem in physics. + +This algorithm solves a specific problem in which +the motion starts from the ground as can be seen below:: + + (v = 0) + * * + * * + * * + * * + * * + * * + GROUND GROUND + +For more info: https://en.wikipedia.org/wiki/Projectile_motion +""" # Importing packages from math import radians as deg_to_rad @@ -8,6 +25,9 @@ def check_args(init_velocity: float, angle: float) -> None: + """ + Check that the arguments are valid + """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): @@ -26,24 +46,101 @@ def horizontal_distance(init_velocity: float, angle: float) -> float: + r""" + Returns the horizontal distance that the object cover + + Formula: + .. math:: + \frac{v_0^2 \cdot \sin(2 \alpha)}{g} + + v_0 - \text{initial velocity} + + \alpha - \text{angle} + + >>> horizontal_distance(30, 45) + 91.77 + >>> horizontal_distance(100, 78) + 414.76 + >>> horizontal_distance(-1, 20) + Traceback (most recent call last): + ... + ValueError: Invalid velocity. Should be a positive number. + >>> horizontal_distance(30, -20) + Traceback (most recent call last): + ... + ValueError: Invalid angle. Range is 1-90 degrees. + """ check_args(init_velocity, angle) radians = deg_to_rad(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: + r""" + Returns the maximum height that the object reach + + Formula: + .. math:: + \frac{v_0^2 \cdot \sin^2 (\alpha)}{2 g} + + v_0 - \text{initial velocity} + + \alpha - \text{angle} + + >>> max_height(30, 45) + 22.94 + >>> max_height(100, 78) + 487.82 + >>> max_height("a", 20) + Traceback (most recent call last): + ... + TypeError: Invalid velocity. Should be an integer or float. + >>> horizontal_distance(30, "b") + Traceback (most recent call last): + ... + TypeError: Invalid angle. Should be an integer or float. + """ check_args(init_velocity, angle) radians = deg_to_rad(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: + r""" + Returns total time of the motion + + Formula: + .. math:: + \frac{2 v_0 \cdot \sin (\alpha)}{g} + + v_0 - \text{initial velocity} + + \alpha - \text{angle} + + >>> total_time(30, 45) + 4.33 + >>> total_time(100, 78) + 19.95 + >>> total_time(-10, 40) + Traceback (most recent call last): + ... + ValueError: Invalid velocity. Should be a positive number. + >>> total_time(30, "b") + Traceback (most recent call last): + ... + TypeError: Invalid angle. Should be an integer or float. + """ check_args(init_velocity, angle) radians = deg_to_rad(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: + """ + Test motion + + >>> test_motion() + """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 @@ -66,4 +163,4 @@ print("Results: ") print(f"Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]") print(f"Maximum Height: {max_height(init_vel, angle)!s} [m]") - print(f"Total Time: {total_time(init_vel, angle)!s} [s]")+ print(f"Total Time: {total_time(init_vel, angle)!s} [s]")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/horizontal_projectile_motion.py
Create Google-style docstrings for my code
def hubble_parameter( hubble_constant: float, radiation_density: float, matter_density: float, dark_energy: float, redshift: float, ) -> float: parameters = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters): raise ValueError("All input parameters must be positive") if any(p > 1 for p in parameters[1:4]): raise ValueError("Relative densities cannot be greater than one") else: curvature = 1 - (matter_density + radiation_density + dark_energy) e_2 = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) hubble = hubble_constant * e_2 ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation matter_density = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
--- +++ @@ -1,3 +1,30 @@+""" +Title : Calculating the Hubble Parameter + +Description : The Hubble parameter H is the Universe expansion rate +in any time. In cosmology is customary to use the redshift redshift +in place of time, becausethe redshift is directily mensure +in the light of galaxies moving away from us. + +So, the general relation that we obtain is + +H = hubble_constant*(radiation_density*(redshift+1)**4 + + matter_density*(redshift+1)**3 + + curvature*(redshift+1)**2 + dark_energy)**(1/2) + +where radiation_density, matter_density, dark_energy are the relativity +(the percentage) energy densities that exist +in the Universe today. Here, matter_density is the +sum of the barion density and the +dark matter. Curvature is the curvature parameter and can be written in term +of the densities by the completeness + + +curvature = 1 - (matter_density + radiation_density + dark_energy) + +Source : +https://www.sciencedirect.com/topics/mathematics/hubble-parameter +""" def hubble_parameter( @@ -7,6 +34,41 @@ dark_energy: float, redshift: float, ) -> float: + """ + Input Parameters + ---------------- + hubble_constant: Hubble constante is the expansion rate today usually + given in km/(s*Mpc) + + radiation_density: relative radiation density today + + matter_density: relative mass density today + + dark_energy: relative dark energy density today + + redshift: the light redshift + + Returns + ------- + result : Hubble parameter in and the unit km/s/Mpc (the unit can be + changed if you want, just need to change the unit of the Hubble constant) + + >>> hubble_parameter(hubble_constant=68.3, radiation_density=1e-4, + ... matter_density=-0.3, dark_energy=0.7, redshift=1) + Traceback (most recent call last): + ... + ValueError: All input parameters must be positive + + >>> hubble_parameter(hubble_constant=68.3, radiation_density=1e-4, + ... matter_density= 1.2, dark_energy=0.7, redshift=1) + Traceback (most recent call last): + ... + ValueError: Relative densities cannot be greater than one + + >>> hubble_parameter(hubble_constant=68.3, radiation_density=1e-4, + ... matter_density= 0.3, dark_energy=0.7, redshift=0) + 68.3 + """ parameters = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters): raise ValueError("All input parameters must be positive") @@ -44,4 +106,4 @@ dark_energy=1 - matter_density, redshift=0, ) - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/hubble_parameter.py
Generate docstrings for this script
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) c = 299792458 # Symbols ct, x, y, z = symbols("ct x y z") # Vehicle's speed divided by speed of light (no units) def beta(velocity: float) -> float: if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!") elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!") return velocity / c def gamma(velocity: float) -> float: return 1 / sqrt(1 - beta(velocity) ** 2) def transformation_matrix(velocity: float) -> np.ndarray: return np.array( [ [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], [-gamma(velocity) * beta(velocity), gamma(velocity), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray: # Ensure event is not empty if event is None: event = np.array([ct, x, y, z]) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(velocity) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: four_vector = transform(29979245) print("Example of four vector: ") print(f"ct' = {four_vector[0]}") print(f"x' = {four_vector[1]}") print(f"y' = {four_vector[2]}") print(f"z' = {four_vector[3]}") # Substitute symbols with numerical values sub_dict = {ct: c, x: 1, y: 1, z: 1} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)] print(f"\n{numerical_vector}")
--- +++ @@ -1,3 +1,28 @@+""" +Lorentz transformations describe the transition between two inertial reference +frames F and F', each of which is moving in some direction with respect to the +other. This code only calculates Lorentz transformations for movement in the x +direction with no spatial rotation (i.e., a Lorentz boost in the x direction). +The Lorentz transformations are calculated here as linear transformations of +four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is +multiplied by c (the speed of light) in the first entry of each four-vector. + +Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for +two inertial reference frames and X' moves in the x direction with velocity v +with respect to X, then the Lorentz transformation from X to X' is X' = BX, +where + + | y -γβ 0 0| +B = |-γβ y 0 0| + | 0 0 1 0| + | 0 0 0 1| + +is the matrix describing the Lorentz boost between X and X', +y = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as +a fraction of c. + +Reference: https://en.wikipedia.org/wiki/Lorentz_transformation +""" from math import sqrt @@ -14,6 +39,19 @@ # Vehicle's speed divided by speed of light (no units) def beta(velocity: float) -> float: + """ + Calculates β = v/c, the given velocity as a fraction of c + >>> beta(c) + 1.0 + >>> beta(199792458) + 0.666435904801848 + >>> beta(1e5) + 0.00033356409519815205 + >>> beta(0.2) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than or equal to 1! + """ if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!") elif velocity < 1: @@ -24,10 +62,68 @@ def gamma(velocity: float) -> float: + """ + Calculate the Lorentz factor y = 1 / √(1 - v²/c²) for a given velocity + >>> gamma(4) + 1.0000000000000002 + >>> gamma(1e5) + 1.0000000556325075 + >>> gamma(3e7) + 1.005044845777813 + >>> gamma(2.8e8) + 2.7985595722318277 + >>> gamma(299792451) + 4627.49902669495 + >>> gamma(0.3) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than or equal to 1! + >>> gamma(2 * c) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed light speed 299,792,458 [m/s]! + """ return 1 / sqrt(1 - beta(velocity) ** 2) def transformation_matrix(velocity: float) -> np.ndarray: + """ + Calculate the Lorentz transformation matrix for movement in the x direction: + + | y -γβ 0 0| + |-γβ y 0 0| + | 0 0 1 0| + | 0 0 0 1| + + where y is the Lorentz factor and β is the velocity as a fraction of c + >>> transformation_matrix(29979245) + array([[ 1.00503781, -0.10050378, 0. , 0. ], + [-0.10050378, 1.00503781, 0. , 0. ], + [ 0. , 0. , 1. , 0. ], + [ 0. , 0. , 0. , 1. ]]) + >>> transformation_matrix(19979245.2) + array([[ 1.00222811, -0.06679208, 0. , 0. ], + [-0.06679208, 1.00222811, 0. , 0. ], + [ 0. , 0. , 1. , 0. ], + [ 0. , 0. , 0. , 1. ]]) + >>> transformation_matrix(1) + array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00, + 0.00000000e+00], + [-3.33564095e-09, 1.00000000e+00, 0.00000000e+00, + 0.00000000e+00], + [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, + 0.00000000e+00], + [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, + 1.00000000e+00]]) + >>> transformation_matrix(0) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than or equal to 1! + >>> transformation_matrix(c * 1.5) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed light speed 299,792,458 [m/s]! + """ return np.array( [ [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], @@ -39,6 +135,31 @@ def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray: + """ + Calculate a Lorentz transformation for movement in the x direction given a + velocity and a four-vector for an inertial reference frame + + If no four-vector is given, then calculate the transformation symbolically + with variables + >>> transform(29979245, np.array([1, 2, 3, 4])) + array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) + >>> transform(29979245) + array([1.00503781498831*ct - 0.100503778816875*x, + -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], + dtype=object) + >>> transform(19879210.2) + array([1.0022057787097*ct - 0.066456172618675*x, + -0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z], + dtype=object) + >>> transform(299792459, np.array([1, 1, 1, 1])) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed light speed 299,792,458 [m/s]! + >>> transform(-1, np.array([1, 1, 1, 1])) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than or equal to 1! + """ # Ensure event is not empty if event is None: event = np.array([ct, x, y, z]) # Symbolic four vector @@ -65,4 +186,4 @@ sub_dict = {ct: c, x: 1, y: 1, z: 1} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)] - print(f"\n{numerical_vector}")+ print(f"\n{numerical_vector}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/lorentz_transformation_four_vector.py
Generate descriptive docstrings automatically
def focal_length_of_lens( object_distance_from_lens: float, image_distance_from_lens: float ) -> float: if object_distance_from_lens == 0 or image_distance_from_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ( (1 / image_distance_from_lens) - (1 / object_distance_from_lens) ) return focal_length def object_distance( focal_length_of_lens: float, image_distance_from_lens: float ) -> float: if image_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / image_distance_from_lens) - (1 / focal_length_of_lens)) return object_distance def image_distance( focal_length_of_lens: float, object_distance_from_lens: float ) -> float: if object_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / object_distance_from_lens) + (1 / focal_length_of_lens)) return image_distance
--- +++ @@ -1,8 +1,70 @@+""" +This module has functions which calculate focal length of lens, distance of +image from the lens and distance of object from the lens. +The above is calculated using the lens formula. + +In optics, the relationship between the distance of the image (v), +the distance of the object (u), and +the focal length (f) of the lens is given by the formula known as the Lens formula. +The Lens formula is applicable for convex as well as concave lenses. The formula +is given as follows: + +------------------- +| 1/f = 1/v + 1/u | +------------------- + +Where + f = focal length of the lens in meters. + v = distance of the image from the lens in meters. + u = distance of the object from the lens in meters. + +To make our calculations easy few assumptions are made while deriving the formula +which are important to keep in mind before solving this equation. +The assumptions are as follows: + 1. The object O is a point object lying somewhere on the principle axis. + 2. The lens is thin. + 3. The aperture of the lens taken must be small. + 4. The angles of incidence and angle of refraction should be small. + +Sign convention is a set of rules to set signs for image distance, object distance, +focal length, etc +for mathematical analysis of image formation. According to it: + 1. Object is always placed to the left of lens. + 2. All distances are measured from the optical centre of the mirror. + 3. Distances measured in the direction of the incident ray are positive and + the distances measured in the direction opposite + to that of the incident rays are negative. + 4. Distances measured along y-axis above the principal axis are positive and + that measured along y-axis below the principal + axis are negative. + +Note: Sign convention can be reversed and will still give the correct results. + +Reference for Sign convention: +https://www.toppr.com/ask/content/concept/sign-convention-for-lenses-210246/ + +Reference for assumptions: +https://testbook.com/physics/derivation-of-lens-maker-formula +""" def focal_length_of_lens( object_distance_from_lens: float, image_distance_from_lens: float ) -> float: + """ + Doctests: + >>> from math import isclose + >>> isclose(focal_length_of_lens(10,4), 6.666666666666667) + True + >>> from math import isclose + >>> isclose(focal_length_of_lens(2.7,5.8), -5.0516129032258075) + True + >>> focal_length_of_lens(0, 20) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter non zero values with respect + to the sign convention. + """ if object_distance_from_lens == 0 or image_distance_from_lens == 0: raise ValueError( @@ -17,6 +79,22 @@ def object_distance( focal_length_of_lens: float, image_distance_from_lens: float ) -> float: + """ + Doctests: + >>> from math import isclose + >>> isclose(object_distance(10,40), -13.333333333333332) + True + + >>> from math import isclose + >>> isclose(object_distance(6.2,1.5), 1.9787234042553192) + True + + >>> object_distance(0, 20) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter non zero values with respect + to the sign convention. + """ if image_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( @@ -30,9 +108,24 @@ def image_distance( focal_length_of_lens: float, object_distance_from_lens: float ) -> float: + """ + Doctests: + >>> from math import isclose + >>> isclose(image_distance(50,40), 22.22222222222222) + True + >>> from math import isclose + >>> isclose(image_distance(5.3,7.9), 3.1719696969696973) + True + + >>> object_distance(0, 20) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter non zero values with respect + to the sign convention. + """ if object_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / object_distance_from_lens) + (1 / focal_length_of_lens)) - return image_distance+ return image_distance
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/lens_formulae.py
Create structured documentation for my script
def kinetic_energy(mass: float, velocity: float) -> float: if mass < 0: raise ValueError("The mass of a body cannot be negative") return 0.5 * mass * abs(velocity) * abs(velocity) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
--- +++ @@ -1,6 +1,44 @@+""" +Find the kinetic energy of an object, given its mass and velocity. + +Description : In physics, the kinetic energy of an object is the energy that it +possesses due to its motion.It is defined as the work needed to accelerate a body of a +given mass from rest to its stated velocity.Having gained this energy during its +acceleration, the body maintains this kinetic energy unless its speed changes.The same +amount of work is done by the body when decelerating from its current speed to a state +of rest.Formally, a kinetic energy is any term in a system's Lagrangian which includes +a derivative with respect to time. + +In classical mechanics, the kinetic energy of a non-rotating object of mass m traveling +at a speed v is ½mv².In relativistic mechanics, this is a good approximation only when +v is much less than the speed of light.The standard unit of kinetic energy is the +joule, while the English unit of kinetic energy is the foot-pound. + +Reference : https://en.m.wikipedia.org/wiki/Kinetic_energy +""" def kinetic_energy(mass: float, velocity: float) -> float: + """ + Calculate kinetic energy. + + The kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv² + + >>> kinetic_energy(10,10) + 500.0 + >>> kinetic_energy(0,10) + 0.0 + >>> kinetic_energy(10,0) + 0.0 + >>> kinetic_energy(20,-20) + 4000.0 + >>> kinetic_energy(0,0) + 0.0 + >>> kinetic_energy(2,2) + 4.0 + >>> kinetic_energy(100,100) + 500000.0 + """ if mass < 0: raise ValueError("The mass of a body cannot be negative") return 0.5 * mass * abs(velocity) * abs(velocity) @@ -9,4 +47,4 @@ if __name__ == "__main__": import doctest - doctest.testmod(verbose=True)+ doctest.testmod(verbose=True)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/kinetic_energy.py
Add docstrings including usage examples
from math import pow, sqrt # noqa: A004 def validate(*values: float) -> bool: result = len(values) > 0 and all(value > 0.0 for value in values) return result def effusion_ratio(molar_mass_1: float, molar_mass_2: float) -> float | ValueError: return ( round(sqrt(molar_mass_2 / molar_mass_1), 6) if validate(molar_mass_1, molar_mass_2) else ValueError("Input Error: Molar mass values must greater than 0.") ) def first_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: return ( round(effusion_rate * sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def second_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: return ( round(effusion_rate / sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def first_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: return ( round(molar_mass / pow(effusion_rate_1 / effusion_rate_2, 2), 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def second_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: return ( round(pow(effusion_rate_1 / effusion_rate_2, 2) / molar_mass, 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) )
--- +++ @@ -1,13 +1,62 @@+""" +Title: Graham's Law of Effusion + +Description: Graham's law of effusion states that the rate of effusion of a gas is +inversely proportional to the square root of the molar mass of its particles: + +r1/r2 = sqrt(m2/m1) + +r1 = Rate of effusion for the first gas. +r2 = Rate of effusion for the second gas. +m1 = Molar mass of the first gas. +m2 = Molar mass of the second gas. + +(Description adapted from https://en.wikipedia.org/wiki/Graham%27s_law) +""" from math import pow, sqrt # noqa: A004 def validate(*values: float) -> bool: + """ + Input Parameters: + ----------------- + effusion_rate_1: Effustion rate of first gas (m^2/s, mm^2/s, etc.) + effusion_rate_2: Effustion rate of second gas (m^2/s, mm^2/s, etc.) + molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) + molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) + + Returns: + -------- + >>> validate(2.016, 4.002) + True + >>> validate(-2.016, 4.002) + False + >>> validate() + False + """ result = len(values) > 0 and all(value > 0.0 for value in values) return result def effusion_ratio(molar_mass_1: float, molar_mass_2: float) -> float | ValueError: + """ + Input Parameters: + ----------------- + molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) + molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) + + Returns: + -------- + >>> effusion_ratio(2.016, 4.002) + 1.408943 + >>> effusion_ratio(-2.016, 4.002) + ValueError('Input Error: Molar mass values must greater than 0.') + >>> effusion_ratio(2.016) + Traceback (most recent call last): + ... + TypeError: effusion_ratio() missing 1 required positional argument: 'molar_mass_2' + """ return ( round(sqrt(molar_mass_2 / molar_mass_1), 6) if validate(molar_mass_1, molar_mass_2) @@ -18,6 +67,30 @@ def first_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: + """ + Input Parameters: + ----------------- + effusion_rate: Effustion rate of second gas (m^2/s, mm^2/s, etc.) + molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) + molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) + + Returns: + -------- + >>> first_effusion_rate(1, 2.016, 4.002) + 1.408943 + >>> first_effusion_rate(-1, 2.016, 4.002) + ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') + >>> first_effusion_rate(1) + Traceback (most recent call last): + ... + TypeError: first_effusion_rate() missing 2 required positional arguments: \ +'molar_mass_1' and 'molar_mass_2' + >>> first_effusion_rate(1, 2.016) + Traceback (most recent call last): + ... + TypeError: first_effusion_rate() missing 1 required positional argument: \ +'molar_mass_2' + """ return ( round(effusion_rate * sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) @@ -30,6 +103,30 @@ def second_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: + """ + Input Parameters: + ----------------- + effusion_rate: Effustion rate of second gas (m^2/s, mm^2/s, etc.) + molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) + molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) + + Returns: + -------- + >>> second_effusion_rate(1, 2.016, 4.002) + 0.709752 + >>> second_effusion_rate(-1, 2.016, 4.002) + ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') + >>> second_effusion_rate(1) + Traceback (most recent call last): + ... + TypeError: second_effusion_rate() missing 2 required positional arguments: \ +'molar_mass_1' and 'molar_mass_2' + >>> second_effusion_rate(1, 2.016) + Traceback (most recent call last): + ... + TypeError: second_effusion_rate() missing 1 required positional argument: \ +'molar_mass_2' + """ return ( round(effusion_rate / sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) @@ -42,6 +139,30 @@ def first_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: + """ + Input Parameters: + ----------------- + molar_mass: Molar mass of the first gas (g/mol, kg/kmol, etc.) + effusion_rate_1: Effustion rate of first gas (m^2/s, mm^2/s, etc.) + effusion_rate_2: Effustion rate of second gas (m^2/s, mm^2/s, etc.) + + Returns: + -------- + >>> first_molar_mass(2, 1.408943, 0.709752) + 0.507524 + >>> first_molar_mass(-1, 2.016, 4.002) + ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') + >>> first_molar_mass(1) + Traceback (most recent call last): + ... + TypeError: first_molar_mass() missing 2 required positional arguments: \ +'effusion_rate_1' and 'effusion_rate_2' + >>> first_molar_mass(1, 2.016) + Traceback (most recent call last): + ... + TypeError: first_molar_mass() missing 1 required positional argument: \ +'effusion_rate_2' + """ return ( round(molar_mass / pow(effusion_rate_1 / effusion_rate_2, 2), 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) @@ -54,10 +175,34 @@ def second_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: + """ + Input Parameters: + ----------------- + molar_mass: Molar mass of the first gas (g/mol, kg/kmol, etc.) + effusion_rate_1: Effustion rate of first gas (m^2/s, mm^2/s, etc.) + effusion_rate_2: Effustion rate of second gas (m^2/s, mm^2/s, etc.) + + Returns: + -------- + >>> second_molar_mass(2, 1.408943, 0.709752) + 1.970351 + >>> second_molar_mass(-2, 1.408943, 0.709752) + ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') + >>> second_molar_mass(1) + Traceback (most recent call last): + ... + TypeError: second_molar_mass() missing 2 required positional arguments: \ +'effusion_rate_1' and 'effusion_rate_2' + >>> second_molar_mass(1, 2.016) + Traceback (most recent call last): + ... + TypeError: second_molar_mass() missing 1 required positional argument: \ +'effusion_rate_2' + """ return ( round(pow(effusion_rate_1 / effusion_rate_2, 2) / molar_mass, 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/grahams_law.py
Generate docstrings for exported functions
from scipy.constants import c # speed of light in vacuum (299792458 m/s) def energy_from_mass(mass: float) -> float: if mass < 0: raise ValueError("Mass can't be negative.") return mass * c**2 def mass_from_energy(energy: float) -> float: if energy < 0: raise ValueError("Energy can't be negative.") return energy / c**2 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,14 +1,71 @@+""" +Title: +Finding the energy equivalence of mass and mass equivalence of energy +by Einstein's equation. + +Description: +Einstein's mass-energy equivalence is a pivotal concept in theoretical physics. +It asserts that energy (E) and mass (m) are directly related by the speed of +light in vacuum (c) squared, as described in the equation E = mc². This means that +mass and energy are interchangeable; a mass increase corresponds to an energy increase, +and vice versa. This principle has profound implications in nuclear reactions, +explaining the release of immense energy from minuscule changes in atomic nuclei. + +Equations: +E = mc² and m = E/c², where m is mass, E is Energy, c is speed of light in vacuum. + +Reference: +https://en.wikipedia.org/wiki/Mass%E2%80%93energy_equivalence +""" from scipy.constants import c # speed of light in vacuum (299792458 m/s) def energy_from_mass(mass: float) -> float: + """ + Calculates the Energy equivalence of the Mass using E = mc² + in SI units J from Mass in kg. + + mass (float): Mass of body. + + Usage example: + >>> energy_from_mass(124.56) + 1.11948945063458e+19 + >>> energy_from_mass(320) + 2.8760165719578165e+19 + >>> energy_from_mass(0) + 0.0 + >>> energy_from_mass(-967.9) + Traceback (most recent call last): + ... + ValueError: Mass can't be negative. + + """ if mass < 0: raise ValueError("Mass can't be negative.") return mass * c**2 def mass_from_energy(energy: float) -> float: + """ + Calculates the Mass equivalence of the Energy using m = E/c² + in SI units kg from Energy in J. + + energy (float): Mass of body. + + Usage example: + >>> mass_from_energy(124.56) + 1.3859169098203872e-15 + >>> mass_from_energy(320) + 3.560480179371579e-15 + >>> mass_from_energy(0) + 0.0 + >>> mass_from_energy(-967.9) + Traceback (most recent call last): + ... + ValueError: Energy can't be negative. + + """ if energy < 0: raise ValueError("Energy can't be negative.") return energy / c**2 @@ -17,4 +74,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/mass_energy_equivalence.py
Create docstrings for all classes and functions
from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin from numpy.typing import NDArray def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: # summation of moments is zero moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) return bool(abs(sum_moments) < eps) if __name__ == "__main__": # Test to check if it works forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
--- +++ @@ -1,3 +1,6 @@+""" +Checks if a system of forces is in static equilibrium. +""" from __future__ import annotations @@ -8,6 +11,21 @@ def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: + """ + Resolves force along rectangular components. + (force, angle) => (force_x, force_y) + >>> import math + >>> force = polar_force(10, 45) + >>> math.isclose(force[0], 7.071067811865477) + True + >>> math.isclose(force[1], 7.0710678118654755) + True + >>> force = polar_force(10, 3.14, radian_mode=True) + >>> math.isclose(force[0], -9.999987317275396) + True + >>> math.isclose(force[1], 0.01592652916486828) + True + """ if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] @@ -16,6 +34,22 @@ def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: + """ + Check if a system is in equilibrium. + It takes two numpy.array objects. + forces ==> [ + [force1_x, force1_y], + [force2_x, force2_y], + ....] + location ==> [ + [x1, y1], + [x2, y2], + ....] + >>> force = array([[1, 1], [-1, 2]]) + >>> location = array([[1, 0], [10, 0]]) + >>> in_static_equilibrium(force, location) + False + """ # summation of moments is zero moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) @@ -58,4 +92,4 @@ import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/in_static_equilibrium.py
Help me document legacy Python code
from __future__ import annotations # Define the Gravitational Constant G and the function GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: product_of_mass = mass_1 * mass_2 if (force, mass_1, mass_2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Gravitational force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if mass_1 < 0 or mass_2 < 0: raise ValueError("Mass can not be negative") if force == 0: force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2) return {"force": force} elif mass_1 == 0: mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2) return {"mass_1": mass_1} elif mass_2 == 0: mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1) return {"mass_2": mass_2} elif distance == 0: distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5 return {"distance": distance} raise ValueError("One and only one argument must be 0") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,23 @@+""" +Title : Finding the value of either Gravitational Force, one of the masses or distance +provided that the other three parameters are given. + +Description : Newton's Law of Universal Gravitation explains the presence of force of +attraction between bodies having a definite mass situated at a distance. It is usually +stated as that, every particle attracts every other particle in the universe with a +force that is directly proportional to the product of their masses and inversely +proportional to the square of the distance between their centers. The publication of the +theory has become known as the "first great unification", as it marked the unification +of the previously described phenomena of gravity on Earth with known astronomical +behaviors. + +The equation for the universal gravitation is as follows: +F = (G * mass_1 * mass_2) / (distance)^2 + +Source : +- https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation +- Newton (1687) "Philosophiæ Naturalis Principia Mathematica" +""" from __future__ import annotations @@ -8,6 +28,44 @@ def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: + """ + Input Parameters + ---------------- + force : magnitude in Newtons + + mass_1 : mass in Kilograms + + mass_2 : mass in Kilograms + + distance : distance in Meters + + Returns + ------- + result : dict name, value pair of the parameter having Zero as it's value + + Returns the value of one of the parameters specified as 0, provided the values of + other parameters are given. + >>> gravitational_law(force=0, mass_1=5, mass_2=10, distance=20) + {'force': 8.342875e-12} + + >>> gravitational_law(force=7367.382, mass_1=0, mass_2=74, distance=3048) + {'mass_1': 1.385816317292268e+19} + + >>> gravitational_law(force=36337.283, mass_1=0, mass_2=0, distance=35584) + Traceback (most recent call last): + ... + ValueError: One and only one argument must be 0 + + >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584) + Traceback (most recent call last): + ... + ValueError: Mass can not be negative + + >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374) + Traceback (most recent call last): + ... + ValueError: Gravitational force can not be negative + """ product_of_mass = mass_1 * mass_2 @@ -38,4 +96,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/newtons_law_of_gravitation.py
Generate NumPy-style docstrings
def focal_length(distance_of_object: float, distance_of_image: float) -> float: if distance_of_object == 0 or distance_of_image == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ((1 / distance_of_object) + (1 / distance_of_image)) return focal_length def object_distance(focal_length: float, distance_of_image: float) -> float: if distance_of_image == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / focal_length) - (1 / distance_of_image)) return object_distance def image_distance(focal_length: float, distance_of_object: float) -> float: if distance_of_object == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / focal_length) - (1 / distance_of_object)) return image_distance
--- +++ @@ -1,6 +1,77 @@+""" +This module contains the functions to calculate the focal length, object distance +and image distance of a mirror. + +The mirror formula is an equation that relates the object distance (u), +image distance (v), and focal length (f) of a spherical mirror. +It is commonly used in optics to determine the position and characteristics +of an image formed by a mirror. It is expressed using the formulae : + +------------------- +| 1/f = 1/v + 1/u | +------------------- + +Where, +f = Focal length of the spherical mirror (metre) +v = Image distance from the mirror (metre) +u = Object distance from the mirror (metre) + + +The signs of the distances are taken with respect to the sign convention. +The sign convention is as follows: + 1) Object is always placed to the left of mirror + 2) Distances measured in the direction of the incident ray are positive + and the distances measured in the direction opposite to that of the incident + rays are negative. + 3) All distances are measured from the pole of the mirror. + + +There are a few assumptions that are made while using the mirror formulae. +They are as follows: + 1) Thin Mirror: The mirror is assumed to be thin, meaning its thickness is + negligible compared to its radius of curvature. This assumption allows + us to treat the mirror as a two-dimensional surface. + 2) Spherical Mirror: The mirror is assumed to have a spherical shape. While this + assumption may not hold exactly for all mirrors, it is a reasonable approximation + for most practical purposes. + 3) Small Angles: The angles involved in the derivation are assumed to be small. + This assumption allows us to use the small-angle approximation, where the tangent + of a small angle is approximately equal to the angle itself. It simplifies the + calculations and makes the derivation more manageable. + 4) Paraxial Rays: The mirror formula is derived using paraxial rays, which are + rays that are close to the principal axis and make small angles with it. This + assumption ensures that the rays are close enough to the principal axis, making the + calculations more accurate. + 5) Reflection and Refraction Laws: The derivation assumes that the laws of + reflection and refraction hold. + These laws state that the angle of incidence is equal to the angle of reflection + for reflection, and the incident and refracted rays lie in the same plane and + obey Snell's law for refraction. + +(Description and Assumptions adapted from +https://www.collegesearch.in/articles/mirror-formula-derivation) + +(Sign Convention adapted from +https://www.toppr.com/ask/content/concept/sign-convention-for-mirrors-210189/) + + +""" def focal_length(distance_of_object: float, distance_of_image: float) -> float: + """ + >>> from math import isclose + >>> isclose(focal_length(10, 20), 6.66666666666666) + True + >>> from math import isclose + >>> isclose(focal_length(9.5, 6.7), 3.929012346) + True + >>> focal_length(0, 20) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter non zero values with respect + to the sign convention. + """ if distance_of_object == 0 or distance_of_image == 0: raise ValueError( @@ -11,6 +82,19 @@ def object_distance(focal_length: float, distance_of_image: float) -> float: + """ + >>> from math import isclose + >>> isclose(object_distance(30, 20), -60.0) + True + >>> from math import isclose + >>> isclose(object_distance(10.5, 11.7), 102.375) + True + >>> object_distance(90, 0) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter non zero values with respect + to the sign convention. + """ if distance_of_image == 0 or focal_length == 0: raise ValueError( @@ -21,10 +105,23 @@ def image_distance(focal_length: float, distance_of_object: float) -> float: + """ + >>> from math import isclose + >>> isclose(image_distance(10, 40), 13.33333333) + True + >>> from math import isclose + >>> isclose(image_distance(1.5, 6.7), 1.932692308) + True + >>> image_distance(0, 0) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter non zero values with respect + to the sign convention. + """ if distance_of_object == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / focal_length) - (1 / distance_of_object)) - return image_distance+ return image_distance
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/mirror_formulae.py
Add concise docstrings to each method
from __future__ import annotations import random from matplotlib import animation from matplotlib import pyplot as plt # Frame rate of the animation INTERVAL = 20 # Time between time steps in seconds DELTA_TIME = INTERVAL / 1000 class Body: def __init__( self, position_x: float, position_y: float, velocity_x: float, velocity_y: float, mass: float = 1.0, size: float = 1.0, color: str = "blue", ) -> None: self.position_x = position_x self.position_y = position_y self.velocity_x = velocity_x self.velocity_y = velocity_y self.mass = mass self.size = size self.color = color @property def position(self) -> tuple[float, float]: return self.position_x, self.position_y @property def velocity(self) -> tuple[float, float]: return self.velocity_x, self.velocity_y def update_velocity( self, force_x: float, force_y: float, delta_time: float ) -> None: self.velocity_x += force_x * delta_time self.velocity_y += force_y * delta_time def update_position(self, delta_time: float) -> None: self.position_x += self.velocity_x * delta_time self.position_y += self.velocity_y * delta_time class BodySystem: def __init__( self, bodies: list[Body], gravitation_constant: float = 1.0, time_factor: float = 1.0, softening_factor: float = 0.0, ) -> None: self.bodies = bodies self.gravitation_constant = gravitation_constant self.time_factor = time_factor self.softening_factor = softening_factor def __len__(self) -> int: return len(self.bodies) def update_system(self, delta_time: float) -> None: for body1 in self.bodies: force_x = 0.0 force_y = 0.0 for body2 in self.bodies: if body1 != body2: dif_x = body2.position_x - body1.position_x dif_y = body2.position_y - body1.position_y # Calculation of the distance using Pythagoras's theorem # Extra factor due to the softening technique distance = (dif_x**2 + dif_y**2 + self.softening_factor) ** (1 / 2) # Newton's law of universal gravitation. force_x += ( self.gravitation_constant * body2.mass * dif_x / distance**3 ) force_y += ( self.gravitation_constant * body2.mass * dif_y / distance**3 ) # Update the body's velocity once all the force components have been added body1.update_velocity(force_x, force_y, delta_time * self.time_factor) # Update the positions only after all the velocities have been updated for body in self.bodies: body.update_position(delta_time * self.time_factor) def update_step( body_system: BodySystem, delta_time: float, patches: list[plt.Circle] ) -> None: # Update the positions of the bodies body_system.update_system(delta_time) # Update the positions of the patches for patch, body in zip(patches, body_system.bodies): patch.center = (body.position_x, body.position_y) def plot( title: str, body_system: BodySystem, x_start: float = -1, x_end: float = 1, y_start: float = -1, y_end: float = 1, ) -> None: fig = plt.figure() fig.canvas.manager.set_window_title(title) ax = plt.axes( xlim=(x_start, x_end), ylim=(y_start, y_end) ) # Set section to be plotted plt.gca().set_aspect("equal") # Fix aspect ratio # Each body is drawn as a patch by the plt-function patches = [ plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) for body in body_system.bodies ] for patch in patches: ax.add_patch(patch) # Function called at each step of the animation def update(frame: int) -> list[plt.Circle]: # noqa: ARG001 update_step(body_system, DELTA_TIME, patches) return patches anim = animation.FuncAnimation( # noqa: F841 fig, update, interval=INTERVAL, blit=True ) plt.show() def example_1() -> BodySystem: position_x = 0.9700436 position_y = -0.24308753 velocity_x = 0.466203685 velocity_y = 0.43236573 bodies1 = [ Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), ] return BodySystem(bodies1, time_factor=3) def example_2() -> BodySystem: moon_mass = 7.3476e22 earth_mass = 5.972e24 velocity_dif = 1022 earth_moon_distance = 384399000 gravitation_constant = 6.674e-11 # Calculation of the respective velocities so that total impulse is zero, # i.e. the two bodies together don't move moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) earth_velocity = moon_velocity - velocity_dif moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") return BodySystem([earth, moon], gravitation_constant, time_factor=1000000) def example_3() -> BodySystem: bodies = [] for _ in range(10): velocity_x = random.uniform(-0.5, 0.5) velocity_y = random.uniform(-0.5, 0.5) # Bodies are created pairwise with opposite velocities so that the # total impulse remains zero bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), velocity_x, velocity_y, size=0.05, ) ) bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), -velocity_x, -velocity_y, size=0.05, ) ) return BodySystem(bodies, 0.01, 10, 0.1) if __name__ == "__main__": plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) plot( "Moon's orbit around the earth", example_2(), -430000000, 430000000, -430000000, 430000000, ) plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)
--- +++ @@ -1,220 +1,347 @@- -from __future__ import annotations - -import random - -from matplotlib import animation -from matplotlib import pyplot as plt - -# Frame rate of the animation -INTERVAL = 20 - -# Time between time steps in seconds -DELTA_TIME = INTERVAL / 1000 - - -class Body: - def __init__( - self, - position_x: float, - position_y: float, - velocity_x: float, - velocity_y: float, - mass: float = 1.0, - size: float = 1.0, - color: str = "blue", - ) -> None: - self.position_x = position_x - self.position_y = position_y - self.velocity_x = velocity_x - self.velocity_y = velocity_y - self.mass = mass - self.size = size - self.color = color - - @property - def position(self) -> tuple[float, float]: - return self.position_x, self.position_y - - @property - def velocity(self) -> tuple[float, float]: - return self.velocity_x, self.velocity_y - - def update_velocity( - self, force_x: float, force_y: float, delta_time: float - ) -> None: - self.velocity_x += force_x * delta_time - self.velocity_y += force_y * delta_time - - def update_position(self, delta_time: float) -> None: - self.position_x += self.velocity_x * delta_time - self.position_y += self.velocity_y * delta_time - - -class BodySystem: - - def __init__( - self, - bodies: list[Body], - gravitation_constant: float = 1.0, - time_factor: float = 1.0, - softening_factor: float = 0.0, - ) -> None: - self.bodies = bodies - self.gravitation_constant = gravitation_constant - self.time_factor = time_factor - self.softening_factor = softening_factor - - def __len__(self) -> int: - return len(self.bodies) - - def update_system(self, delta_time: float) -> None: - for body1 in self.bodies: - force_x = 0.0 - force_y = 0.0 - for body2 in self.bodies: - if body1 != body2: - dif_x = body2.position_x - body1.position_x - dif_y = body2.position_y - body1.position_y - - # Calculation of the distance using Pythagoras's theorem - # Extra factor due to the softening technique - distance = (dif_x**2 + dif_y**2 + self.softening_factor) ** (1 / 2) - - # Newton's law of universal gravitation. - force_x += ( - self.gravitation_constant * body2.mass * dif_x / distance**3 - ) - force_y += ( - self.gravitation_constant * body2.mass * dif_y / distance**3 - ) - - # Update the body's velocity once all the force components have been added - body1.update_velocity(force_x, force_y, delta_time * self.time_factor) - - # Update the positions only after all the velocities have been updated - for body in self.bodies: - body.update_position(delta_time * self.time_factor) - - -def update_step( - body_system: BodySystem, delta_time: float, patches: list[plt.Circle] -) -> None: - # Update the positions of the bodies - body_system.update_system(delta_time) - - # Update the positions of the patches - for patch, body in zip(patches, body_system.bodies): - patch.center = (body.position_x, body.position_y) - - -def plot( - title: str, - body_system: BodySystem, - x_start: float = -1, - x_end: float = 1, - y_start: float = -1, - y_end: float = 1, -) -> None: - fig = plt.figure() - fig.canvas.manager.set_window_title(title) - ax = plt.axes( - xlim=(x_start, x_end), ylim=(y_start, y_end) - ) # Set section to be plotted - plt.gca().set_aspect("equal") # Fix aspect ratio - - # Each body is drawn as a patch by the plt-function - patches = [ - plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) - for body in body_system.bodies - ] - - for patch in patches: - ax.add_patch(patch) - - # Function called at each step of the animation - def update(frame: int) -> list[plt.Circle]: # noqa: ARG001 - update_step(body_system, DELTA_TIME, patches) - return patches - - anim = animation.FuncAnimation( # noqa: F841 - fig, update, interval=INTERVAL, blit=True - ) - - plt.show() - - -def example_1() -> BodySystem: - - position_x = 0.9700436 - position_y = -0.24308753 - velocity_x = 0.466203685 - velocity_y = 0.43236573 - - bodies1 = [ - Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), - Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), - Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), - ] - return BodySystem(bodies1, time_factor=3) - - -def example_2() -> BodySystem: - - moon_mass = 7.3476e22 - earth_mass = 5.972e24 - velocity_dif = 1022 - earth_moon_distance = 384399000 - gravitation_constant = 6.674e-11 - - # Calculation of the respective velocities so that total impulse is zero, - # i.e. the two bodies together don't move - moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) - earth_velocity = moon_velocity - velocity_dif - - moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") - earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") - return BodySystem([earth, moon], gravitation_constant, time_factor=1000000) - - -def example_3() -> BodySystem: - - bodies = [] - for _ in range(10): - velocity_x = random.uniform(-0.5, 0.5) - velocity_y = random.uniform(-0.5, 0.5) - - # Bodies are created pairwise with opposite velocities so that the - # total impulse remains zero - bodies.append( - Body( - random.uniform(-0.5, 0.5), - random.uniform(-0.5, 0.5), - velocity_x, - velocity_y, - size=0.05, - ) - ) - bodies.append( - Body( - random.uniform(-0.5, 0.5), - random.uniform(-0.5, 0.5), - -velocity_x, - -velocity_y, - size=0.05, - ) - ) - return BodySystem(bodies, 0.01, 10, 0.1) - - -if __name__ == "__main__": - plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) - plot( - "Moon's orbit around the earth", - example_2(), - -430000000, - 430000000, - -430000000, - 430000000, - ) - plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)+""" +In physics and astronomy, a gravitational N-body simulation is a simulation of a +dynamical system of particles under the influence of gravity. The system +consists of a number of bodies, each of which exerts a gravitational force on all +other bodies. These forces are calculated using Newton's law of universal +gravitation. The Euler method is used at each time-step to calculate the change in +velocity and position brought about by these forces. Softening is used to prevent +numerical divergences when a particle comes too close to another (and the force +goes to infinity). +(Description adapted from https://en.wikipedia.org/wiki/N-body_simulation ) +(See also http://www.shodor.org/refdesk/Resources/Algorithms/EulersMethod/ ) +""" + +from __future__ import annotations + +import random + +from matplotlib import animation +from matplotlib import pyplot as plt + +# Frame rate of the animation +INTERVAL = 20 + +# Time between time steps in seconds +DELTA_TIME = INTERVAL / 1000 + + +class Body: + def __init__( + self, + position_x: float, + position_y: float, + velocity_x: float, + velocity_y: float, + mass: float = 1.0, + size: float = 1.0, + color: str = "blue", + ) -> None: + """ + The parameters "size" & "color" are not relevant for the simulation itself, + they are only used for plotting. + """ + self.position_x = position_x + self.position_y = position_y + self.velocity_x = velocity_x + self.velocity_y = velocity_y + self.mass = mass + self.size = size + self.color = color + + @property + def position(self) -> tuple[float, float]: + return self.position_x, self.position_y + + @property + def velocity(self) -> tuple[float, float]: + return self.velocity_x, self.velocity_y + + def update_velocity( + self, force_x: float, force_y: float, delta_time: float + ) -> None: + """ + Euler algorithm for velocity + + >>> body_1 = Body(0.,0.,0.,0.) + >>> body_1.update_velocity(1.,0.,1.) + >>> body_1.velocity + (1.0, 0.0) + + >>> body_1.update_velocity(1.,0.,1.) + >>> body_1.velocity + (2.0, 0.0) + + >>> body_2 = Body(0.,0.,5.,0.) + >>> body_2.update_velocity(0.,-10.,10.) + >>> body_2.velocity + (5.0, -100.0) + + >>> body_2.update_velocity(0.,-10.,10.) + >>> body_2.velocity + (5.0, -200.0) + """ + self.velocity_x += force_x * delta_time + self.velocity_y += force_y * delta_time + + def update_position(self, delta_time: float) -> None: + """ + Euler algorithm for position + + >>> body_1 = Body(0.,0.,1.,0.) + >>> body_1.update_position(1.) + >>> body_1.position + (1.0, 0.0) + + >>> body_1.update_position(1.) + >>> body_1.position + (2.0, 0.0) + + >>> body_2 = Body(10.,10.,0.,-2.) + >>> body_2.update_position(1.) + >>> body_2.position + (10.0, 8.0) + + >>> body_2.update_position(1.) + >>> body_2.position + (10.0, 6.0) + """ + self.position_x += self.velocity_x * delta_time + self.position_y += self.velocity_y * delta_time + + +class BodySystem: + """ + This class is used to hold the bodies, the gravitation constant, the time + factor and the softening factor. The time factor is used to control the speed + of the simulation. The softening factor is used for softening, a numerical + trick for N-body simulations to prevent numerical divergences when two bodies + get too close to each other. + """ + + def __init__( + self, + bodies: list[Body], + gravitation_constant: float = 1.0, + time_factor: float = 1.0, + softening_factor: float = 0.0, + ) -> None: + self.bodies = bodies + self.gravitation_constant = gravitation_constant + self.time_factor = time_factor + self.softening_factor = softening_factor + + def __len__(self) -> int: + return len(self.bodies) + + def update_system(self, delta_time: float) -> None: + """ + For each body, loop through all other bodies to calculate the total + force they exert on it. Use that force to update the body's velocity. + + >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) + >>> len(body_system_1) + 2 + >>> body_system_1.update_system(1) + >>> body_system_1.bodies[0].position + (0.01, 0.0) + >>> body_system_1.bodies[0].velocity + (0.01, 0.0) + + >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) + >>> body_system_2.update_system(1) + >>> body_system_2.bodies[0].position + (-9.0, 0.0) + >>> body_system_2.bodies[0].velocity + (0.1, 0.0) + """ + for body1 in self.bodies: + force_x = 0.0 + force_y = 0.0 + for body2 in self.bodies: + if body1 != body2: + dif_x = body2.position_x - body1.position_x + dif_y = body2.position_y - body1.position_y + + # Calculation of the distance using Pythagoras's theorem + # Extra factor due to the softening technique + distance = (dif_x**2 + dif_y**2 + self.softening_factor) ** (1 / 2) + + # Newton's law of universal gravitation. + force_x += ( + self.gravitation_constant * body2.mass * dif_x / distance**3 + ) + force_y += ( + self.gravitation_constant * body2.mass * dif_y / distance**3 + ) + + # Update the body's velocity once all the force components have been added + body1.update_velocity(force_x, force_y, delta_time * self.time_factor) + + # Update the positions only after all the velocities have been updated + for body in self.bodies: + body.update_position(delta_time * self.time_factor) + + +def update_step( + body_system: BodySystem, delta_time: float, patches: list[plt.Circle] +) -> None: + """ + Updates the body-system and applies the change to the patch-list used for plotting + + >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) + >>> patches_1 = [plt.Circle((body.position_x, body.position_y), body.size, + ... fc=body.color)for body in body_system_1.bodies] #doctest: +ELLIPSIS + >>> update_step(body_system_1, 1, patches_1) + >>> patches_1[0].center + (0.01, 0.0) + + >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) + >>> patches_2 = [plt.Circle((body.position_x, body.position_y), body.size, + ... fc=body.color)for body in body_system_2.bodies] #doctest: +ELLIPSIS + >>> update_step(body_system_2, 1, patches_2) + >>> patches_2[0].center + (-9.0, 0.0) + """ + # Update the positions of the bodies + body_system.update_system(delta_time) + + # Update the positions of the patches + for patch, body in zip(patches, body_system.bodies): + patch.center = (body.position_x, body.position_y) + + +def plot( + title: str, + body_system: BodySystem, + x_start: float = -1, + x_end: float = 1, + y_start: float = -1, + y_end: float = 1, +) -> None: + """ + Utility function to plot how the given body-system evolves over time. + No doctest provided since this function does not have a return value. + """ + fig = plt.figure() + fig.canvas.manager.set_window_title(title) + ax = plt.axes( + xlim=(x_start, x_end), ylim=(y_start, y_end) + ) # Set section to be plotted + plt.gca().set_aspect("equal") # Fix aspect ratio + + # Each body is drawn as a patch by the plt-function + patches = [ + plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) + for body in body_system.bodies + ] + + for patch in patches: + ax.add_patch(patch) + + # Function called at each step of the animation + def update(frame: int) -> list[plt.Circle]: # noqa: ARG001 + update_step(body_system, DELTA_TIME, patches) + return patches + + anim = animation.FuncAnimation( # noqa: F841 + fig, update, interval=INTERVAL, blit=True + ) + + plt.show() + + +def example_1() -> BodySystem: + """ + Example 1: figure-8 solution to the 3-body-problem + This example can be seen as a test of the implementation: given the right + initial conditions, the bodies should move in a figure-8. + (initial conditions taken from http://www.artcompsci.org/vol_1/v1_web/node56.html) + >>> body_system = example_1() + >>> len(body_system) + 3 + """ + + position_x = 0.9700436 + position_y = -0.24308753 + velocity_x = 0.466203685 + velocity_y = 0.43236573 + + bodies1 = [ + Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), + Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), + Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), + ] + return BodySystem(bodies1, time_factor=3) + + +def example_2() -> BodySystem: + """ + Example 2: Moon's orbit around the earth + This example can be seen as a test of the implementation: given the right + initial conditions, the moon should orbit around the earth as it actually does. + (mass, velocity and distance taken from https://en.wikipedia.org/wiki/Earth + and https://en.wikipedia.org/wiki/Moon) + No doctest provided since this function does not have a return value. + """ + + moon_mass = 7.3476e22 + earth_mass = 5.972e24 + velocity_dif = 1022 + earth_moon_distance = 384399000 + gravitation_constant = 6.674e-11 + + # Calculation of the respective velocities so that total impulse is zero, + # i.e. the two bodies together don't move + moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) + earth_velocity = moon_velocity - velocity_dif + + moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") + earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") + return BodySystem([earth, moon], gravitation_constant, time_factor=1000000) + + +def example_3() -> BodySystem: + """ + Example 3: Random system with many bodies. + No doctest provided since this function does not have a return value. + """ + + bodies = [] + for _ in range(10): + velocity_x = random.uniform(-0.5, 0.5) + velocity_y = random.uniform(-0.5, 0.5) + + # Bodies are created pairwise with opposite velocities so that the + # total impulse remains zero + bodies.append( + Body( + random.uniform(-0.5, 0.5), + random.uniform(-0.5, 0.5), + velocity_x, + velocity_y, + size=0.05, + ) + ) + bodies.append( + Body( + random.uniform(-0.5, 0.5), + random.uniform(-0.5, 0.5), + -velocity_x, + -velocity_y, + size=0.05, + ) + ) + return BodySystem(bodies, 0.01, 10, 0.1) + + +if __name__ == "__main__": + plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) + plot( + "Moon's orbit around the earth", + example_2(), + -430000000, + 430000000, + -430000000, + 430000000, + ) + plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/n_body_simulation.py
Provide clean and structured docstrings
UNIVERSAL_GAS_CONSTANT = 8.314462 # Unit - J mol-1 K-1 def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure def temperature_of_gas_system(moles: float, volume: float, pressure: float) -> float: if moles < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (moles * UNIVERSAL_GAS_CONSTANT) def moles_of_gas_system(kelvin: float, volume: float, pressure: float) -> float: if kelvin < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (kelvin * UNIVERSAL_GAS_CONSTANT) if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -1,20 +1,69 @@+""" +The ideal gas law, also called the general gas equation, is the +equation of state of a hypothetical ideal gas. It is a good approximation +of the behavior of many gases under many conditions, although it has +several limitations. It was first stated by Benoît Paul Émile Clapeyron +in 1834 as a combination of the empirical Boyle's law, Charles's law, +Avogadro's law, and Gay-Lussac's law.[1] The ideal gas law is often written +in an empirical form: + ------------ + | PV = nRT | + ------------ +P = Pressure (Pa) +V = Volume (m^3) +n = Amount of substance (mol) +R = Universal gas constant +T = Absolute temperature (Kelvin) + +(Description adapted from https://en.wikipedia.org/wiki/Ideal_gas_law ) +""" UNIVERSAL_GAS_CONSTANT = 8.314462 # Unit - J mol-1 K-1 def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float: + """ + >>> pressure_of_gas_system(2, 100, 5) + 332.57848 + >>> pressure_of_gas_system(0.5, 273, 0.004) + 283731.01575 + >>> pressure_of_gas_system(3, -0.46, 23.5) + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter positive value. + """ if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float: + """ + >>> volume_of_gas_system(2, 100, 5) + 332.57848 + >>> volume_of_gas_system(0.5, 273, 0.004) + 283731.01575 + >>> volume_of_gas_system(3, -0.46, 23.5) + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter positive value. + """ if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure def temperature_of_gas_system(moles: float, volume: float, pressure: float) -> float: + """ + >>> temperature_of_gas_system(2, 100, 5) + 30.068090996146232 + >>> temperature_of_gas_system(11, 5009, 1000) + 54767.66101807144 + >>> temperature_of_gas_system(3, -0.46, 23.5) + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter positive value. + """ if moles < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") @@ -22,6 +71,16 @@ def moles_of_gas_system(kelvin: float, volume: float, pressure: float) -> float: + """ + >>> moles_of_gas_system(100, 5, 10) + 0.06013618199229246 + >>> moles_of_gas_system(110, 5009, 1000) + 5476.766101807144 + >>> moles_of_gas_system(3, -0.46, 23.5) + Traceback (most recent call last): + ... + ValueError: Invalid inputs. Enter positive value. + """ if kelvin < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") @@ -31,4 +90,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/ideal_gas_law.py
Generate missing documentation strings
PLANCK_CONSTANT_JS = 6.6261 * pow(10, -34) # in SI (Js) PLANCK_CONSTANT_EVS = 4.1357 * pow(10, -15) # in eVs def maximum_kinetic_energy( frequency: float, work_function: float, in_ev: bool = False ) -> float: if frequency < 0: raise ValueError("Frequency can't be negative.") if in_ev: return max(PLANCK_CONSTANT_EVS * frequency - work_function, 0) return max(PLANCK_CONSTANT_JS * frequency - work_function, 0) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,19 +1,67 @@- -PLANCK_CONSTANT_JS = 6.6261 * pow(10, -34) # in SI (Js) -PLANCK_CONSTANT_EVS = 4.1357 * pow(10, -15) # in eVs - - -def maximum_kinetic_energy( - frequency: float, work_function: float, in_ev: bool = False -) -> float: - if frequency < 0: - raise ValueError("Frequency can't be negative.") - if in_ev: - return max(PLANCK_CONSTANT_EVS * frequency - work_function, 0) - return max(PLANCK_CONSTANT_JS * frequency - work_function, 0) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +The photoelectric effect is the emission of electrons when electromagnetic radiation , +such as light, hits a material. Electrons emitted in this manner are called +photoelectrons. + +In 1905, Einstein proposed a theory of the photoelectric effect using a concept that +light consists of tiny packets of energy known as photons or light quanta. Each packet +carries energy hv that is proportional to the frequency v of the corresponding +electromagnetic wave. The proportionality constant h has become known as the +Planck constant. In the range of kinetic energies of the electrons that are removed from +their varying atomic bindings by the absorption of a photon of energy hv, the highest +kinetic energy K_max is : + +K_max = hv-W + +Here, W is the minimum energy required to remove an electron from the surface of the +material. It is called the work function of the surface + +Reference: https://en.wikipedia.org/wiki/Photoelectric_effect + +""" + +PLANCK_CONSTANT_JS = 6.6261 * pow(10, -34) # in SI (Js) +PLANCK_CONSTANT_EVS = 4.1357 * pow(10, -15) # in eVs + + +def maximum_kinetic_energy( + frequency: float, work_function: float, in_ev: bool = False +) -> float: + """ + Calculates the maximum kinetic energy of emitted electron from the surface. + if the maximum kinetic energy is zero then no electron will be emitted + or given electromagnetic wave frequency is small. + + frequency (float): Frequency of electromagnetic wave. + work_function (float): Work function of the surface. + in_ev (optional)(bool): Pass True if values are in eV. + + Usage example: + >>> maximum_kinetic_energy(1000000,2) + 0 + >>> maximum_kinetic_energy(1000000,2,True) + 0 + >>> maximum_kinetic_energy(10000000000000000,2,True) + 39.357000000000006 + >>> maximum_kinetic_energy(-9,20) + Traceback (most recent call last): + ... + ValueError: Frequency can't be negative. + + >>> maximum_kinetic_energy(1000,"a") + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for -: 'float' and 'str' + + """ + if frequency < 0: + raise ValueError("Frequency can't be negative.") + if in_ev: + return max(PLANCK_CONSTANT_EVS * frequency - work_function, 0) + return max(PLANCK_CONSTANT_JS * frequency - work_function, 0) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/photoelectric_effect.py
Generate docstrings with parameter types
from math import pi from scipy.constants import g def period_of_pendulum(length: float) -> float: if length < 0: raise ValueError("The length should be non-negative") return 2 * pi * (length / g) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,26 @@+""" +Title : Computing the time period of a simple pendulum + +The simple pendulum is a mechanical system that sways or moves in an +oscillatory motion. The simple pendulum comprises of a small bob of +mass m suspended by a thin string of length L and secured to a platform +at its upper end. Its motion occurs in a vertical plane and is mainly +driven by gravitational force. The period of the pendulum depends on the +length of the string and the amplitude (the maximum angle) of oscillation. +However, the effect of the amplitude can be ignored if the amplitude is +small. It should be noted that the period does not depend on the mass of +the bob. + +For small amplitudes, the period of a simple pendulum is given by the +following approximation: +T ≈ 2π * √(L / g) + +where: +L = length of string from which the bob is hanging (in m) +g = acceleration due to gravity (approx 9.8 m/s²) + +Reference : https://byjus.com/jee/simple-pendulum/ +""" from math import pi @@ -5,6 +28,20 @@ def period_of_pendulum(length: float) -> float: + """ + >>> period_of_pendulum(1.23) + 2.2252155506257845 + >>> period_of_pendulum(2.37) + 3.0888278441908574 + >>> period_of_pendulum(5.63) + 4.76073193364765 + >>> period_of_pendulum(-12) + Traceback (most recent call last): + ... + ValueError: The length should be non-negative + >>> period_of_pendulum(0) + 0.0 + """ if length < 0: raise ValueError("The length should be non-negative") return 2 * pi * (length / g) ** 0.5 @@ -13,4 +50,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/period_of_pendulum.py
Help me comply with documentation standards
def perfect_cube(n: int) -> bool: val = n ** (1 / 3) return (val * val * val) == n def perfect_cube_binary_search(n: int) -> bool: if not isinstance(n, int): raise TypeError("perfect_cube_binary_search() only accepts integers") if n < 0: n = -n left = 0 right = n while left <= right: mid = left + (right - left) // 2 if mid * mid * mid == n: return True elif mid * mid * mid < n: left = mid + 1 else: right = mid - 1 return False if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,9 +1,37 @@ def perfect_cube(n: int) -> bool: + """ + Check if a number is a perfect cube or not. + + >>> perfect_cube(27) + True + >>> perfect_cube(4) + False + """ val = n ** (1 / 3) return (val * val * val) == n def perfect_cube_binary_search(n: int) -> bool: + """ + Check if a number is a perfect cube or not using binary search. + Time complexity : O(Log(n)) + Space complexity: O(1) + + >>> perfect_cube_binary_search(27) + True + >>> perfect_cube_binary_search(64) + True + >>> perfect_cube_binary_search(4) + False + >>> perfect_cube_binary_search("a") + Traceback (most recent call last): + ... + TypeError: perfect_cube_binary_search() only accepts integers + >>> perfect_cube_binary_search(0.1) + Traceback (most recent call last): + ... + TypeError: perfect_cube_binary_search() only accepts integers + """ if not isinstance(n, int): raise TypeError("perfect_cube_binary_search() only accepts integers") if n < 0: @@ -24,4 +52,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/perfect_cube.py
Add docstrings to meet PEP guidelines
UNIVERSAL_GAS_CONSTANT = 8.3144598 def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float: if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example temperature = 300 molar_mass = 28 vrms = rms_speed_of_molecule(temperature, molar_mass) print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")
--- +++ @@ -1,8 +1,35 @@+""" +The root-mean-square speed is essential in measuring the average speed of particles +contained in a gas, defined as, + ----------------- + | Vrms = √3RT/M | + ----------------- + +In Kinetic Molecular Theory, gasified particles are in a condition of constant random +motion; each particle moves at a completely different pace, perpetually clashing and +changing directions consistently velocity is used to describe the movement of gas +particles, thereby taking into account both speed and direction. Although the velocity +of gaseous particles is constantly changing, the distribution of velocities does not +change. +We cannot gauge the velocity of every individual particle, thus we frequently reason +in terms of the particles average behavior. Particles moving in opposite directions +have velocities of opposite signs. Since gas particles are in random motion, it's +plausible that there'll be about as several moving in one direction as within the other +way, which means that the average velocity for a collection of gas particles equals +zero; as this value is unhelpful, the average of velocities can be determined using an +alternative method. +""" UNIVERSAL_GAS_CONSTANT = 8.3144598 def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float: + """ + >>> rms_speed_of_molecule(100, 2) + 35.315279554323226 + >>> rms_speed_of_molecule(273, 12) + 23.821458421977443 + """ if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: @@ -21,4 +48,4 @@ temperature = 300 molar_mass = 28 vrms = rms_speed_of_molecule(temperature, molar_mass) - print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")+ print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/rms_speed_of_molecule.py
Add clean documentation to messy code
def reynolds_number( density: float, velocity: float, diameter: float, viscosity: float ) -> float: if density <= 0 or diameter <= 0 or viscosity <= 0: raise ValueError( "please ensure that density, diameter and viscosity are positive" ) return (density * abs(velocity) * diameter) / viscosity if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,54 @@+""" +Title : computing the Reynolds number to find + out the type of flow (laminar or turbulent) + +Reynolds number is a dimensionless quantity that is used to determine +the type of flow pattern as laminar or turbulent while flowing through a +pipe. Reynolds number is defined by the ratio of inertial forces to that of +viscous forces. + +R = Inertial Forces / Viscous Forces +R = (p * V * D)/μ + +where : +p = Density of fluid (in Kg/m^3) +D = Diameter of pipe through which fluid flows (in m) +V = Velocity of flow of the fluid (in m/s) +μ = Viscosity of the fluid (in Ns/m^2) + +If the Reynolds number calculated is high (greater than 2000), then the +flow through the pipe is said to be turbulent. If Reynolds number is low +(less than 2000), the flow is said to be laminar. Numerically, these are +acceptable values, although in general the laminar and turbulent flows +are classified according to a range. Laminar flow falls below Reynolds +number of 1100 and turbulent falls in a range greater than 2200. +Laminar flow is the type of flow in which the fluid travels smoothly in +regular paths. Conversely, turbulent flow isn't smooth and follows an +irregular path with lots of mixing. + +Reference : https://byjus.com/physics/reynolds-number/ +""" def reynolds_number( density: float, velocity: float, diameter: float, viscosity: float ) -> float: + """ + >>> reynolds_number(900, 2.5, 0.05, 0.4) + 281.25 + >>> reynolds_number(450, 3.86, 0.078, 0.23) + 589.0695652173912 + >>> reynolds_number(234, -4.5, 0.3, 0.44) + 717.9545454545454 + >>> reynolds_number(-90, 2, 0.045, 1) + Traceback (most recent call last): + ... + ValueError: please ensure that density, diameter and viscosity are positive + >>> reynolds_number(0, 2, -0.4, -2) + Traceback (most recent call last): + ... + ValueError: please ensure that density, diameter and viscosity are positive + """ if density <= 0 or diameter <= 0 or viscosity <= 0: raise ValueError( @@ -14,4 +60,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/reynolds_number.py
Write docstrings for data processing functions
def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: force = 0.0 try: force = mass * acceleration except Exception: return -0.0 return force if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) print("The force is ", force, "N")
--- +++ @@ -1,6 +1,76 @@+r""" +Description: + Newton's second law of motion pertains to the behavior of objects for which + all existing forces are not balanced. + The second law states that the acceleration of an object is dependent upon + two variables - the net force acting upon the object and the mass of the object. + The acceleration of an object depends directly + upon the net force acting upon the object, + and inversely upon the mass of the object. + As the force acting upon an object is increased, + the acceleration of the object is increased. + As the mass of an object is increased, the acceleration of the object is decreased. + +Source: https://www.physicsclassroom.com/class/newtlaws/Lesson-3/Newton-s-Second-Law + +Formulation: F_net = m • a + +Diagrammatic Explanation:: + + Forces are unbalanced + | + | + | + V + There is acceleration + /\ + / \ + / \ + / \ + / \ + / \ + / \ + __________________ ____________________ + | The acceleration | | The acceleration | + | depends directly | | depends inversely | + | on the net force | | upon the object's | + | | | mass | + |__________________| |____________________| + +Units: 1 Newton = 1 kg • meters/seconds^2 + +How to use? + +Inputs:: + + ______________ _____________________ ___________ + | Name | Units | Type | + |--------------|---------------------|-----------| + | mass | in kgs | float | + |--------------|---------------------|-----------| + | acceleration | in meters/seconds^2 | float | + |______________|_____________________|___________| + +Output:: + + ______________ _______________________ ___________ + | Name | Units | Type | + |--------------|-----------------------|-----------| + | force | in Newtons | float | + |______________|_______________________|___________| + +""" def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: + """ + Calculates force from `mass` and `acceleration` + + >>> newtons_second_law_of_motion(10, 10) + 100 + >>> newtons_second_law_of_motion(2.0, 1) + 2.0 + """ force = 0.0 try: force = mass * acceleration @@ -19,4 +89,4 @@ mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) - print("The force is ", force, "N")+ print("The force is ", force, "N")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/newtons_second_law_of_motion.py
Add standardized docstrings across the file
def solution(n: int = 1000) -> int: total = 0 terms = (n - 1) // 3 total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P. terms = (n - 1) // 5 total += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 total -= ((terms) * (30 + (terms - 1) * 15)) // 2 return total if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,28 @@+""" +Project Euler Problem 1: https://projecteuler.net/problem=1 + +Multiples of 3 and 5 + +If we list all the natural numbers below 10 that are multiples of 3 or 5, +we get 3, 5, 6 and 9. The sum of these multiples is 23. + +Find the sum of all the multiples of 3 or 5 below 1000. +""" def solution(n: int = 1000) -> int: + """ + Returns the sum of all the multiples of 3 or 5 below n. + + >>> solution(3) + 0 + >>> solution(4) + 3 + >>> solution(10) + 23 + >>> solution(600) + 83700 + """ total = 0 terms = (n - 1) // 3 @@ -13,4 +35,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_001/sol2.py
Please document this code using docstrings
def speed_of_sound_in_a_fluid(density: float, bulk_modulus: float) -> float: if density <= 0: raise ValueError("Impossible fluid density") if bulk_modulus <= 0: raise ValueError("Impossible bulk modulus") return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,38 @@+""" +Title : Calculating the speed of sound + +Description : + The speed of sound (c) is the speed that a sound wave travels per unit time (m/s). + During propagation, the sound wave propagates through an elastic medium. + + Sound propagates as longitudinal waves in liquids and gases and as transverse waves + in solids. This file calculates the speed of sound in a fluid based on its bulk + module and density. + + Equation for the speed of sound in a fluid: + c_fluid = sqrt(K_s / p) + + c_fluid: speed of sound in fluid + K_s: isentropic bulk modulus + p: density of fluid + +Source : https://en.wikipedia.org/wiki/Speed_of_sound +""" def speed_of_sound_in_a_fluid(density: float, bulk_modulus: float) -> float: + """ + Calculates the speed of sound in a fluid from its density and bulk modulus + + Examples: + Example 1 --> Water 20°C: bulk_modulus= 2.15MPa, density=998kg/m³ + Example 2 --> Mercury 20°C: bulk_modulus= 28.5MPa, density=13600kg/m³ + + >>> speed_of_sound_in_a_fluid(bulk_modulus=2.15e9, density=998) + 1467.7563207952705 + >>> speed_of_sound_in_a_fluid(bulk_modulus=28.5e9, density=13600) + 1447.614670861731 + """ if density <= 0: raise ValueError("Impossible fluid density") @@ -13,4 +45,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/speed_of_sound.py
Add detailed docstrings explaining each function
def solution(n: int = 1000) -> int: return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,9 +1,33 @@+""" +Project Euler Problem 1: https://projecteuler.net/problem=1 + +Multiples of 3 and 5 + +If we list all the natural numbers below 10 that are multiples of 3 or 5, +we get 3, 5, 6 and 9. The sum of these multiples is 23. + +Find the sum of all the multiples of 3 or 5 below 1000. +""" def solution(n: int = 1000) -> int: + """ + Returns the sum of all the multiples of 3 or 5 below n. + + >>> solution(3) + 0 + >>> solution(4) + 3 + >>> solution(10) + 23 + >>> solution(600) + 83700 + >>> solution(-7) + 0 + """ return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0) if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_001/sol1.py
Write proper docstrings for these functions
# import the constants R and pi from the scipy.constants library from scipy.constants import R, pi def avg_speed_of_molecule(temperature: float, molar_mass: float) -> float: if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass should be greater than 0 kg/mol") return (8 * R * temperature / (pi * molar_mass)) ** 0.5 def mps_speed_of_molecule(temperature: float, molar_mass: float) -> float: if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass should be greater than 0 kg/mol") return (2 * R * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,9 +1,76 @@+""" +The root-mean-square, average and most probable speeds of gas molecules are +derived from the Maxwell-Boltzmann distribution. The Maxwell-Boltzmann +distribution is a probability distribution that describes the distribution of +speeds of particles in an ideal gas. + +The distribution is given by the following equation:: + + ------------------------------------------------- + | f(v) = (M/2πRT)^(3/2) * 4πv^2 * e^(-Mv^2/2RT) | + ------------------------------------------------- + +where: + * ``f(v)`` is the fraction of molecules with a speed ``v`` + * ``M`` is the molar mass of the gas in kg/mol + * ``R`` is the gas constant + * ``T`` is the absolute temperature + +More information about the Maxwell-Boltzmann distribution can be found here: +https://en.wikipedia.org/wiki/Maxwell%E2%80%93Boltzmann_distribution + +The average speed can be calculated by integrating the Maxwell-Boltzmann distribution +from 0 to infinity and dividing by the total number of molecules. The result is:: + + ---------------------- + | v_avg = √(8RT/πM) | + ---------------------- + +The most probable speed is the speed at which the Maxwell-Boltzmann distribution +is at its maximum. This can be found by differentiating the Maxwell-Boltzmann +distribution with respect to ``v`` and setting the result equal to zero. The result is:: + + ---------------------- + | v_mp = √(2RT/M) | + ---------------------- + +The root-mean-square speed is another measure of the average speed +of the molecules in a gas. It is calculated by taking the square root +of the average of the squares of the speeds of the molecules. The result is:: + + ---------------------- + | v_rms = √(3RT/M) | + ---------------------- + +Here we have defined functions to calculate the average and +most probable speeds of molecules in a gas given the +temperature and molar mass of the gas. +""" # import the constants R and pi from the scipy.constants library from scipy.constants import R, pi def avg_speed_of_molecule(temperature: float, molar_mass: float) -> float: + """ + Takes the temperature (in K) and molar mass (in kg/mol) of a gas + and returns the average speed of a molecule in the gas (in m/s). + + Examples: + + >>> avg_speed_of_molecule(273, 0.028) # nitrogen at 273 K + 454.3488755062257 + >>> avg_speed_of_molecule(300, 0.032) # oxygen at 300 K + 445.5257273433045 + >>> avg_speed_of_molecule(-273, 0.028) # invalid temperature + Traceback (most recent call last): + ... + Exception: Absolute temperature cannot be less than 0 K + >>> avg_speed_of_molecule(273, 0) # invalid molar mass + Traceback (most recent call last): + ... + Exception: Molar mass should be greater than 0 kg/mol + """ if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") @@ -13,6 +80,25 @@ def mps_speed_of_molecule(temperature: float, molar_mass: float) -> float: + """ + Takes the temperature (in K) and molar mass (in kg/mol) of a gas + and returns the most probable speed of a molecule in the gas (in m/s). + + Examples: + + >>> mps_speed_of_molecule(273, 0.028) # nitrogen at 273 K + 402.65620702280023 + >>> mps_speed_of_molecule(300, 0.032) # oxygen at 300 K + 394.8368955535605 + >>> mps_speed_of_molecule(-273, 0.028) # invalid temperature + Traceback (most recent call last): + ... + Exception: Absolute temperature cannot be less than 0 K + >>> mps_speed_of_molecule(273, 0) # invalid molar mass + Traceback (most recent call last): + ... + Exception: Molar mass should be greater than 0 kg/mol + """ if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") @@ -24,4 +110,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/speeds_of_gas_molecules.py
Write docstrings for data processing functions
def solution(n: int = 1000) -> int: a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,28 @@+""" +Project Euler Problem 1: https://projecteuler.net/problem=1 + +Multiples of 3 and 5 + +If we list all the natural numbers below 10 that are multiples of 3 or 5, +we get 3, 5, 6 and 9. The sum of these multiples is 23. + +Find the sum of all the multiples of 3 or 5 below 1000. +""" def solution(n: int = 1000) -> int: + """ + Returns the sum of all the multiples of 3 or 5 below n. + + >>> solution(3) + 0 + >>> solution(4) + 3 + >>> solution(10) + 23 + >>> solution(600) + 83700 + """ a = 3 result = 0 @@ -14,4 +36,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_001/sol6.py
Add docstrings to incomplete code
def solution(n: int = 1000) -> int: xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,28 @@+""" +Project Euler Problem 1: https://projecteuler.net/problem=1 + +Multiples of 3 and 5 + +If we list all the natural numbers below 10 that are multiples of 3 or 5, +we get 3, 5, 6 and 9. The sum of these multiples is 23. + +Find the sum of all the multiples of 3 or 5 below 1000. +""" def solution(n: int = 1000) -> int: + """ + Returns the sum of all the multiples of 3 or 5 below n. + + >>> solution(3) + 0 + >>> solution(4) + 3 + >>> solution(10) + 23 + >>> solution(600) + 83700 + """ xmulti = [] zmulti = [] @@ -27,4 +49,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_001/sol4.py
Improve my code by adding docstrings
def solution(n: int = 1000) -> int: return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,9 +1,32 @@+""" +Project Euler Problem 1: https://projecteuler.net/problem=1 + +Multiples of 3 and 5 + +If we list all the natural numbers below 10 that are multiples of 3 or 5, +we get 3, 5, 6 and 9. The sum of these multiples is 23. + +Find the sum of all the multiples of 3 or 5 below 1000. +""" def solution(n: int = 1000) -> int: + """ + Returns the sum of all the multiples of 3 or 5 below n. + A straightforward pythonic solution using list comprehension. + + >>> solution(3) + 0 + >>> solution(4) + 3 + >>> solution(10) + 23 + >>> solution(600) + 83700 + """ return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_001/sol5.py
Fully document this Python code with docstrings
from scipy.constants import g def terminal_velocity( mass: float, density: float, area: float, drag_coefficient: float ) -> float: if mass <= 0 or density <= 0 or area <= 0 or drag_coefficient <= 0: raise ValueError( "mass, density, area and the drag coefficient all need to be positive" ) return ((2 * mass * g) / (density * area * drag_coefficient)) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,25 @@+""" +Title : Computing the terminal velocity of an object falling + through a fluid. + +Terminal velocity is defined as the highest velocity attained by an +object falling through a fluid. It is observed when the sum of drag force +and buoyancy is equal to the downward gravity force acting on the +object. The acceleration of the object is zero as the net force acting on +the object is zero. + +Vt = ((2 * m * g)/(p * A * Cd))^0.5 + +where : +Vt = Terminal velocity (in m/s) +m = Mass of the falling object (in Kg) +g = Acceleration due to gravity (value taken : imported from scipy) +p = Density of the fluid through which the object is falling (in Kg/m^3) +A = Projected area of the object (in m^2) +Cd = Drag coefficient (dimensionless) + +Reference : https://byjus.com/physics/derivation-of-terminal-velocity/ +""" from scipy.constants import g @@ -5,6 +27,26 @@ def terminal_velocity( mass: float, density: float, area: float, drag_coefficient: float ) -> float: + """ + >>> terminal_velocity(1, 25, 0.6, 0.77) + 1.3031197996044768 + >>> terminal_velocity(2, 100, 0.45, 0.23) + 1.9467947148674276 + >>> terminal_velocity(5, 50, 0.2, 0.5) + 4.428690551393267 + >>> terminal_velocity(-5, 50, -0.2, -2) + Traceback (most recent call last): + ... + ValueError: mass, density, area and the drag coefficient all need to be positive + >>> terminal_velocity(3, -20, -1, 2) + Traceback (most recent call last): + ... + ValueError: mass, density, area and the drag coefficient all need to be positive + >>> terminal_velocity(-2, -1, -0.44, -1) + Traceback (most recent call last): + ... + ValueError: mass, density, area and the drag coefficient all need to be positive + """ if mass <= 0 or density <= 0 or area <= 0 or drag_coefficient <= 0: raise ValueError( "mass, density, area and the drag coefficient all need to be positive" @@ -15,4 +57,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/terminal_velocity.py
Add structured docstrings to improve clarity
def solution(n: int = 1000) -> int: result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,28 @@+""" +Project Euler Problem 1: https://projecteuler.net/problem=1 + +Multiples of 3 and 5 + +If we list all the natural numbers below 10 that are multiples of 3 or 5, +we get 3, 5, 6 and 9. The sum of these multiples is 23. + +Find the sum of all the multiples of 3 or 5 below 1000. +""" def solution(n: int = 1000) -> int: + """ + Returns the sum of all the multiples of 3 or 5 below n. + + >>> solution(3) + 0 + >>> solution(4) + 3 + >>> solution(10) + 23 + >>> solution(600) + 83700 + """ result = 0 for i in range(n): @@ -10,4 +32,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_001/sol7.py
Add docstrings to make code maintainable
def rainfall_intensity( coefficient_k: float, coefficient_a: float, coefficient_b: float, coefficient_c: float, return_period: float, duration: float, ) -> float: if ( coefficient_k <= 0 or coefficient_a <= 0 or coefficient_b <= 0 or coefficient_c <= 0 or return_period <= 0 or duration <= 0 ): raise ValueError("All parameters must be positive.") intensity = (coefficient_k * (return_period**coefficient_a)) / ( (duration + coefficient_b) ** coefficient_c ) return intensity if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,17 @@+""" +Rainfall Intensity +================== +This module contains functions to calculate the intensity of +a rainfall event for a given duration and return period. + +This function uses the Sherman intensity-duration-frequency curve. + +References +---------- +- Aparicio, F. (1997): Fundamentos de Hidrología de Superficie. + Balderas, México, Limusa. 303 p. +- https://en.wikipedia.org/wiki/Intensity-duration-frequency_curve +""" def rainfall_intensity( @@ -8,6 +22,106 @@ return_period: float, duration: float, ) -> float: + """ + Calculate the intensity of a rainfall event for a given duration and return period. + It's based on the Sherman intensity-duration-frequency curve: + + I = k * T^a / (D + b)^c + + where: + I = Intensity of the rainfall event [mm/h] + k, a, b, c = Coefficients obtained through statistical distribution adjust + T = Return period in years + D = Rainfall event duration in minutes + + Parameters + ---------- + coefficient_k : float + Coefficient obtained through statistical distribution adjust. + coefficient_a : float + Coefficient obtained through statistical distribution adjust. + coefficient_b : float + Coefficient obtained through statistical distribution adjust. + coefficient_c : float + Coefficient obtained through statistical distribution adjust. + return_period : float + Return period in years. + duration : float + Rainfall event duration in minutes. + + Returns + ------- + intensity : float + Intensity of the rainfall event in mm/h. + + Raises + ------ + ValueError + If any of the parameters are not positive. + + Examples + -------- + + >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 10, 60) + 49.83339231138578 + + >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 10, 30) + 77.36319588106228 + + >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 5, 60) + 43.382487747633625 + + >>> rainfall_intensity(0, 0.2, 11.6, 0.81, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, -0.2, 11.6, 0.81, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, 0.2, -11.6, 0.81, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, 0.2, 11.6, -0.81, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, 0, 11.6, 0.81, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, 0.2, 0, 0.81, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, 0.2, 11.6, 0, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(0, 0.2, 11.6, 0.81, 10, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 0, 60) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 10, 0) + Traceback (most recent call last): + ... + ValueError: All parameters must be positive. + + """ if ( coefficient_k <= 0 or coefficient_a <= 0 @@ -26,4 +140,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/rainfall_intensity.py