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: in... | --- +++ @@ -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)
... | 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) f... | --- +++ @@ -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,... | 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:
... | --- +++ @@ -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.... | 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
testm... | --- +++ @@ -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
+
+Ot... | 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 ... | --- +++ @@ -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 Syl... | 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
w... | --- +++ @@ -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 con... | 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 seg... | --- +++ @@ -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 the... | 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:
... | --- +++ @@ -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 containi... | 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 corres... | 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
re... | --- +++ @@ -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 soluti... | 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,
)... | --- +++ @@ -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]]:
+ ... | 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 h... | --- +++ @@ -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.
+
+ >>>... | 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)... | --- +++ @@ -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/itsAkshay... | 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 __nam... | --- +++ @@ -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... | 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)
... | --- +++ @@ -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, ... | 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
... | --- +++ @@ -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 man... | 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(a... | --- +++ @@ -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, ...]:
+ """... | 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)
d... | --- +++ @@ -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
+... | 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, ... | --- +++ @@ -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.... | 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)]
... | --- +++ @@ -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... | 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, ... | --- +++ @@ -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(ma... | 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
d... | --- +++ @@ -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:
+ >>> ma... | 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))
... | --- +++ @@ -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) ... | 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(r... | --- +++ @@ -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(matri... | 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):
... | --- +++ @@ -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... | 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... | 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]
... | --- +++ @@ -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]
+... | 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... | 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
... | --- +++ @@ -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... | 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.wik... | 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 el... | 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 ... | 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_parame... | --- +++ @@ -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 * sigmoi... | 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(
"T... | --- +++ @@ -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 @@ ste... | 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 *... | --- +++ @@ -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_modifie... | 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:
... | --- +++ @@ -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:
+ ... | 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 m... | --- +++ @@ -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 ... | 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... | --- +++ @@ -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... | 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 ... | 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 applica... | --- +++ @@ -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 ar... | 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
#... | --- +++ @@ -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 T... | 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 a... | 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_S... | --- +++ @@ -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 repeti... | 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):
... | --- +++ @@ -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: tu... | 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 +=... | --- +++ @@ -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): # p... | 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)
l... | --- +++ @@ -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.datetim... | 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.wei... | --- +++ @@ -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
... | 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__(s... | --- +++ @@ -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) ... | 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:
# Rando... | --- +++ @@ -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:
+ """Re... | 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(cita... | --- +++ @@ -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... | 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 __i... | --- +++ @@ -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']... | 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[i... | --- +++ @@ -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]) -> ... | 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 Valu... | --- +++ @@ -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,... | 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: Do... | --- +++ @@ -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 | ... | 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] | ... | --- +++ @@ -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... | 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:
majo... | --- +++ @@ -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_vot... | 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
):
... | --- +++ @@ -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 n... | 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 `LinearCongruentialGenera... | --- +++ @@ -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 @@ ... | 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_re... | --- +++ @@ -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 max... | 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
... | --- +++ @@ -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 ... | 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.indexm... | --- +++ @@ -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-fro... | 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... | --- +++ @@ -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:
-... | 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
HEIG... | --- +++ @@ -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, W... | 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 __nam... | --- +++ @@ -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... | 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:
... | --- +++ @@ -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 ... | 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... | --- +++ @@ -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... | 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
# ... | --- +++ @@ -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(... | 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
+
... | 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:... | --- +++ @@ -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 macro... | 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__ == "__... | --- +++ @@ -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 dis... | 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 ... | --- +++ @@ -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... | 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 ValueEr... | --- +++ @@ -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
+"""
# ... | 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 vel... | --- +++ @@ -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)
+ * *
+ * *
+ * *
+ * ... | 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 par... | --- +++ @@ -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.
+
... | 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... | --- +++ @@ -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 Lorent... | 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_le... | --- +++ @@ -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... | 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 ... | 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)... | --- +++ @@ -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 fo... | 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 b... | --- +++ @@ -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 v... | 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)]
retu... | --- +++ @@ -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, an... | 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... | --- +++ @@ -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... | 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 ... | --- +++ @@ -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 d... | 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,
posit... | --- +++ @@ -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__(
- s... | 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 vo... | --- +++ @@ -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 183... | 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:
r... | --- +++ @@ -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 ... | 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. It... | 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... | --- +++ @@ -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:
+ """... | 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:
... | --- +++ @@ -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 m... | 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) * diame... | --- +++ @@ -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 rat... | 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
... | --- +++ @@ -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 o... | 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 t... | --- +++ @@ -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... | 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 doct... | --- +++ @@ -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 a... | 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... | 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 Exceptio... | --- +++ @@ -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 gi... | 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... | 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
... | --- +++ @@ -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... | 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... | 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"
... | --- +++ @@ -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 acti... | 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... | 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
... | --- +++ @@ -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... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/physics/rainfall_intensity.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.