instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Expand my code with proper documentation strings
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11532 # https://github.com/TheAlgorithms/Python/pull/11532 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from data_structures.kd_tree.kd_node imp...
--- +++ @@ -12,11 +12,33 @@ def nearest_neighbour_search( root: KDNode | None, query_point: list[float] ) -> tuple[list[float] | None, float, int]: + """ + Performs a nearest neighbor search in a KD-Tree for a given query point. + + Args: + root (KDNode | None): The root node of the KD-Tree. + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/kd_tree/nearest_neighbour_search.py
Write docstrings describing each step
from PIL import Image def change_brightness(img: Image, level: float) -> Image: def brightness(c: int) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __...
--- +++ @@ -2,8 +2,15 @@ def change_brightness(img: Image, level: float) -> Image: + """ + Change the brightness of a PIL Image to a given level. + """ def brightness(c: int) -> float: + """ + Fundamental Transformation/Operation that'll be performed on + every bit. + """...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/change_brightness.py
Create structured documentation for my script
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: data: Any next_node: Node | None = None @dataclass class CircularLinkedList: head: Node | None = None # Reference to the head (first node) tail: N...
--- +++ @@ -17,6 +17,11 @@ tail: Node | None = None # Reference to the tail (last node) def __iter__(self) -> Iterator[Any]: + """ + Iterate through all nodes in the Circular Linked List yielding their data. + Yields: + The data of each node in the linked list. + """ ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/circular_linked_list.py
Add concise docstrings to each method
from __future__ import annotations from itertools import pairwise from random import random from typing import TypeVar KT = TypeVar("KT") VT = TypeVar("VT") class Node[KT, VT]: def __init__(self, key: KT | str = "root", value: VT | None = None): self.key = key self.value = value self.fo...
--- +++ @@ -1,3 +1,7 @@+""" +Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh +https://epaperpress.com/sortsearch/download/skiplist.pdf +""" from __future__ import annotations @@ -16,11 +20,31 @@ self.forward: list[Node[KT, VT]] = [] def __repr__(self) -> str: + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/skip_list.py
Add docstrings that explain purpose and usage
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: data: Any next_node: Node | None = None def __repr__(self) -> str: return f"Node({self.data})" class LinkedList: def __init__(self): ...
--- +++ @@ -7,31 +7,121 @@ @dataclass class Node: + """ + Create and initialize Node class instance. + >>> Node(20) + Node(20) + >>> Node("Hello, world!") + Node(Hello, world!) + >>> Node(None) + Node(None) + >>> Node(True) + Node(True) + """ data: Any next_node: Node | N...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/singly_linked_list.py
Write proper docstrings for these functions
# Implementation of Circular Queue (using Python lists) class CircularQueue: def __init__(self, n: int): self.n = n self.array = [None] * self.n self.front = 0 # index of the first element self.rear = 0 self.size = 0 def __len__(self) -> int: return self.size...
--- +++ @@ -2,6 +2,7 @@ class CircularQueue: + """Circular FIFO queue with a fixed capacity""" def __init__(self, n: int): self.n = n @@ -11,15 +12,64 @@ self.size = 0 def __len__(self) -> int: + """ + >>> cq = CircularQueue(5) + >>> len(cq) + 0 + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/queues/circular_queue.py
Add docstrings to improve collaboration
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11554 # https://github.com/TheAlgorithms/Python/pull/11554 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from data_structures.suffix_tree.suffix_...
--- +++ @@ -11,11 +11,20 @@ class SuffixTree: def __init__(self, text: str) -> None: + """ + Initializes the suffix tree with the given text. + + Args: + text (str): The text for which the suffix tree is to be built. + """ self.text: str = text self.root: ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/suffix_tree/suffix_tree.py
Add docstrings that explain inputs and outputs
from __future__ import annotations from dataclasses import dataclass @dataclass class ListNode: val: int = 0 next_node: ListNode | None = None def is_palindrome(head: ListNode | None) -> bool: if not head: return True # split the list to two parts fast: ListNode | None = head.next_node ...
--- +++ @@ -10,6 +10,31 @@ def is_palindrome(head: ListNode | None) -> bool: + """ + Check if a linked list is a palindrome. + + Args: + head: The head of the linked list. + + Returns: + bool: True if the linked list is a palindrome, False otherwise. + + Examples: + >>> is_palind...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/is_palindrome.py
Add verbose docstrings with examples
operators = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): return c.isdigit() def evaluate(expression): stack = [] # iterate over the string in reverse order for c in expression.split()[::-1]: # pus...
--- +++ @@ -1,3 +1,7 @@+""" +Program to evaluate a prefix expression. +https://en.wikipedia.org/wiki/Polish_notation +""" operators = { "+": lambda x, y: x + y, @@ -8,10 +12,31 @@ def is_operand(c): + """ + Return True if the given char c is an operand, e.g. it is a number + + >>> is_operand("1") +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/prefix_evaluation.py
Generate consistent docstrings
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | ...
--- +++ @@ -7,6 +7,17 @@ class CircularQueueLinkedList: + """ + Circular FIFO list with the given capacity (default queue length : 6) + + >>> cq = CircularQueueLinkedList(2) + >>> cq.enqueue('a') + >>> cq.enqueue('b') + >>> cq.enqueue('c') + Traceback (most recent call last): + ... + E...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/queues/circular_queue_linked_list.py
Add missing documentation to my Python functions
__author__ = "Alexander Joslin" import operator as op from .stack import Stack def dijkstras_two_stack_algorithm(equation: str) -> int: operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} operand_stack: Stack[int] = Stack() operator_stack: Stack[str] = Stack() for i in equation: ...
--- +++ @@ -1,3 +1,34 @@+""" +Author: Alexander Joslin +GitHub: github.com/echoaj + +Explanation: https://medium.com/@haleesammar/implemented-in-js-dijkstras-2-stack- + algorithm-for-evaluating-mathematical-expressions-fc0837dae1ea + +We can use Dijkstra's two stack algorithm to solve an equation +such as...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/dijkstras_two_stack_algorithm.py
Write documentation strings for class attributes
from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: __slots__ = ("_back", "_front", "_len") @dataclass class _Node: val: Any = None next_node: Deque._Node | None = None prev_node: Deque._...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation of double ended queue. +""" from __future__ import annotations @@ -7,17 +10,50 @@ class Deque: + """ + Deque data structure. + Operations + ---------- + append(val: Any) -> None + appendleft(val: Any) -> None + extend(iterable: Iterable) -> None ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/queues/double_ended_queue.py
Add documentation for all methods
class OverFlowError(Exception): pass class UnderFlowError(Exception): pass class FixedPriorityQueue: def __init__(self): self.queues = [ [], [], [], ] def enqueue(self, priority: int, data: int) -> None: try: if len(self.que...
--- +++ @@ -1,3 +1,7 @@+""" +Pure Python implementations of a Fixed Priority Queue and an Element Priority Queue +using Python lists. +""" class OverFlowError(Exception): @@ -9,6 +13,58 @@ class FixedPriorityQueue: + """ + Tasks can be added to a Priority Queue at any time and in any order but when Tasks...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/queues/priority_queue_using_list.py
Add docstrings to make code maintainable
# Defining valid unary operator symbols UNARY_OP_SYMBOLS = ("-", "+") # operators & their respective operation OPERATORS = { "^": lambda p, q: p**q, "*": lambda p, q: p * q, "/": lambda p, q: p / q, "+": lambda p, q: p + q, "-": lambda p, q: p - q, } def parse_token(token: str | float) -> float ...
--- +++ @@ -1,3 +1,28 @@+""" +Reverse Polish Nation is also known as Polish postfix notation or simply postfix +notation. +https://en.wikipedia.org/wiki/Reverse_Polish_notation +Classic examples of simple stack implementations. +Valid operators are +, -, *, /. +Each operand may be an integer or another expression. + +O...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/postfix_evaluation.py
Add docstrings that explain logic
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass @dataclass class Node: data: int next_node: Node | None = None class LinkedList: def __init__(self) -> None: self.head: Node | None = None self.tail: Node | None = None ...
--- +++ @@ -11,32 +11,94 @@ class LinkedList: + """A class to represent a Linked List. + Use a tail pointer to speed up the append() operation. + """ def __init__(self) -> None: + """Initialize a LinkedList with the head node set to None. + >>> linked_list = LinkedList() + >>> (...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/print_reverse.py
Create docstrings for API functions
from __future__ import annotations arr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] expect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def next_greatest_element_slow(arr: list[float]) -> list[float]: result = [] arr_size = len(arr) for i in range(arr_size): nex...
--- +++ @@ -5,6 +5,24 @@ def next_greatest_element_slow(arr: list[float]) -> list[float]: + """ + Get the Next Greatest Element (NGE) for each element in the array + by checking all subsequent elements to find the next greater one. + + This is a brute-force implementation, and it has a time complexity +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/next_greater_element.py
Add clean documentation to messy code
class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): string_rep = "" temp = self while temp: string_rep += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_re...
--- +++ @@ -1,3 +1,7 @@+""" +Recursive Program to create a Linked List from a sequence and +print a string representation of it. +""" class Node: @@ -6,6 +10,7 @@ self.next = None def __repr__(self): + """Returns a visual representation of the node and all its following nodes.""" str...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/from_sequence.py
Add docstrings for utility scripts
from collections.abc import Iterable class QueueByTwoStacks[T]: def __init__(self, iterable: Iterable[T] | None = None) -> None: self._stack1: list[T] = list(iterable or []) self._stack2: list[T] = [] def __len__(self) -> int: return len(self._stack1) + len(self._stack2) def __...
--- +++ @@ -1,24 +1,97 @@+"""Queue implementation using two stacks""" from collections.abc import Iterable class QueueByTwoStacks[T]: def __init__(self, iterable: Iterable[T] | None = None) -> None: + """ + >>> QueueByTwoStacks() + Queue(()) + >>> QueueByTwoStacks([10, 20, 30]) ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/queues/queue_by_two_stacks.py
Add structured docstrings to improve clarity
from PIL import Image def change_contrast(img: Image, level: int) -> Image: factor = (259 * (level + 255)) / (255 * (259 - level)) def contrast(c: int) -> int: return int(128 + factor * (c - 128)) return img.point(contrast) if __name__ == "__main__": # Load image with Image.open("imag...
--- +++ @@ -1,19 +1,35 @@- -from PIL import Image - - -def change_contrast(img: Image, level: int) -> Image: - factor = (259 * (level + 255)) / (255 * (259 - level)) - - def contrast(c: int) -> int: - return int(128 + factor * (c - 128)) - - return img.point(contrast) - - -if __name__ == "__main__": - ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/change_contrast.py
Generate NumPy-style docstrings
from __future__ import annotations from typing import TypeVar T = TypeVar("T") class StackOverflowError(BaseException): pass class StackUnderflowError(BaseException): pass class Stack[T]: def __init__(self, limit: int = 10): self.stack: list[T] = [] self.limit = limit def __boo...
--- +++ @@ -14,6 +14,13 @@ class Stack[T]: + """A stack is an abstract data type that serves as a collection of + elements with two principal operations: push() and pop(). push() adds an + element to the top of the stack, and pop() removes an element from the top + of a stack. The order in which element...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/stack.py
Add docstrings to improve readability
def calculate_span(price: list[int]) -> list[int]: n = len(price) s = [0] * n # Create a stack and push index of fist element to it st = [] st.append(0) # Span value of first element is always 1 s[0] = 1 # Calculate span values for rest of the elements for i in range(1, n): ...
--- +++ @@ -1,6 +1,34 @@+""" +The stock span problem is a financial problem where we have a series of n daily +price quotes for a stock and we need to calculate span of stock's price for all n days. + +The span Si of the stock's price on a given day i is defined as the maximum +number of consecutive days just before th...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/stock_span_problem.py
Add docstrings to make code maintainable
from collections.abc import Iterable class QueueByList[T]: def __init__(self, iterable: Iterable[T] | None = None) -> None: self.entries: list[T] = list(iterable or []) def __len__(self) -> int: return len(self.entries) def __repr__(self) -> str: return f"Queue({tuple(self.ent...
--- +++ @@ -1,30 +1,113 @@+"""Queue represented by a Python list""" from collections.abc import Iterable class QueueByList[T]: def __init__(self, iterable: Iterable[T] | None = None) -> None: + """ + >>> QueueByList() + Queue(()) + >>> QueueByList([10, 20, 30]) + Queue((1...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/queues/queue_by_list.py
Create Google-style docstrings for my code
def infix_2_postfix(infix: str) -> str: stack = [] post_fix = [] priority = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator print_width = max(len(infix), 7) # Print table header for output print( "Sym...
--- +++ @@ -1,6 +1,67 @@+""" +Output: + +Enter an Infix Equation = a + b ^c + Symbol | Stack | Postfix +---------------------------- + c | | c + ^ | ^ | c + b | ^ | cb + + | + | cb^ + a | + | cb^a + | | cb^a+ + + a+b^c (Infix) -> ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/infix_to_prefix_conversion.py
Improve documentation using docstrings
# A complete working Python program to demonstrate all # stack operations using a doubly linked list from __future__ import annotations from typing import TypeVar T = TypeVar("T") class Node[T]: def __init__(self, data: T): self.data = data # Assign data self.next: Node[T] | None = None # Ini...
--- +++ @@ -1,103 +1,130 @@-# A complete working Python program to demonstrate all -# stack operations using a doubly linked list - -from __future__ import annotations - -from typing import TypeVar - -T = TypeVar("T") - - -class Node[T]: - def __init__(self, data: T): - self.data = data # Assign data - ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/stack_with_doubly_linked_list.py
Improve my code by adding docstrings
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next_node: Node | None class SortedLinkedList: def __init__(self...
--- +++ @@ -1,3 +1,6 @@+""" +Algorithm that merges two sorted linked lists into one sorted linked list. +""" from __future__ import annotations @@ -21,21 +24,54 @@ self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: + """ + >>> tuple(SortedLinkedList(test_data_odd))...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/merge_two_lists.py
Add concise docstrings to each method
from __future__ import annotations from collections.abc import Iterator from typing import TypeVar T = TypeVar("T") class Node[T]: def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: return f"{self.data}" class LinkedStack[T]: ...
--- +++ @@ -1,67 +1,165 @@- -from __future__ import annotations - -from collections.abc import Iterator -from typing import TypeVar - -T = TypeVar("T") - - -class Node[T]: - def __init__(self, data: T): - self.data = data - self.next: Node[T] | None = None - - def __str__(self) -> str: - retu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/stack_with_singly_linked_list.py
Add return value explanations in docstrings
class TrieNode: def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode self.is_leaf = False def insert_many(self, words: list[str]) -> None: for word in words: self.insert(word) def insert(self, word: str) -> None: cu...
--- +++ @@ -1,3 +1,9 @@+""" +A Trie/Prefix Tree is a kind of search tree used to provide quick lookup +of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity +making it impractical in practice. It however provides O(max(search_string, length of +longest word)) lookup time making it an opt...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/trie/trie.py
Improve my code by adding docstrings
class RadixNode: def __init__(self, prefix: str = "", is_leaf: bool = False) -> None: # Mapping from the first character of the prefix of the node self.nodes: dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word self.is_leaf = is_leaf self.prefi...
--- +++ @@ -1,3 +1,8 @@+""" +A Radix Tree is a data structure that represents a space-optimized +trie (prefix tree) in whicheach node that is the only child is merged +with its parent [https://en.wikipedia.org/wiki/Radix_tree] +""" class RadixNode: @@ -11,6 +16,17 @@ self.prefix = prefix def match(s...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/trie/radix_tree.py
Add docstrings that explain logic
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordin...
--- +++ @@ -5,6 +5,17 @@ def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: + """ + Comparing local neighborhood pixel value with threshold value of centre pixel. + Exception is required when neighborhood value of a center pixel value is null. + i.e...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/filters/local_binary_pattern.py
Add structured docstrings to improve clarity
import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: def __init__(self, input_img, threshold: int): self.min_threshold = 0 # max greyscale value for #FFFFFF self.max_threshold = int(self.get_greyscale(255, 255, 255)) if not self.min_thresho...
--- +++ @@ -1,9 +1,20 @@+""" +Implementation Burke's algorithm (dithering) +""" import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: + """ + Burke's algorithm is using for converting grayscale image to black and white version + Source: Source: https://en.wikipedi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/dithering/burkes.py
Add docstrings for utility scripts
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: return (gray > 127) & (gray <= 255) def ...
--- +++ @@ -1,44 +1,75 @@-from pathlib import Path - -import numpy as np -from PIL import Image - - -def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: - r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] - return 0.2989 * r + 0.5870 * g + 0.1140 * b - - -def gray_to_binary(gray: np.ndarray) -> np.ndarray: - retu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/morphological_operations/dilation_operation.py
Add structured docstrings to improve clarity
# Author: João Gustavo A. Amorim # Author email: joaogustavoamorim@gmail.com # Coding date: jan 2019 # python/black: True # Imports import numpy as np # Class implemented to calculus the index class IndexCalculation: def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set...
--- +++ @@ -9,6 +9,100 @@ # Class implemented to calculus the index class IndexCalculation: + """ + # Class Summary + This algorithm consists in calculating vegetation indices, these + indices can be used for precision agriculture for example (or remote + sensing). There are functions ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/index_calculation.py
Add docstrings to improve collaboration
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: return (gray > 127) & (gray <= 255) def ...
--- +++ @@ -1,48 +1,82 @@-from pathlib import Path - -import numpy as np -from PIL import Image - - -def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: - r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] - return 0.2989 * r + 0.5870 * g + 0.1140 * b - - -def gray_to_binary(gray: np.ndarray) -> np.ndarray: - retu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/morphological_operations/erosion_operation.py
Add detailed docstrings explaining each function
from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] ...
--- +++ @@ -1,9 +1,17 @@+""" +Implementation of median filter algorithm +""" from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): + """ + :param gray_img: gray image + :param mask: mask ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/filters/median_filter.py
Help me write clear docstrings
import cv2 import numpy as np from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter PI = 180 def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - ce...
--- +++ @@ -19,6 +19,11 @@ def suppress_non_maximum(image_shape, gradient_direction, sobel_grad): + """ + Non-maximum suppression. If the edge strength of the current pixel is the largest + compared to the other pixels in the mask with the same direction, the value will be + preserved. Otherwise, the va...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/edge_detection/canny.py
Write beginner-friendly docstrings
def abbr(a: str, b: str) -> bool: n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = Tr...
--- +++ @@ -1,6 +1,24 @@+""" +https://www.hackerrank.com/challenges/abbr/problem +You can perform the following operation on some string, : + +1. Capitalize zero or more of 's lowercase letters at some index i + (i.e., make them uppercase). +2. Delete all of the remaining lowercase letters in . + +Example: +a=daBcd a...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/abbreviation.py
Document all endpoints with docstrings
def heaps(arr: list) -> list: if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i...
--- +++ @@ -1,6 +1,31 @@+""" +Heap's (iterative) algorithm returns the list of all permutations possible from a list. +It minimizes movement by generating each permutation from the previous one +by swapping only two elements. +More information: +https://en.wikipedia.org/wiki/Heap%27s_algorithm. +""" def heaps(arr:...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/heaps_algorithm_iterative.py
Add docstrings to my Python code
def euclidean_distance_sqr(point1, point2): return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): for i in range(points_counts ...
--- +++ @@ -1,14 +1,55 @@+""" +The algorithm finds distance between closest pair of points +in the given n points. +Approach used -> Divide and conquer +The points are sorted based on Xco-ords and +then based on Yco-ords separately. +And by applying divide and conquer approach, +minimum distance is obtained recursively...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/closest_pair_of_points.py
Please document this code using docstrings
def count_inversions_bf(arr): num_inversions = 0 n = len(arr) for i in range(n - 1): for j in range(i + 1, n): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def count_inversions_recursive(arr): if len(arr) <= 1: return arr, 0 mid...
--- +++ @@ -1,6 +1,33 @@+""" +Given an array-like data structure A[1..n], how many pairs +(i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are +called inversions. Counting the number of such inversions in an array-like +object is the important. Among other things, counting inversions can help +us deter...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/inversions.py
Include argument descriptions in docstrings
import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0") self.img = img self....
--- +++ @@ -1,9 +1,14 @@+"""Multiple image resizing techniques""" import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: + """ + Simplest and fastest version of image resizing. + Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation + ""...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/resize/resize.py
Auto-generate documentation strings for this file
from __future__ import annotations from collections.abc import Iterable class Point: def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def...
--- +++ @@ -1,3 +1,17 @@+""" +The convex hull problem is problem of finding all the vertices of convex polygon, P of +a set of points in a plane such that all the points are either on the vertices of P or +inside P. TH convex hull problem has several applications in geometrical problems, +computer graphics and game dev...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/convex_hull.py
Write clean docstrings for readability
def partition(m: int) -> int: memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - ...
--- +++ @@ -1,6 +1,36 @@+""" +The number of partitions of a number n into at least k parts equals the number of +partitions into exactly k parts plus the number of partitions into at least k-1 parts. +Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k +into k parts. These two facts t...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/integer_partition.py
Add verbose docstrings with examples
def actual_power(a: int, b: int) -> int: if b == 0: return 1 half = actual_power(a, b // 2) if (b % 2) == 0: return half * half else: return a * half * half def power(a: int, b: int) -> float: if b < 0: return 1 / actual_power(a, -b) return actual_power(a, b) ...
--- +++ @@ -1,4 +1,22 @@ def actual_power(a: int, b: int) -> int: + """ + Function using divide and conquer to calculate a^b. + It only works for integer a,b. + + :param a: The base of the power operation, an integer. + :param b: The exponent of the power operation, a non-negative integer. + :return: ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/power.py
Write docstrings that follow conventions
from __future__ import annotations def peak(lst: list[int]) -> int: # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on...
--- +++ @@ -1,8 +1,30 @@+""" +Finding the peak of a unimodal list using divide and conquer. +A unimodal array is defined as follows: array is increasing up to index p, +then decreasing afterwards. (for p >= 1) +An obvious solution can be performed in O(n), +to find the maximum of the array. +(From Kleinberg and Tardos....
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/peak.py
Write Python docstrings for this snippet
from __future__ import annotations def merge(left_half: list, right_half: list) -> list: sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 # pointer to current index for left Half pointer2 = 0 # pointer to current index for the right Half index = 0 # pointer to current index ...
--- +++ @@ -2,6 +2,33 @@ def merge(left_half: list, right_half: list) -> list: + """Helper function for mergesort. + + >>> left_half = [-2] + >>> right_half = [-1] + >>> merge(left_half, right_half) + [-2, -1] + + >>> left_half = [1,2,3] + >>> right_half = [4,5,6] + >>> merge(left_half, righ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/mergesort.py
Generate descriptive docstrings automatically
from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): return min(value, 255) for i in ra...
--- +++ @@ -1,14 +1,26 @@+""" +Implemented an algorithm using opencv to tone an image with sepia technique +""" from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): + """ + Function create sepia tone. + Source: https://en.wikipedia.org/wiki/Sepia_(color) + """...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/digital_image_processing/sepia.py
Document my Python code with docstrings
import sys """ Dynamic Programming Implementation of Matrix Chain Multiplication Time Complexity: O(n^3) Space Complexity: O(n^2) Reference: https://en.wikipedia.org/wiki/Matrix_chain_multiplication """ def matrix_chain_order(array: list[int]) -> tuple[list[list[int]], list[list[int]]]: n = len(array) matri...
--- +++ @@ -11,6 +11,10 @@ def matrix_chain_order(array: list[int]) -> tuple[list[list[int]], list[list[int]]]: + """ + >>> matrix_chain_order([10, 30, 5]) + ([[0, 0, 0], [0, 0, 1500], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]) + """ n = len(array) matrix = [[0 for _ in range(n)] for _ in ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/matrix_chain_order.py
Write Python docstrings for this snippet
def dp_count(s, n): if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than o...
--- +++ @@ -1,6 +1,27 @@+""" +You have m types of coins available in infinite quantities +where the value of each coins is given in the array S=[S0,... Sm-1] +Can you determine number of ways of making change for n units using +the given types of coins? +https://www.hackerrank.com/challenges/coin-change/problem +""" ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/minimum_coin_change.py
Add standardized docstrings across the file
def heaps(arr: list) -> list: if len(arr) <= 1: return [tuple(arr)] res = [] def generate(k: int, arr: list): if k == 1: res.append(tuple(arr[:])) return generate(k - 1, arr) for i in range(k - 1): if k % 2 == 0: # k is even ...
--- +++ @@ -1,6 +1,31 @@+""" +Heap's algorithm returns the list of all permutations possible from a list. +It minimizes movement by generating each permutation from the previous one +by swapping only two elements. +More information: +https://en.wikipedia.org/wiki/Heap%27s_algorithm. +""" def heaps(arr: list) -> li...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/heaps_algorithm.py
Add docstrings to existing functions
from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: word_bank = word_bank or [] # create a table table_size: int = len(target) + 1 table: list[list[list[str]]] = [] for _ in range(table_size): table.append([]) # s...
--- +++ @@ -1,8 +1,22 @@+""" +Program to list all the ways a target string can be +constructed from the given list of substrings +""" from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: + """ + returns the list containing all the possib...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/all_construct.py
Generate consistent docstrings
def combination_sum_iv(array: list[int], target: int) -> int: def count_of_possible_combinations(target: int) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item) for item in array) return count_of_p...
--- +++ @@ -1,6 +1,36 @@+""" +Question: + You are given an array of distinct integers and you have to tell how many + different ways of selecting the elements from the array are there such that + the sum of chosen elements is equal to the target number tar. + +Example + +Input: + * N = 3 + * target = 5 +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/combination_sum_iv.py
Generate docstrings for script automation
from __future__ import annotations import math def default_matrix_multiplication(a: list, b: list) -> list: if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2: raise Exception("Matrices are not 2x2") new_matrix = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0...
--- +++ @@ -4,6 +4,9 @@ def default_matrix_multiplication(a: list, b: list) -> list: + """ + Multiplication only for 2x2 matrices + """ if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2: raise Exception("Matrices are not 2x2") new_matrix = [ @@ -28,6 +31,21 @@ def spl...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/strassen_matrix_multiplication.py
Insert docstrings into my code
def longest_common_substring(text1: str, text2: str) -> str: if not (isinstance(text1, str) and isinstance(text2, str)): raise ValueError("longest_common_substring() takes two strings for inputs") if not text1 or not text2: return "" text1_length = len(text1) text2_length = len(text...
--- +++ @@ -1,6 +1,44 @@+""" +Longest Common Substring Problem Statement: + Given two sequences, find the + longest common substring present in both of them. A substring is + necessarily continuous. + +Example: + ``abcdef`` and ``xabded`` have two longest common substrings, ``ab`` or ``de``. + Therefore,...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/longest_common_substring.py
Fully document this Python code with docstrings
class Fibonacci: def __init__(self) -> None: self.sequence = [0, 1] def get(self, index: int) -> list: if (difference := index - (len(self.sequence) - 2)) >= 1: for _ in range(difference): self.sequence.append(self.sequence[-1] + self.sequence[-2]) return s...
--- +++ @@ -1,3 +1,7 @@+""" +This is a pure Python implementation of Dynamic Programming solution to the fibonacci +sequence problem. +""" class Fibonacci: @@ -5,6 +9,15 @@ self.sequence = [0, 1] def get(self, index: int) -> list: + """ + Get the Fibonacci number of `index`. If the num...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/fibonacci.py
Generate helpful docstrings for debugging
import math class Graph: def __init__(self, n=0): # a graph with Node 0,1,...,N-1 self.n = n self.w = [ [math.inf for j in range(n)] for i in range(n) ] # adjacency matrix for weight self.dp = [ [math.inf for j in range(n)] for i in range(n) ] # d...
--- +++ @@ -1,51 +1,85 @@-import math - - -class Graph: - def __init__(self, n=0): # a graph with Node 0,1,...,N-1 - self.n = n - self.w = [ - [math.inf for j in range(n)] for i in range(n) - ] # adjacency matrix for weight - self.dp = [ - [math.inf for j in range(...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/floyd_warshall.py
Document all public functions with docstrings
#!/usr/bin/env python3 from __future__ import annotations import sys def fibonacci(n: int) -> int: if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] # returns (F(n), F(n-1)) def _fib(n: int) -> tuple[int, int]: if n == 0: # (F(0), F(1)) return (0, 1...
--- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python3 +""" +This program calculates the nth Fibonacci number in O(log(n)). +It's possible to calculate F(1_000_000) in less than a second. +""" from __future__ import annotations @@ -7,6 +11,11 @@ def fibonacci(n: int) -> int: + """ + return F(n) + >>> [fibon...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/fast_fibonacci.py
Help me add docstrings to my project
class EditDistance: def __init__(self): self.word1 = "" self.word2 = "" self.dp = [] def __min_dist_top_down_dp(self, m: int, n: int) -> int: if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: retur...
--- +++ @@ -1,6 +1,22 @@+""" +Author : Turfa Auliarachman +Date : October 12, 2016 + +This is a pure Python implementation of Dynamic Programming solution to the edit +distance problem. + +The problem is : +Given two strings A and B. Find the minimum number of operations to string B such that +A = B. The permitted ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/edit_distance.py
Help me comply with documentation standards
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def max_subarray( arr: Sequence[float], low: int, high: int ) -> tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == h...
--- +++ @@ -1,3 +1,11 @@+""" +The maximum subarray problem is the task of finding the continuous subarray that has the +maximum sum within a given array of numbers. For example, given the array +[-2, 1, -3, 4, -1, 2, 1, -5, 4], the contiguous subarray with the maximum sum is +[4, -1, 2, 1], which has a sum of 6. + +Thi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/max_subarray.py
Write docstrings for this repository
def find_minimum_partitions(string: str) -> int: length = len(string) cut = [0] * length is_palindromic = [[False for i in range(length)] for j in range(length)] for i, c in enumerate(string): mincut = i for j in range(i + 1): if c == string[j] and (i - j < 2 or is_palindro...
--- +++ @@ -1,6 +1,25 @@+""" +Given a string s, partition s such that every substring of the +partition is a palindrome. +Find the minimum cuts needed for a palindrome partitioning of s. + +Time Complexity: O(n^2) +Space Complexity: O(n^2) +For other explanations refer to: https://www.youtube.com/watch?v=_H8V5hJUGd0 +"...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/palindrome_partitioning.py
Add docstrings to existing functions
from __future__ import annotations from random import choice def random_pivot(lst): return choice(lst) def kth_number(lst: list[int], k: int) -> int: # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e i...
--- +++ @@ -1,3 +1,13 @@+""" +Find the kth smallest element in linear time using divide and conquer. +Recall we can do this trivially in O(nlogn) time. Sort the list and +access kth element in constant time. + +This is a divide and conquer algorithm that can find a solution in O(n) time. + +For more information of this...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/divide_and_conquer/kth_order_statistic.py
Add docstrings with type hints explained
def score_function( source_char: str, target_char: str, match: int = 1, mismatch: int = -1, gap: int = -2, ) -> int: if "-" in (source_char, target_char): return gap return match if source_char == target_char else mismatch def smith_waterman( query: str, subject: str, ...
--- +++ @@ -1,3 +1,12 @@+""" +https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm +The Smith-Waterman algorithm is a dynamic programming algorithm used for sequence +alignment. It is particularly useful for finding similarities between two sequences, +such as DNA or protein sequences. In this implementation,...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/smith_waterman.py
Create documentation strings for testing functions
def longest_common_subsequence(x: str, y: str): # find the length of strings assert x is not None assert y is not None m = len(x) n = len(y) # declaring the array for storing the dp values dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1...
--- +++ @@ -1,6 +1,52 @@+""" +LCS Problem Statement: Given two sequences, find the length of longest subsequence +present in both of them. A subsequence is a sequence that appears in the same relative +order, but not necessarily continuous. +Example:"abc", "abg" are subsequences of "abcdefgh". +""" def longest_co...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/longest_common_subsequence.py
Generate consistent documentation across files
from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: assert isinstance(mask, int) and mask > 0, ( f"mask needs to be positive integer, your input {mask}" ) """ first submask iterated will be mask itself then operation will be performed to get other submasks t...
--- +++ @@ -1,8 +1,41 @@+""" +Author : Syed Faizan (3rd Year Student IIIT Pune) +github : faizan2700 +You are given a bitmask m and you want to efficiently iterate through all of +its submasks. The mask s is submask of m if only bits that were included in +bitmask are set +""" from __future__ import annotations ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/iterating_through_submasks.py
Add inline docstrings for readability
def longest_palindromic_subsequence(input_string: str) -> int: n = len(input_string) rev = input_string[::-1] m = len(rev) dp = [[-1] * (m + 1) for i in range(n + 1)] for i in range(n + 1): dp[i][0] = 0 for i in range(m + 1): dp[0][i] = 0 # create and initialise dp array ...
--- +++ @@ -1,6 +1,21 @@+""" +author: Sanket Kittad +Given a string s, find the longest palindromic subsequence's length in s. +Input: s = "bbbab" +Output: 4 +Explanation: One possible longest palindromic subsequence is "bbbb". +Leetcode link: https://leetcode.com/problems/longest-palindromic-subsequence/description/ +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/longest_palindromic_subsequence.py
Generate helpful docstrings for debugging
from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else ...
--- +++ @@ -1,8 +1,38 @@+""" +Author : Mehdi ALAOUI + +This is a pure Python implementation of Dynamic Programming solution to the longest +increasing subsequence of a given sequence. + +The problem is: + Given an array, to find the longest and increasing sub-array in that given array and + return it. + +Example...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/longest_increasing_subsequence.py
Document this script properly
def catalan_numbers(upper_limit: int) -> "list[int]": if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") catalan_list = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 catalan_list[0] = 1 if upper_limit > 0: catalan_list[1] = 1 # Recurren...
--- +++ @@ -1,6 +1,44 @@+""" +Print all the Catalan numbers from 0 to n, n being the user input. + + * The Catalan numbers are a sequence of positive integers that + * appear in many counting problems in combinatorics [1]. Such + * problems include counting [2]: + * - The number of Dyck words of length 2n + * - The num...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/catalan_numbers.py
Generate consistent docstrings
# https://farside.ph.utexas.edu/teaching/316/lectures/node46.html from __future__ import annotations def capacitor_parallel(capacitors: list[float]) -> float: sum_c = 0.0 for index, capacitor in enumerate(capacitors): if capacitor < 0: msg = f"Capacitor at index {index} has a negative val...
--- +++ @@ -4,6 +4,16 @@ def capacitor_parallel(capacitors: list[float]) -> float: + """ + Ceq = C1 + C2 + ... + Cn + Calculate the equivalent resistance for any number of capacitors in parallel. + >>> capacitor_parallel([5.71389, 12, 3]) + 20.71389 + >>> capacitor_parallel([5.71389, 12, -3]) + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/capacitor_equivalence.py
Document functions with detailed explanations
def mf_knapsack(i, wt, val, j): global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: val = mf_knapsack(i - 1, wt, val, j) else: val = max( mf_knapsack(i - 1, wt, val, j), mf_knapsack(i - 1, wt, val, j - wt[i - 1]) ...
--- +++ @@ -1,6 +1,18 @@+""" +Given weights and values of n items, put these items in a knapsack of +capacity W to get the maximum total value in the knapsack. + +Note that only the integer weights 0-1 knapsack problem is solvable +using dynamic programming. +""" def mf_knapsack(i, wt, val, j): + """ + This ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/knapsack.py
Add docstrings to incomplete code
import functools def min_distance_up_bottom(word1: str, word2: str) -> int: len_word1 = len(word1) len_word2 = len(word2) @functools.cache def min_distance(index1: int, index2: int) -> int: # if first word index overflows - delete all from the second word if index1 >= len_word1: ...
--- +++ @@ -1,8 +1,27 @@+""" +Author : Alexander Pantyukhin +Date : October 14, 2022 +This is an implementation of the up-bottom approach to find edit distance. +The implementation was tested on Leetcode: https://leetcode.com/problems/edit-distance/ + +Levinstein distance +Dynamic Programming: up -> down. +""" i...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/min_distance_up_bottom.py
Document all endpoints with docstrings
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: _validation( observations_space, states_space, initial_probabilities, transiti...
--- +++ @@ -8,6 +8,105 @@ transition_probabilities: dict, emission_probabilities: dict, ) -> list: + """ + Viterbi Algorithm, to find the most likely path of + states from the start and the expected output. + + https://en.wikipedia.org/wiki/Viterbi_algorithm + + Wikipedia example + + >>> obs...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/viterbi.py
Generate docstrings with parameter types
def is_match(string: str, pattern: str) -> bool: dp = [[False] * (len(pattern) + 1) for _ in string + "1"] dp[0][0] = True # Fill in the first row for j, char in enumerate(pattern, 1): if char == "*": dp[0][j] = dp[0][j - 1] # Fill in the rest of the DP table for i, s_char ...
--- +++ @@ -1,6 +1,50 @@+""" +Author : ilyas dahhou +Date : Oct 7, 2023 + +Task: +Given an input string and a pattern, implement wildcard pattern matching with support +for '?' and '*' where: +'?' matches any single character. +'*' matches any sequence of characters (including the empty sequence). +The matching sho...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/wildcard_matching.py
Add docstrings for utility scripts
def prefix_sum(array: list[int], queries: list[tuple[int, int]]) -> list[int]: # The prefix sum array dp = [0] * len(array) dp[0] = array[0] for i in range(1, len(array)): dp[i] = dp[i - 1] + array[i] # See Algorithm section (Line 44) result = [] for query in queries: left...
--- +++ @@ -1,6 +1,73 @@+""" +Author: Sanjay Muthu <https://github.com/XenoBytesX> + +This is an implementation of the Dynamic Programming solution to the Range Sum Query. + +The problem statement is: + Given an array and q queries, + each query stating you to find the sum of elements from l to r (inclusive) + +E...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/range_sum_query.py
Auto-generate documentation strings for this file
# https://en.wikipedia.org/wiki/LC_circuit from __future__ import annotations from math import pi, sqrt def resonant_frequency(inductance: float, capacitance: float) -> tuple: if inductance <= 0: raise ValueError("Inductance cannot be 0 or negative") elif capacitance <= 0: raise ValueErro...
--- +++ @@ -1,5 +1,12 @@ # https://en.wikipedia.org/wiki/LC_circuit +"""An LC circuit, also called a resonant circuit, tank circuit, or tuned circuit, +is an electric circuit consisting of an inductor, represented by the letter L, +and a capacitor, represented by the letter C, connected together. +The circuit can act...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/resonant_frequency.py
Generate missing documentation strings
from collections.abc import Iterator from contextlib import contextmanager from functools import cache from sys import maxsize def matrix_chain_multiply(arr: list[int]) -> int: if len(arr) < 2: return 0 # initialising 2D dp matrix n = len(arr) dp = [[maxsize for j in range(n)] for i in range(...
--- +++ @@ -1,3 +1,49 @@+""" +| Find the minimum number of multiplications needed to multiply chain of matrices. +| Reference: https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/ + +The algorithm has interesting real-world applications. + +Example: + 1. Image transformations in Computer Graphics as images ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/matrix_chain_multiplication.py
Help me add docstrings to my project
def find_min(numbers: list[int]) -> int: n = len(numbers) s = sum(numbers) dp = [[False for x in range(s + 1)] for y in range(n + 1)] for i in range(n + 1): dp[i][0] = True for i in range(1, s + 1): dp[0][i] = False for i in range(1, n + 1): for j in range(1, s + 1)...
--- +++ @@ -1,6 +1,49 @@+""" +Partition a set into two subsets such that the difference of subset sums is minimum +""" def find_min(numbers: list[int]) -> int: + """ + >>> find_min([1, 2, 3, 4, 5]) + 1 + >>> find_min([5, 5, 5, 5, 5]) + 5 + >>> find_min([5, 5, 5, 5]) + 0 + >>> find_min([3]) ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/minimum_partition.py
Add docstrings to incomplete code
def recursive_match(text: str, pattern: str) -> bool: if not pattern: return not text if not text: return pattern[-1] == "*" and recursive_match(text, pattern[:-2]) if text[-1] == pattern[-1] or pattern[-1] == ".": return recursive_match(text[:-1], pattern[:-1]) if pattern[-...
--- +++ @@ -1,6 +1,37 @@+""" +Regex matching check if a text matches pattern or not. +Pattern: + + 1. ``.`` Matches any single character. + 2. ``*`` Matches zero or more of the preceding element. + +More info: + https://medium.com/trick-the-interviwer/regular-expression-matching-9972eb74c03 +""" def recur...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/regex_match.py
Can you add docstrings to this Python file?
#!/usr/bin/env python3 # This Python program implements an optimal binary search tree (abbreviated BST) # building dynamic programming algorithm that delivers O(n^2) performance. # # The goal of the optimal BST problem is to build a low-cost BST for a # given set of nodes, each with its own key and frequency. The freq...
--- +++ @@ -21,16 +21,35 @@ class Node: + """Binary Search Tree Node""" def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): + """ + >>> str(Node(1, 2)) + 'Node(key=1, freq=2)' + """ return f"Node(key={self.key}, fr...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/optimal_binary_search_tree.py
Provide docstrings following PEP 257
from __future__ import annotations __author__ = "Alexander Joslin" def min_steps_to_one(number: int) -> int: if number <= 0: msg = f"n must be greater than 0. Got n = {number}" raise ValueError(msg) table = [number + 1] * (number + 1) # starting position table[1] = 0 for i in ...
--- +++ @@ -1,3 +1,26 @@+""" +YouTube Explanation: https://www.youtube.com/watch?v=f2xi3c1S95M + +Given an integer n, return the minimum steps from n to 1 + +AVAILABLE STEPS: + * Decrement by 1 + * if n is divisible by 2, divide by 2 + * if n is divisible by 3, divide by 3 + + +Example 1: n = 10 +10 -> 9 -> 3 ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/minimum_steps_to_one.py
Add docstrings for utility scripts
def trapped_rainwater(heights: tuple[int, ...]) -> int: if not heights: return 0 if any(h < 0 for h in heights): raise ValueError("No height can be negative") length = len(heights) left_max = [0] * length left_max[0] = heights[0] for i, height in enumerate(heights[1:], start=1...
--- +++ @@ -1,6 +1,35 @@+""" +Given an array of non-negative integers representing an elevation map where the width +of each bar is 1, this program calculates how much rainwater can be trapped. + +Example - height = (0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1) +Output: 6 +This problem can be solved using the concept of "DYNAMI...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/trapped_water.py
Add docstrings to improve code quality
import functools def mincost_tickets(days: list[int], costs: list[int]) -> int: # Validation if not isinstance(days, list) or not all(isinstance(day, int) for day in days): raise ValueError("The parameter days should be a list of integers") if len(costs) != 3 or not all(isinstance(cost, int) fo...
--- +++ @@ -1,8 +1,92 @@+""" +Author : Alexander Pantyukhin +Date : November 1, 2022 + +Task: +Given a list of days when you need to travel. Each day is integer from 1 to 365. +You are able to use tickets for 1 day, 7 days and 30 days. +Each ticket has a cost. + +Find the minimum cost you need to travel every day i...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/minimum_tickets_cost.py
Create docstrings for API functions
def naive_cut_rod_recursive(n: int, prices: list): _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max( max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices) ) return max_revue def top_...
--- +++ @@ -1,6 +1,45 @@+""" +This module provides two implementations for the rod-cutting problem: + 1. A naive recursive implementation which has an exponential runtime + 2. Two dynamic programming implementations which have quadratic runtime + +The rod-cutting problem is the problem of finding the maximum possible...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/rod_cutting.py
Document helper functions with docstrings
from __future__ import annotations import copy def longest_subsequence(array: list[int]) -> list[int]: n = len(array) # The longest increasing subsequence ending at array[i] longest_increasing_subsequence = [] for i in range(n): longest_increasing_subsequence.append([array[i]]) for i in...
--- +++ @@ -1,3 +1,17 @@+""" +Author : Sanjay Muthu <https://github.com/XenoBytesX> + +This is a pure Python implementation of Dynamic Programming solution to the longest +increasing subsequence of a given sequence. + +The problem is: + Given an array, to find the longest and increasing sub-array in that given arra...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/longest_increasing_subsequence_iterative.py
Generate missing documentation strings
def find_narcissistic_numbers(limit: int) -> list[int]: if limit <= 0: return [] narcissistic_nums = [] # Memoization: cache[(power, digit)] = digit^power # This avoids recalculating the same power for different numbers power_cache: dict[tuple[int, int], int] = {} def get_digit_powe...
--- +++ @@ -1,6 +1,58 @@+""" +Find all narcissistic numbers up to a given limit using dynamic programming. + +A narcissistic number (also known as an Armstrong number or plus perfect number) +is a number that is the sum of its own digits each raised to the power of the +number of digits. + +For example, 153 is a narcis...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/narcissistic_number.py
Can you add docstrings to this Python file?
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RC_time_constant from math import exp # value of exp = 2.718281828459… def charging_capacitor( source_voltage: float, # voltage in volts. resistance: float, # resistance in ohms. capacitance: float, # capacitance i...
--- +++ @@ -1,6 +1,19 @@ # source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RC_time_constant +""" +Description +----------- +When a capacitor is connected with a potential source (AC or DC). It starts to charge +at a general speed but when a resistor is connected in the circuit wi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/charging_capacitor.py
Add docstrings to make code maintainable
import functools from typing import Any def word_break(string: str, words: list[str]) -> bool: # Validation if not isinstance(string, str) or len(string) == 0: raise ValueError("the string should be not empty string") if not isinstance(words, list) or not all( isinstance(item, str) and ...
--- +++ @@ -1,9 +1,58 @@+""" +Author : Alexander Pantyukhin +Date : December 12, 2022 + +Task: +Given a string and a list of words, return true if the string can be +segmented into a space-separated sequence of one or more words. + +Note that the same word may be reused +multiple times in the segmentation. + +Imple...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/word_break.py
Write docstrings describing functionality
from collections.abc import Sequence def max_subarray_sum( arr: Sequence[float], allow_empty_subarrays: bool = False ) -> float: if not arr: return 0 max_sum = 0 if allow_empty_subarrays else float("-inf") curr_sum = 0.0 for num in arr: curr_sum = max(0 if allow_empty_subarrays e...
--- +++ @@ -1,3 +1,14 @@+""" +The maximum subarray sum problem is the task of finding the maximum sum that can be +obtained from a contiguous subarray within a given array of numbers. For example, given +the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the contiguous subarray with the maximum sum +is [4, -1, 2, 1], so the ma...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/dynamic_programming/max_subarray_sum.py
Include argument descriptions in docstrings
# https://en.wikipedia.org/wiki/Circular_convolution import doctest from collections import deque import numpy as np class CircularConvolution: def __init__(self) -> None: self.first_signal = [2, 1, 2, -1] self.second_signal = [1, 2, 3, 4] def circular_convolution(self) -> list[float]: ...
--- +++ @@ -1,5 +1,16 @@ # https://en.wikipedia.org/wiki/Circular_convolution +""" +Circular convolution, also known as cyclic convolution, +is a special case of periodic convolution, which is the convolution of two +periodic functions that have the same period. Periodic convolution arises, +for example, in the conte...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/circular_convolution.py
Add docstrings to make code maintainable
import math def real_power(apparent_power: float, power_factor: float) -> float: if ( not isinstance(power_factor, (int, float)) or power_factor < -1 or power_factor > 1 ): raise ValueError("power_factor must be a valid float value between -1 and 1.") return apparent_power ...
--- +++ @@ -2,6 +2,17 @@ def real_power(apparent_power: float, power_factor: float) -> float: + """ + Calculate real power from apparent power and power factor. + + Examples: + >>> real_power(100, 0.9) + 90.0 + >>> real_power(0, 0.8) + 0.0 + >>> real_power(100, -0.9) + -90.0 + """ ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/real_and_reactive_power.py
Add missing documentation to my Python functions
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RL_circuit from math import exp # value of exp = 2.718281828459… def charging_inductor( source_voltage: float, # source_voltage should be in volts. resistance: float, # resistance should be in ohms. inductance: floa...
--- +++ @@ -1,6 +1,30 @@ # source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RL_circuit +""" +Description +----------- +Inductor is a passive electronic device which stores energy but unlike capacitor, it +stores energy in its 'magnetic field' or 'magnetostatic field'. + +When induc...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/charging_inductor.py
Generate docstrings for script automation
from __future__ import annotations """ Calculate the frequency and/or duty cycle of an astable 555 timer. * https://en.wikipedia.org/wiki/555_timer_IC#Astable These functions take in the value of the external resistances (in ohms) and capacitance (in Microfarad), and calculates the following: ---...
--- +++ @@ -26,6 +26,21 @@ def astable_frequency( resistance_1: float, resistance_2: float, capacitance: float ) -> float: + """ + Usage examples: + >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=7) + 1523.8095238095239 + >>> astable_frequency(resistance_1=356, resistance_2=234...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/ic_555_timer.py
Generate helpful docstrings for debugging
from __future__ import annotations from math import pow, sqrt # noqa: A004 def electrical_impedance( resistance: float, reactance: float, impedance: float ) -> dict[str, float]: if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resis...
--- +++ @@ -1,3 +1,8 @@+"""Electrical impedance is the measure of the opposition that a +circuit presents to a current when a voltage is applied. +Impedance extends the concept of resistance to alternating current (AC) circuits. +Source: https://en.wikipedia.org/wiki/Electrical_impedance +""" from __future__ import ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/electrical_impedance.py
Add docstrings for utility scripts
import colorsys from PIL import Image def get_distance(x: float, y: float, max_step: int) -> float: a = x b = y for step in range(max_step): # noqa: B007 a_new = a * a - b * b + x b = 2 * a * b + y a = a_new # divergence happens for all complex number with an absolute v...
--- +++ @@ -1,85 +1,150 @@- -import colorsys - -from PIL import Image - - -def get_distance(x: float, y: float, max_step: int) -> float: - a = x - b = y - for step in range(max_step): # noqa: B007 - a_new = a * a - b * b + x - b = 2 * a * b + y - a = a_new - - # divergence happens ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/fractals/mandelbrot.py
Add return value explanations in docstrings
# https://byjus.com/equivalent-resistance-formula/ from __future__ import annotations def resistor_parallel(resistors: list[float]) -> float: first_sum = 0.00 for index, resistor in enumerate(resistors): if resistor <= 0: msg = f"Resistor at index {index} has a negative or zero value!" ...
--- +++ @@ -4,6 +4,20 @@ def resistor_parallel(resistors: list[float]) -> float: + """ + Req = 1/ (1/R1 + 1/R2 + ... + 1/Rn) + + >>> resistor_parallel([3.21389, 2, 3]) + 0.8737571620498019 + >>> resistor_parallel([3.21389, 2, -3]) + Traceback (most recent call last): + ... + ValueError: ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/resistor_equivalence.py
Write docstrings for algorithm functions
import turtle def draw_cross(x: float, y: float, length: float): turtle.up() turtle.goto(x - length / 2, y - length / 6) turtle.down() turtle.seth(0) turtle.begin_fill() for _ in range(4): turtle.fd(length / 3) turtle.right(90) turtle.fd(length / 3) turtle.left...
--- +++ @@ -1,8 +1,24 @@+"""Authors Bastien Capiaux & Mehdi Oudghiri + +The Vicsek fractal algorithm is a recursive algorithm that creates a +pattern known as the Vicsek fractal or the Vicsek square. +It is based on the concept of self-similarity, where the pattern at each +level of recursion resembles the overall patt...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/fractals/vicsek.py
Add clean documentation to messy code
def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: int ) -> float: if principal <= 0: raise Exception("Principal borrowed must be > 0") if rate_per_annum < 0: raise Exception("Rate of interest must be >= 0") if years_to_repay <= 0 or not isinstan...
--- +++ @@ -1,8 +1,39 @@+""" +Program to calculate the amortization amount per month, given +- Principal borrowed +- Rate of interest per annum +- Years to repay the loan + +Wikipedia Reference: https://en.wikipedia.org/wiki/Equated_monthly_installment +""" def equated_monthly_installments( principal: float, ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/equated_monthly_installments.py
Add docstrings to make code maintainable
valid_colors: list = [ "Black", "Brown", "Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Grey", "White", "Gold", "Silver", ] significant_figures_color_values: dict[str, int] = { "Black": 0, "Brown": 1, "Red": 2, "Orange": 3, "Yellow": 4, "...
--- +++ @@ -1,3 +1,63 @@+""" +Title : Calculating the resistance of a n band resistor using the color codes + +Description : + Resistors resist the flow of electrical current.Each one has a value that tells how + strongly it resists current flow.This value's unit is the ohm, often noted with the + Greek letter...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/electronics/resistor_color_code.py
Create documentation for each function signature
def present_value(discount_rate: float, cash_flows: list[float]) -> float: if discount_rate < 0: raise ValueError("Discount rate cannot be negative") if not cash_flows: raise ValueError("Cash flows list cannot be empty") present_value = sum( cash_flow / ((1 + discount_rate) ** i) f...
--- +++ @@ -1,6 +1,31 @@+""" +Reference: https://www.investopedia.com/terms/p/presentvalue.asp + +An algorithm that calculates the present value of a stream of yearly cash flows given... +1. The discount rate (as a decimal, not a percent) +2. An array of cash flows, with the index of the cash flow being the associated ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/present_value.py
Add docstrings with type hints explained
from collections.abc import Iterator def exponential_moving_average( stock_prices: Iterator[float], window_size: int ) -> Iterator[float]: if window_size <= 0: raise ValueError("window_size must be > 0") # Calculating smoothing factor alpha = 2 / (1 + window_size) # Exponential average...
--- +++ @@ -1,3 +1,13 @@+""" +Calculate the exponential moving average (EMA) on the series of stock prices. +Wikipedia Reference: https://en.wikipedia.org/wiki/Exponential_smoothing +https://www.investopedia.com/terms/e/ema.asp#toc-what-is-an-exponential +-moving-average-ema + +Exponential moving average is used in fin...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/exponential_moving_average.py
Document classes and their methods
def straight_line_depreciation( useful_years: int, purchase_value: float, residual_value: float = 0.0, ) -> list[float]: if not isinstance(useful_years, int): raise TypeError("Useful years must be an integer") if useful_years < 1: raise ValueError("Useful years cannot be less tha...
--- +++ @@ -1,3 +1,32 @@+""" +In accounting, depreciation refers to the decreases in the value +of a fixed asset during the asset's useful life. +When an organization purchases a fixed asset, +the purchase expenditure is not recognized as an expense immediately. +Instead, the decreases in the asset's value are recogniz...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/straight_line_depreciation.py
Add detailed docstrings explaining each function
from collections.abc import Sequence def simple_moving_average( data: Sequence[float], window_size: int ) -> list[float | None]: if window_size < 1: raise ValueError("Window size must be a positive integer") sma: list[float | None] = [] for i in range(len(data)): if i < window_size ...
--- +++ @@ -1,3 +1,11 @@+""" +The Simple Moving Average (SMA) is a statistical calculation used to analyze data points +by creating a constantly updated average price over a specific time period. +In finance, SMA is often used in time series analysis to smooth out price data +and identify trends. + +Reference: https://...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/simple_moving_average.py