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 import KDNode def nearest_neighbour_search( root: KDNode | None, query_point: list[float] ) -> tuple[list[float] | None, float, int]: nearest_point: list[float] | None = None nearest_dist: float = float("inf") nodes_visited: int = 0 def search(node: KDNode | None, depth: int = 0) -> None: nonlocal nearest_point, nearest_dist, nodes_visited if node is None: return nodes_visited += 1 # Calculate the current distance (squared distance) current_point = node.point current_dist = sum( (query_coord - point_coord) ** 2 for query_coord, point_coord in zip(query_point, current_point) ) # Update nearest point if the current node is closer if nearest_point is None or current_dist < nearest_dist: nearest_point = current_point nearest_dist = current_dist # Determine which subtree to search first (based on axis and query point) k = len(query_point) # Dimensionality of points axis = depth % k if query_point[axis] <= current_point[axis]: nearer_subtree = node.left further_subtree = node.right else: nearer_subtree = node.right further_subtree = node.left # Search the nearer subtree first search(nearer_subtree, depth + 1) # If the further subtree has a closer point if (query_point[axis] - current_point[axis]) ** 2 < nearest_dist: search(further_subtree, depth + 1) search(root, 0) return nearest_point, nearest_dist, nodes_visited
--- +++ @@ -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. + query_point (list[float]): The point for which the nearest neighbor + is being searched. + + Returns: + tuple[list[float] | None, float, int]: + - The nearest point found in the KD-Tree to the query point, + or None if no point is found. + - The squared distance to the nearest point. + - The number of nodes visited during the search. + """ nearest_point: list[float] | None = None nearest_dist: float = float("inf") nodes_visited: int = 0 def search(node: KDNode | None, depth: int = 0) -> None: + """ + Recursively searches for the nearest neighbor in the KD-Tree. + + Args: + node: The current node in the KD-Tree. + depth: The current depth in the KD-Tree. + """ nonlocal nearest_point, nearest_dist, nodes_visited if node is None: return @@ -54,4 +76,4 @@ search(further_subtree, depth + 1) search(root, 0) - return nearest_point, nearest_dist, nodes_visited+ return nearest_point, nearest_dist, nodes_visited
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 __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
--- +++ @@ -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. + """ return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: @@ -16,4 +23,4 @@ with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) - brigt_img.save("image_data/lena_brightness.png", format="png")+ brigt_img.save("image_data/lena_brightness.png", format="png")
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: Node | None = None # Reference to the tail (last node) def __iter__(self) -> Iterator[Any]: node = self.head while node: yield node.data node = node.next_node if node == self.head: break def __len__(self) -> int: return sum(1 for _ in self) def __repr__(self) -> str: return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node: Node = Node(data) if self.head is None: new_node.next_node = new_node # First node points to itself self.tail = self.head = new_node elif index == 0: # Insert at the head new_node.next_node = self.head assert self.tail is not None # List is not empty, tail exists self.head = self.tail.next_node = new_node else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next_node assert temp is not None new_node.next_node = temp.next_node temp.next_node = new_node if index == len(self) - 1: # Insert at the tail self.tail = new_node def delete_front(self) -> Any: return self.delete_nth(0) def delete_tail(self) -> Any: return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: if not 0 <= index < len(self): raise IndexError("list index out of range.") assert self.head is not None assert self.tail is not None delete_node: Node = self.head if self.head == self.tail: # Just one node self.head = self.tail = None elif index == 0: # Delete head node assert self.tail.next_node is not None self.tail.next_node = self.tail.next_node.next_node self.head = self.head.next_node else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next_node assert temp is not None assert temp.next_node is not None delete_node = temp.next_node temp.next_node = temp.next_node.next_node if index == len(self) - 1: # Delete at tail self.tail = temp return delete_node.data def is_empty(self) -> bool: return len(self) == 0 def test_circular_linked_list() -> None: circular_linked_list = CircularLinkedList() assert len(circular_linked_list) == 0 assert circular_linked_list.is_empty() is True assert str(circular_linked_list) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5): assert len(circular_linked_list) == i circular_linked_list.insert_nth(i, i + 1) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) circular_linked_list.insert_tail(6) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7)) circular_linked_list.insert_head(0) assert str(circular_linked_list) == "->".join(str(i) for i in range(7)) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.delete_nth(2) == 3 circular_linked_list.insert_nth(2, 3) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. + """ node = self.head while node: yield node.data @@ -25,18 +30,41 @@ break def __len__(self) -> int: + """ + Get the length (number of nodes) in the Circular Linked List. + """ return sum(1 for _ in self) def __repr__(self) -> str: + """ + Generate a string representation of the Circular Linked List. + Returns: + A string of the format "1->2->....->N". + """ return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: + """ + Insert a node with the given data at the end of the Circular Linked List. + """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: + """ + Insert a node with the given data at the beginning of the Circular Linked List. + """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: + """ + Insert the data of the node at the nth pos in the Circular Linked List. + Args: + index: The index at which the data should be inserted. + data: The data to be inserted. + + Raises: + IndexError: If the index is out of range. + """ if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node: Node = Node(data) @@ -59,12 +87,33 @@ self.tail = new_node def delete_front(self) -> Any: + """ + Delete and return the data of the node at the front of the Circular Linked List. + Raises: + IndexError: If the list is empty. + """ return self.delete_nth(0) def delete_tail(self) -> Any: + """ + Delete and return the data of the node at the end of the Circular Linked List. + Returns: + Any: The data of the deleted node. + Raises: + IndexError: If the index is out of range. + """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: + """ + Delete and return the data of the node at the nth pos in Circular Linked List. + Args: + index (int): The index of the node to be deleted. Defaults to 0. + Returns: + Any: The data of the deleted node. + Raises: + IndexError: If the index is out of range. + """ if not 0 <= index < len(self): raise IndexError("list index out of range.") @@ -91,10 +140,19 @@ return delete_node.data def is_empty(self) -> bool: + """ + Check if the Circular Linked List is empty. + Returns: + bool: True if the list is empty, False otherwise. + """ return len(self) == 0 def test_circular_linked_list() -> None: + """ + Test cases for the CircularLinkedList class. + >>> test_circular_linked_list() + """ circular_linked_list = CircularLinkedList() assert len(circular_linked_list) == 0 assert circular_linked_list.is_empty() is True @@ -149,4 +207,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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.forward: list[Node[KT, VT]] = [] def __repr__(self) -> str: return f"Node({self.key}: {self.value})" @property def level(self) -> int: return len(self.forward) class SkipList[KT, VT]: def __init__(self, p: float = 0.5, max_level: int = 16): self.head: Node[KT, VT] = Node[KT, VT]() self.level = 0 self.p = p self.max_level = max_level def __str__(self) -> str: items = list(self) if len(items) == 0: return f"SkipList(level={self.level})" label_size = max((len(str(item)) for item in items), default=4) label_size = max(label_size, 4) + 4 node = self.head lines = [] forwards = node.forward.copy() lines.append(f"[{node.key}]".ljust(label_size, "-") + "* " * len(forwards)) lines.append(" " * label_size + "| " * len(forwards)) while len(node.forward) != 0: node = node.forward[0] lines.append( f"[{node.key}]".ljust(label_size, "-") + " ".join(str(n.key) if n.key == node.key else "|" for n in forwards) ) lines.append(" " * label_size + "| " * len(forwards)) forwards[: node.level] = node.forward lines.append("None".ljust(label_size) + "* " * len(forwards)) return f"SkipList(level={self.level})\n" + "\n".join(lines) def __iter__(self): node = self.head while len(node.forward) != 0: yield node.forward[0].key node = node.forward[0] def random_level(self) -> int: level = 1 while random() < self.p and level < self.max_level: level += 1 return level def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: # Nodes with refer or should refer to output node update_vector = [] node = self.head for i in reversed(range(self.level)): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: node = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(node) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def delete(self, key: KT): node, update_vector = self._locate_node(key) if node is not None: for i, update_node in enumerate(update_vector): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: update_node.forward[i] = node.forward[i] else: update_node.forward = update_node.forward[:i] def insert(self, key: KT, value: VT): node, update_vector = self._locate_node(key) if node is not None: node.value = value else: level = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1, level): update_vector.append(self.head) self.level = level new_node = Node(key, value) for i, update_node in enumerate(update_vector[:level]): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i]) if update_node.level < i + 1: update_node.forward.append(new_node) else: update_node.forward[i] = new_node def find(self, key: VT) -> VT | None: node, _ = self._locate_node(key) if node is not None: return node.value return None def test_insert(): skip_list = SkipList() skip_list.insert("Key1", 3) skip_list.insert("Key2", 12) skip_list.insert("Key3", 41) skip_list.insert("Key4", -19) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value assert len(all_values) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def test_insert_overrides_existing_value(): skip_list = SkipList() skip_list.insert("Key1", 10) skip_list.insert("Key1", 12) skip_list.insert("Key5", 7) skip_list.insert("Key7", 10) skip_list.insert("Key10", 5) skip_list.insert("Key7", 7) skip_list.insert("Key5", 5) skip_list.insert("Key10", 10) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value if len(all_values) != 4: print() assert len(all_values) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def test_searching_empty_list_returns_none(): skip_list = SkipList() assert skip_list.find("Some key") is None def test_search(): skip_list = SkipList() skip_list.insert("Key2", 20) assert skip_list.find("Key2") == 20 skip_list.insert("Some Key", 10) skip_list.insert("Key2", 8) skip_list.insert("V", 13) assert skip_list.find("Y") is None assert skip_list.find("Key2") == 8 assert skip_list.find("Some Key") == 10 assert skip_list.find("V") == 13 def test_deleting_item_from_empty_list_do_nothing(): skip_list = SkipList() skip_list.delete("Some key") assert len(skip_list.head.forward) == 0 def test_deleted_items_are_not_founded_by_find_method(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("Key2") is None def test_delete_removes_only_given_key(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") assert skip_list.find("V") is None assert skip_list.find("X") == 14 assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("X") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("Key1") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") == 15 skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") is None def test_delete_doesnt_leave_dead_nodes(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 142) skip_list.insert("Key2", 15) skip_list.delete("X") def traverse_keys(node): yield node.key for forward_node in node.forward: yield from traverse_keys(forward_node) assert len(set(traverse_keys(skip_list.head))) == 4 def test_iter_always_yields_sorted_values(): def is_sorted(lst): return all(next_item >= item for item, next_item in pairwise(lst)) skip_list = SkipList() for i in range(10): skip_list.insert(i, i) assert is_sorted(list(skip_list)) skip_list.delete(5) skip_list.delete(8) skip_list.delete(2) assert is_sorted(list(skip_list)) skip_list.insert(-12, -12) skip_list.insert(77, 77) assert is_sorted(list(skip_list)) def pytests(): for _ in range(100): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def main(): skip_list = SkipList() skip_list.insert(2, "2") skip_list.insert(4, "4") skip_list.insert(6, "4") skip_list.insert(4, "5") skip_list.insert(8, "4") skip_list.insert(9, "4") skip_list.delete(4) print(skip_list) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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: + """ + :return: Visual representation of Node + + >>> node = Node("Key", 2) + >>> repr(node) + 'Node(Key: 2)' + """ return f"Node({self.key}: {self.value})" @property def level(self) -> int: + """ + :return: Number of forward references + + >>> node = Node("Key", 2) + >>> node.level + 0 + >>> node.forward.append(Node("Key2", 4)) + >>> node.level + 1 + >>> node.forward.append(Node("Key3", 6)) + >>> node.level + 2 + """ return len(self.forward) @@ -33,6 +57,26 @@ self.max_level = max_level def __str__(self) -> str: + """ + :return: Visual representation of SkipList + + >>> skip_list = SkipList() + >>> print(skip_list) + SkipList(level=0) + >>> skip_list.insert("Key1", "Value") + >>> print(skip_list) # doctest: +ELLIPSIS + SkipList(level=... + [root]--... + [Key1]--Key1... + None *... + >>> skip_list.insert("Key2", "OtherValue") + >>> print(skip_list) # doctest: +ELLIPSIS + SkipList(level=... + [root]--... + [Key1]--Key1... + [Key2]--Key2... + None *... + """ items = list(self) @@ -70,6 +114,10 @@ node = node.forward[0] def random_level(self) -> int: + """ + :return: Random level from [1, self.max_level] interval. + Higher values are less likely. + """ level = 1 while random() < self.p and level < self.max_level: @@ -78,6 +126,12 @@ return level def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: + """ + :param key: Searched key, + :return: Tuple with searched node (or None if given key is not present) + and list of nodes that refer (if key is present) of should refer to + given node. + """ # Nodes with refer or should refer to output node update_vector = [] @@ -107,6 +161,19 @@ return None, update_vector def delete(self, key: KT): + """ + :param key: Key to remove from list. + + >>> skip_list = SkipList() + >>> skip_list.insert(2, "Two") + >>> skip_list.insert(1, "One") + >>> skip_list.insert(3, "Three") + >>> list(skip_list) + [1, 2, 3] + >>> skip_list.delete(2) + >>> list(skip_list) + [1, 3] + """ node, update_vector = self._locate_node(key) @@ -120,6 +187,17 @@ update_node.forward = update_node.forward[:i] def insert(self, key: KT, value: VT): + """ + :param key: Key to insert. + :param value: Value associated with given key. + + >>> skip_list = SkipList() + >>> skip_list.insert(2, "Two") + >>> skip_list.find(2) + 'Two' + >>> list(skip_list) + [2] + """ node, update_vector = self._locate_node(key) if node is not None: @@ -146,6 +224,19 @@ update_node.forward[i] = new_node def find(self, key: VT) -> VT | None: + """ + :param key: Search key. + :return: Value associated with given key or None if given key is not present. + + >>> skip_list = SkipList() + >>> skip_list.find(2) + >>> skip_list.insert(2, "Two") + >>> skip_list.find(2) + 'Two' + >>> skip_list.insert(2, "Three") + >>> skip_list.find(2) + 'Three' + """ node, _ = self._locate_node(key) @@ -333,6 +424,9 @@ def main(): + """ + >>> pytests() + """ skip_list = SkipList() skip_list.insert(2, "2") @@ -351,4 +445,4 @@ import doctest doctest.testmod() - main()+ main()
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): self.head = None def __iter__(self) -> Iterator[Any]: node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def __repr__(self) -> str: return " -> ".join([str(item) for item in self]) def __getitem__(self, index: int) -> Any: if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node return None # Used to change the data of a particular node def __setitem__(self, index: int, data: Any) -> None: if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for _ in range(index): current = current.next_node current.data = data def insert_tail(self, data: Any) -> None: self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next_node = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next_node new_node.next_node = temp.next_node temp.next_node = new_node def print_list(self) -> None: # print every node data print(self) def delete_head(self) -> Any: return self.delete_nth(0) def delete_tail(self) -> Any: # delete from tail return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") delete_node = self.head # default first node if index == 0: self.head = self.head.next_node else: temp = self.head for _ in range(index - 1): temp = temp.next_node delete_node = temp.next_node temp.next_node = temp.next_node.next_node return delete_node.data def is_empty(self) -> bool: return self.head is None def reverse(self) -> None: prev = None current = self.head while current: # Store the current node's next node. next_node = current.next_node # Make the current node's next_node point backwards current.next_node = prev # Make the previous node be the current node prev = current # Make the current node the next_node node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == " -> ".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == " -> ".join(str(i) for i in range(12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == " -> ".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(9)) is True for i in range(9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(9)) is True linked_list.reverse() assert str(linked_list) == " -> ".join(str(i) for i in range(-8, 1)) def test_singly_linked_list_2() -> None: test_input = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] linked_list = LinkedList() for i in test_input: linked_list.insert_tail(i) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(linked_list) == "-9 -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> " "0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2" ) # Delete the head result = linked_list.delete_head() assert result == -9 assert ( str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> " "-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2" ) # Delete the tail result = linked_list.delete_tail() assert result == 12.2 assert ( str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> " "-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None" ) # Delete a node in specific location in linked list result = linked_list.delete_nth(10) assert result is None assert ( str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> " "-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(linked_list) == "Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> " "7 -> 5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None" ) # Add None to its tail linked_list.insert_tail(None) assert ( str(linked_list) == "Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> " "5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None" ) # Reverse the linked list linked_list.reverse() assert ( str(linked_list) == "None -> None -> Node(10) -> 77.9 -> Hello, world! -> -192.55555 -> 0 -> " "5555 -> 7 -> dlrow olleH -> Node(77345112) -> 100 -> Node(Hello again, world!)" ) def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
--- +++ @@ -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 | None = None def __repr__(self) -> str: + """ + Get the string representation of this node. + >>> Node(10).__repr__() + 'Node(10)' + >>> repr(Node(10)) + 'Node(10)' + >>> str(Node(10)) + 'Node(10)' + >>> Node(10) + Node(10) + """ return f"Node({self.data})" class LinkedList: def __init__(self): + """ + Create and initialize LinkedList class instance. + >>> linked_list = LinkedList() + >>> linked_list.head is None + True + """ self.head = None def __iter__(self) -> Iterator[Any]: + """ + This function is intended for iterators to access + and iterate through data inside linked list. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("tail") + >>> linked_list.insert_tail("tail_1") + >>> linked_list.insert_tail("tail_2") + >>> for node in linked_list: # __iter__ used here. + ... node + 'tail' + 'tail_1' + 'tail_2' + """ node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: + """ + Return length of linked list i.e. number of nodes + >>> linked_list = LinkedList() + >>> len(linked_list) + 0 + >>> linked_list.insert_tail("tail") + >>> len(linked_list) + 1 + >>> linked_list.insert_head("head") + >>> len(linked_list) + 2 + >>> _ = linked_list.delete_tail() + >>> len(linked_list) + 1 + >>> _ = linked_list.delete_head() + >>> len(linked_list) + 0 + """ return sum(1 for _ in self) def __repr__(self) -> str: + """ + String representation/visualization of a Linked Lists + >>> linked_list = LinkedList() + >>> linked_list.insert_tail(1) + >>> linked_list.insert_tail(3) + >>> linked_list.__repr__() + '1 -> 3' + >>> repr(linked_list) + '1 -> 3' + >>> str(linked_list) + '1 -> 3' + >>> linked_list.insert_tail(5) + >>> f"{linked_list}" + '1 -> 3 -> 5' + """ return " -> ".join([str(item) for item in self]) def __getitem__(self, index: int) -> Any: + """ + Indexing Support. Used to get a node at particular position + >>> linked_list = LinkedList() + >>> for i in range(0, 10): + ... linked_list.insert_nth(i, i) + >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) + True + >>> linked_list[-10] + Traceback (most recent call last): + ... + ValueError: list index out of range. + >>> linked_list[len(linked_list)] + Traceback (most recent call last): + ... + ValueError: list index out of range. + """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): @@ -41,6 +131,25 @@ # Used to change the data of a particular node def __setitem__(self, index: int, data: Any) -> None: + """ + >>> linked_list = LinkedList() + >>> for i in range(0, 10): + ... linked_list.insert_nth(i, i) + >>> linked_list[0] = 666 + >>> linked_list[0] + 666 + >>> linked_list[5] = -666 + >>> linked_list[5] + -666 + >>> linked_list[-10] = 666 + Traceback (most recent call last): + ... + ValueError: list index out of range. + >>> linked_list[len(linked_list)] = 666 + Traceback (most recent call last): + ... + ValueError: list index out of range. + """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head @@ -49,12 +158,53 @@ current.data = data def insert_tail(self, data: Any) -> None: + """ + Insert data to the end of linked list. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("tail") + >>> linked_list + tail + >>> linked_list.insert_tail("tail_2") + >>> linked_list + tail -> tail_2 + >>> linked_list.insert_tail("tail_3") + >>> linked_list + tail -> tail_2 -> tail_3 + """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: + """ + Insert data to the beginning of linked list. + >>> linked_list = LinkedList() + >>> linked_list.insert_head("head") + >>> linked_list + head + >>> linked_list.insert_head("head_2") + >>> linked_list + head_2 -> head + >>> linked_list.insert_head("head_3") + >>> linked_list + head_3 -> head_2 -> head + """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: + """ + Insert data at given index. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("first") + >>> linked_list.insert_tail("second") + >>> linked_list.insert_tail("third") + >>> linked_list + first -> second -> third + >>> linked_list.insert_nth(1, "fourth") + >>> linked_list + first -> fourth -> second -> third + >>> linked_list.insert_nth(3, "fifth") + >>> linked_list + first -> fourth -> second -> fifth -> third + """ if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) @@ -71,15 +221,94 @@ temp.next_node = new_node def print_list(self) -> None: # print every node data + """ + This method prints every node data. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("first") + >>> linked_list.insert_tail("second") + >>> linked_list.insert_tail("third") + >>> linked_list + first -> second -> third + """ print(self) def delete_head(self) -> Any: + """ + Delete the first node and return the + node's data. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("first") + >>> linked_list.insert_tail("second") + >>> linked_list.insert_tail("third") + >>> linked_list + first -> second -> third + >>> linked_list.delete_head() + 'first' + >>> linked_list + second -> third + >>> linked_list.delete_head() + 'second' + >>> linked_list + third + >>> linked_list.delete_head() + 'third' + >>> linked_list.delete_head() + Traceback (most recent call last): + ... + IndexError: List index out of range. + """ return self.delete_nth(0) def delete_tail(self) -> Any: # delete from tail + """ + Delete the tail end node and return the + node's data. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("first") + >>> linked_list.insert_tail("second") + >>> linked_list.insert_tail("third") + >>> linked_list + first -> second -> third + >>> linked_list.delete_tail() + 'third' + >>> linked_list + first -> second + >>> linked_list.delete_tail() + 'second' + >>> linked_list + first + >>> linked_list.delete_tail() + 'first' + >>> linked_list.delete_tail() + Traceback (most recent call last): + ... + IndexError: List index out of range. + """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: + """ + Delete node at given index and return the + node's data. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("first") + >>> linked_list.insert_tail("second") + >>> linked_list.insert_tail("third") + >>> linked_list + first -> second -> third + >>> linked_list.delete_nth(1) # delete middle + 'second' + >>> linked_list + first -> third + >>> linked_list.delete_nth(5) # this raises error + Traceback (most recent call last): + ... + IndexError: List index out of range. + >>> linked_list.delete_nth(-1) # this also raises error + Traceback (most recent call last): + ... + IndexError: List index out of range. + """ if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") delete_node = self.head # default first node @@ -94,9 +323,30 @@ return delete_node.data def is_empty(self) -> bool: + """ + Check if linked list is empty. + >>> linked_list = LinkedList() + >>> linked_list.is_empty() + True + >>> linked_list.insert_head("first") + >>> linked_list.is_empty() + False + """ return self.head is None def reverse(self) -> None: + """ + This reverses the linked list order. + >>> linked_list = LinkedList() + >>> linked_list.insert_tail("first") + >>> linked_list.insert_tail("second") + >>> linked_list.insert_tail("third") + >>> linked_list + first -> second -> third + >>> linked_list.reverse() + >>> linked_list + third -> second -> first + """ prev = None current = self.head @@ -114,6 +364,9 @@ def test_singly_linked_list() -> None: + """ + >>> test_singly_linked_list() + """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" @@ -156,6 +409,10 @@ def test_singly_linked_list_2() -> None: + """ + This section of the test used varying data types for input. + >>> test_singly_linked_list_2() + """ test_input = [ -9, 100, @@ -269,4 +526,4 @@ if __name__ == "__main__": - main()+ main()
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 def is_empty(self) -> bool: return self.size == 0 def first(self): return False if self.is_empty() else self.array[self.front] def enqueue(self, data): if self.size >= self.n: raise Exception("QUEUE IS FULL") self.array[self.rear] = data self.rear = (self.rear + 1) % self.n self.size += 1 return self def dequeue(self): if self.size == 0: raise Exception("UNDERFLOW") temp = self.array[self.front] self.array[self.front] = None self.front = (self.front + 1) % self.n self.size -= 1 return temp
--- +++ @@ -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 + >>> cq.enqueue("A") # doctest: +ELLIPSIS + <data_structures.queues.circular_queue.CircularQueue object at ...> + >>> cq.array + ['A', None, None, None, None] + >>> len(cq) + 1 + """ return self.size def is_empty(self) -> bool: + """ + Checks whether the queue is empty or not + >>> cq = CircularQueue(5) + >>> cq.is_empty() + True + >>> cq.enqueue("A").is_empty() + False + """ return self.size == 0 def first(self): + """ + Returns the first element of the queue + >>> cq = CircularQueue(5) + >>> cq.first() + False + >>> cq.enqueue("A").first() + 'A' + """ return False if self.is_empty() else self.array[self.front] def enqueue(self, data): + """ + This function inserts an element at the end of the queue using self.rear value + as an index. + + >>> cq = CircularQueue(5) + >>> cq.enqueue("A") # doctest: +ELLIPSIS + <data_structures.queues.circular_queue.CircularQueue object at ...> + >>> (cq.size, cq.first()) + (1, 'A') + >>> cq.enqueue("B") # doctest: +ELLIPSIS + <data_structures.queues.circular_queue.CircularQueue object at ...> + >>> cq.array + ['A', 'B', None, None, None] + >>> (cq.size, cq.first()) + (2, 'A') + >>> cq.enqueue("C").enqueue("D").enqueue("E") # doctest: +ELLIPSIS + <data_structures.queues.circular_queue.CircularQueue object at ...> + >>> cq.enqueue("F") + Traceback (most recent call last): + ... + Exception: QUEUE IS FULL + """ if self.size >= self.n: raise Exception("QUEUE IS FULL") @@ -29,6 +79,26 @@ return self def dequeue(self): + """ + This function removes an element from the queue using on self.front value as an + index and returns it + + >>> cq = CircularQueue(5) + >>> cq.dequeue() + Traceback (most recent call last): + ... + Exception: UNDERFLOW + >>> cq.enqueue("A").enqueue("B").dequeue() + 'A' + >>> (cq.size, cq.first()) + (1, 'B') + >>> cq.dequeue() + 'B' + >>> cq.dequeue() + Traceback (most recent call last): + ... + Exception: UNDERFLOW + """ if self.size == 0: raise Exception("UNDERFLOW") @@ -36,4 +106,4 @@ self.array[self.front] = None self.front = (self.front + 1) % self.n self.size -= 1 - return temp+ return temp
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_tree_node import SuffixTreeNode class SuffixTree: def __init__(self, text: str) -> None: self.text: str = text self.root: SuffixTreeNode = SuffixTreeNode() self.build_suffix_tree() def build_suffix_tree(self) -> None: text = self.text n = len(text) for i in range(n): suffix = text[i:] self._add_suffix(suffix, i) def _add_suffix(self, suffix: str, index: int) -> None: node = self.root for char in suffix: if char not in node.children: node.children[char] = SuffixTreeNode() node = node.children[char] node.is_end_of_string = True node.start = index node.end = index + len(suffix) - 1 def search(self, pattern: str) -> bool: node = self.root for char in pattern: if char not in node.children: return False node = node.children[char] return True
--- +++ @@ -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: SuffixTreeNode = SuffixTreeNode() self.build_suffix_tree() def build_suffix_tree(self) -> None: + """ + Builds the suffix tree for the given text by adding all suffixes. + """ text = self.text n = len(text) for i in range(n): @@ -23,6 +32,13 @@ self._add_suffix(suffix, i) def _add_suffix(self, suffix: str, index: int) -> None: + """ + Adds a suffix to the suffix tree. + + Args: + suffix (str): The suffix to add. + index (int): The starting index of the suffix in the original text. + """ node = self.root for char in suffix: if char not in node.children: @@ -33,9 +49,18 @@ node.end = index + len(suffix) - 1 def search(self, pattern: str) -> bool: + """ + Searches for a pattern in the suffix tree. + + Args: + pattern (str): The pattern to search for. + + Returns: + bool: True if the pattern is found, False otherwise. + """ node = self.root for char in pattern: if char not in node.children: return False node = node.children[char] - return True+ return True
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 slow: ListNode | None = head while fast and fast.next_node: fast = fast.next_node.next_node slow = slow.next_node if slow else None if slow: # slow will always be defined, # adding this check to resolve mypy static check second = slow.next_node slow.next_node = None # Don't forget here! But forget still works! # reverse the second part node: ListNode | None = None while second: nxt = second.next_node second.next_node = node node = second second = nxt # compare two parts # second part has the same or one less node while node and head: if node.val != head.val: return False node = node.next_node head = head.next_node return True def is_palindrome_stack(head: ListNode | None) -> bool: if not head or not head.next_node: return True # 1. Get the midpoint (slow) slow: ListNode | None = head fast: ListNode | None = head while fast and fast.next_node: fast = fast.next_node.next_node slow = slow.next_node if slow else None # slow will always be defined, # adding this check to resolve mypy static check if slow: stack = [slow.val] # 2. Push the second half into the stack while slow.next_node: slow = slow.next_node stack.append(slow.val) # 3. Comparison cur: ListNode | None = head while stack and cur: if stack.pop() != cur.val: return False cur = cur.next_node return True def is_palindrome_dict(head: ListNode | None) -> bool: if not head or not head.next_node: return True d: dict[int, list[int]] = {} pos = 0 while head: if head.val in d: d[head.val].append(pos) else: d[head.val] = [pos] head = head.next_node pos += 1 checksum = pos - 1 middle = 0 for v in d.values(): if len(v) % 2 != 0: middle += 1 else: for step, i in enumerate(range(len(v))): if v[i] + v[len(v) - 1 - step] != checksum: return False if middle > 1: return False return True if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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_palindrome(None) + True + + >>> is_palindrome(ListNode(1)) + True + + >>> is_palindrome(ListNode(1, ListNode(2))) + False + + >>> is_palindrome(ListNode(1, ListNode(2, ListNode(1)))) + True + + >>> is_palindrome(ListNode(1, ListNode(2, ListNode(2, ListNode(1))))) + True + """ if not head: return True # split the list to two parts @@ -41,6 +66,31 @@ def is_palindrome_stack(head: ListNode | None) -> bool: + """ + Check if a linked list is a palindrome using a stack. + + Args: + head (ListNode): The head of the linked list. + + Returns: + bool: True if the linked list is a palindrome, False otherwise. + + Examples: + >>> is_palindrome_stack(None) + True + + >>> is_palindrome_stack(ListNode(1)) + True + + >>> is_palindrome_stack(ListNode(1, ListNode(2))) + False + + >>> is_palindrome_stack(ListNode(1, ListNode(2, ListNode(1)))) + True + + >>> is_palindrome_stack(ListNode(1, ListNode(2, ListNode(2, ListNode(1))))) + True + """ if not head or not head.next_node: return True @@ -72,6 +122,38 @@ def is_palindrome_dict(head: ListNode | None) -> bool: + """ + Check if a linked list is a palindrome using a dictionary. + + Args: + head (ListNode): The head of the linked list. + + Returns: + bool: True if the linked list is a palindrome, False otherwise. + + Examples: + >>> is_palindrome_dict(None) + True + + >>> is_palindrome_dict(ListNode(1)) + True + + >>> is_palindrome_dict(ListNode(1, ListNode(2))) + False + + >>> is_palindrome_dict(ListNode(1, ListNode(2, ListNode(1)))) + True + + >>> is_palindrome_dict(ListNode(1, ListNode(2, ListNode(2, ListNode(1))))) + True + + >>> is_palindrome_dict( + ... ListNode( + ... 1, ListNode(2, ListNode(1, ListNode(3, ListNode(2, ListNode(1))))) + ... ) + ... ) + False + """ if not head or not head.next_node: return True d: dict[int, list[int]] = {} @@ -100,4 +182,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() stack.append(operators[c](o1, o2)) return stack.pop() def evaluate_recursive(expression: list[str]): op = expression.pop(0) if is_operand(op): return int(op) operation = operators[op] a = evaluate_recursive(expression) b = evaluate_recursive(expression) return operation(a, b) # Driver code if __name__ == "__main__": test_expression = "+ 9 * 2 6" print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " print(evaluate(test_expression))
--- +++ @@ -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") + True + >>> is_operand("+") + False + """ return c.isdigit() def evaluate(expression): + """ + Evaluate a given expression in prefix notation. + Asserts that the given expression is valid. + + >>> evaluate("+ 9 * 2 6") + 21 + >>> evaluate("/ * 10 2 + 4 1 ") + 4.0 + >>> evaluate("2") + 2 + >>> evaluate("+ * 2 3 / 8 4") + 8.0 + """ stack = [] # iterate over the string in reverse order @@ -31,6 +56,21 @@ def evaluate_recursive(expression: list[str]): + """ + Alternative recursive implementation + + >>> evaluate_recursive(['2']) + 2 + >>> expression = ['+', '*', '2', '3', '/', '8', '4'] + >>> evaluate_recursive(expression) + 8.0 + >>> expression + [] + >>> evaluate_recursive(['+', '9', '*', '2', '6']) + 21 + >>> evaluate_recursive(['/', '*', '10', '2', '+', '4', '1']) + 4.0 + """ op = expression.pop(0) if is_operand(op): @@ -49,4 +89,4 @@ print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " - print(evaluate(test_expression))+ print(evaluate(test_expression))
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 | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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): + ... + Exception: Full Queue + """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None @@ -27,6 +38,19 @@ self.front.prev = previous_node def is_empty(self) -> bool: + """ + Checks whether the queue is empty or not + >>> cq = CircularQueueLinkedList() + >>> cq.is_empty() + True + >>> cq.enqueue('a') + >>> cq.is_empty() + False + >>> cq.dequeue() + 'a' + >>> cq.is_empty() + True + """ return ( self.front == self.rear @@ -35,10 +59,46 @@ ) def first(self) -> Any | None: + """ + Returns the first element of the queue + >>> cq = CircularQueueLinkedList() + >>> cq.first() + Traceback (most recent call last): + ... + Exception: Empty Queue + >>> cq.enqueue('a') + >>> cq.first() + 'a' + >>> cq.dequeue() + 'a' + >>> cq.first() + Traceback (most recent call last): + ... + Exception: Empty Queue + >>> cq.enqueue('b') + >>> cq.enqueue('c') + >>> cq.first() + 'b' + """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: + """ + Saves data at the end of the queue + + >>> cq = CircularQueueLinkedList() + >>> cq.enqueue('a') + >>> cq.enqueue('b') + >>> cq.dequeue() + 'a' + >>> cq.dequeue() + 'b' + >>> cq.dequeue() + Traceback (most recent call last): + ... + Exception: Empty Queue + """ if self.rear is None: return @@ -49,6 +109,22 @@ self.rear.data = data def dequeue(self) -> Any: + """ + Removes and retrieves the first element of the queue + + >>> cq = CircularQueueLinkedList() + >>> cq.dequeue() + Traceback (most recent call last): + ... + Exception: Empty Queue + >>> cq.enqueue('a') + >>> cq.dequeue() + 'a' + >>> cq.dequeue() + Traceback (most recent call last): + ... + Exception: Empty Queue + """ self.check_can_perform_operation() if self.rear is None or self.front is None: return None @@ -82,4 +158,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: if i.isdigit(): # RULE 1 operand_stack.push(int(i)) elif i in operators: # RULE 2 operator_stack.push(i) elif i == ")": # RULE 4 opr = operator_stack.peek() operator_stack.pop() num1 = operand_stack.peek() operand_stack.pop() num2 = operand_stack.peek() operand_stack.pop() total = operators[opr](num2, num1) operand_stack.push(total) # RULE 5 return operand_stack.peek() if __name__ == "__main__": equation = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 print(f"{equation} = {dijkstras_two_stack_algorithm(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: (5 + ((4 * 2) * (2 + 3))) + +THESE ARE THE ALGORITHM'S RULES: +RULE 1: Scan the expression from left to right. When an operand is encountered, + push it onto the operand stack. + +RULE 2: When an operator is encountered in the expression, + push it onto the operator stack. + +RULE 3: When a left parenthesis is encountered in the expression, ignore it. + +RULE 4: When a right parenthesis is encountered in the expression, + pop an operator off the operator stack. The two operands it must + operate on must be the last two operands pushed onto the operand stack. + We therefore pop the operand stack twice, perform the operation, + and push the result back onto the operand stack so it will be available + for use as an operand of the next operator popped off the operator stack. + +RULE 5: When the entire infix expression has been scanned, the value left on + the operand stack represents the value of the expression. + +NOTE: It only works with whole numbers. +""" __author__ = "Alexander Joslin" @@ -7,6 +38,18 @@ def dijkstras_two_stack_algorithm(equation: str) -> int: + """ + DocTests + >>> dijkstras_two_stack_algorithm("(5 + 3)") + 8 + >>> dijkstras_two_stack_algorithm("((9 - (2 + 9)) + (8 - 1))") + 5 + >>> dijkstras_two_stack_algorithm("((((3 - 2) - (2 + 3)) + (2 - 4)) + 3)") + -3 + + :param equation: a string + :return: result: an integer + """ operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} operand_stack: Stack[int] = Stack() @@ -38,4 +81,4 @@ if __name__ == "__main__": equation = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 - print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")+ print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")
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._Node | None = None class _Iterator: __slots__ = ("_cur",) def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: return self def __next__(self) -> Any: if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: for val in iterable: self.appendleft(val) def pop(self) -> Any: # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back # if only one element in the queue: point the front and back to None # else remove one element from back if self._front == self._back: self._front = None self._back = None else: self._back = self._back.prev_node # set new back # drop the last node, python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front # if only one element in the queue: point the front and back to None # else remove one element from front if self._front == self._back: self._front = None self._back = None else: self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: return self._front is None def __len__(self) -> int: return self._len def __eq__(self, other: object) -> bool: if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: return Deque._Iterator(self._front) def __repr__(self) -> str: values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]" if __name__ == "__main__": import doctest doctest.testmod() dq = Deque([3]) dq.pop()
--- +++ @@ -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 + extendleft(iterable: Iterable) -> None + pop() -> Any + popleft() -> Any + Observers + --------- + is_empty() -> bool + Attributes + ---------- + _front: _Node + front of the deque a.k.a. the first element + _back: _Node + back of the element a.k.a. the last element + _len: int + the number of nodes + """ __slots__ = ("_back", "_front", "_len") @dataclass class _Node: + """ + Representation of a node. + Contains a value and a pointer to the next node as well as to the previous one. + """ val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: + """ + Helper class for iteration. Will be used to implement iteration. + Attributes + ---------- + _cur: _Node + the current node of the iteration. + """ __slots__ = ("_cur",) @@ -25,9 +61,23 @@ self._cur = cur def __iter__(self) -> Deque._Iterator: + """ + >>> our_deque = Deque([1, 2, 3]) + >>> iterator = iter(our_deque) + """ return self def __next__(self) -> Any: + """ + >>> our_deque = Deque([1, 2, 3]) + >>> iterator = iter(our_deque) + >>> next(iterator) + 1 + >>> next(iterator) + 2 + >>> next(iterator) + 3 + """ if self._cur is None: # finished iterating raise StopIteration @@ -47,6 +97,31 @@ self.append(val) def append(self, val: Any) -> None: + """ + Adds val to the end of the deque. + Time complexity: O(1) + >>> our_deque_1 = Deque([1, 2, 3]) + >>> our_deque_1.append(4) + >>> our_deque_1 + [1, 2, 3, 4] + >>> our_deque_2 = Deque('ab') + >>> our_deque_2.append('c') + >>> our_deque_2 + ['a', 'b', 'c'] + >>> from collections import deque + >>> deque_collections_1 = deque([1, 2, 3]) + >>> deque_collections_1.append(4) + >>> deque_collections_1 + deque([1, 2, 3, 4]) + >>> deque_collections_2 = deque('ab') + >>> deque_collections_2.append('c') + >>> deque_collections_2 + deque(['a', 'b', 'c']) + >>> list(our_deque_1) == list(deque_collections_1) + True + >>> list(our_deque_2) == list(deque_collections_2) + True + """ node = self._Node(val, None, None) if self.is_empty(): # front = back @@ -64,6 +139,31 @@ assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: + """ + Adds val to the beginning of the deque. + Time complexity: O(1) + >>> our_deque_1 = Deque([2, 3]) + >>> our_deque_1.appendleft(1) + >>> our_deque_1 + [1, 2, 3] + >>> our_deque_2 = Deque('bc') + >>> our_deque_2.appendleft('a') + >>> our_deque_2 + ['a', 'b', 'c'] + >>> from collections import deque + >>> deque_collections_1 = deque([2, 3]) + >>> deque_collections_1.appendleft(1) + >>> deque_collections_1 + deque([1, 2, 3]) + >>> deque_collections_2 = deque('bc') + >>> deque_collections_2.appendleft('a') + >>> deque_collections_2 + deque(['a', 'b', 'c']) + >>> list(our_deque_1) == list(deque_collections_1) + True + >>> list(our_deque_2) == list(deque_collections_2) + True + """ node = self._Node(val, None, None) if self.is_empty(): # front = back @@ -81,14 +181,94 @@ assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: + """ + Appends every value of iterable to the end of the deque. + Time complexity: O(n) + >>> our_deque_1 = Deque([1, 2, 3]) + >>> our_deque_1.extend([4, 5]) + >>> our_deque_1 + [1, 2, 3, 4, 5] + >>> our_deque_2 = Deque('ab') + >>> our_deque_2.extend('cd') + >>> our_deque_2 + ['a', 'b', 'c', 'd'] + >>> from collections import deque + >>> deque_collections_1 = deque([1, 2, 3]) + >>> deque_collections_1.extend([4, 5]) + >>> deque_collections_1 + deque([1, 2, 3, 4, 5]) + >>> deque_collections_2 = deque('ab') + >>> deque_collections_2.extend('cd') + >>> deque_collections_2 + deque(['a', 'b', 'c', 'd']) + >>> list(our_deque_1) == list(deque_collections_1) + True + >>> list(our_deque_2) == list(deque_collections_2) + True + """ for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: + """ + Appends every value of iterable to the beginning of the deque. + Time complexity: O(n) + >>> our_deque_1 = Deque([1, 2, 3]) + >>> our_deque_1.extendleft([0, -1]) + >>> our_deque_1 + [-1, 0, 1, 2, 3] + >>> our_deque_2 = Deque('cd') + >>> our_deque_2.extendleft('ba') + >>> our_deque_2 + ['a', 'b', 'c', 'd'] + >>> from collections import deque + >>> deque_collections_1 = deque([1, 2, 3]) + >>> deque_collections_1.extendleft([0, -1]) + >>> deque_collections_1 + deque([-1, 0, 1, 2, 3]) + >>> deque_collections_2 = deque('cd') + >>> deque_collections_2.extendleft('ba') + >>> deque_collections_2 + deque(['a', 'b', 'c', 'd']) + >>> list(our_deque_1) == list(deque_collections_1) + True + >>> list(our_deque_2) == list(deque_collections_2) + True + """ for val in iterable: self.appendleft(val) def pop(self) -> Any: + """ + Removes the last element of the deque and returns it. + Time complexity: O(1) + @returns topop.val: the value of the node to pop. + >>> our_deque1 = Deque([1]) + >>> our_popped1 = our_deque1.pop() + >>> our_popped1 + 1 + >>> our_deque1 + [] + + >>> our_deque2 = Deque([1, 2, 3, 15182]) + >>> our_popped2 = our_deque2.pop() + >>> our_popped2 + 15182 + >>> our_deque2 + [1, 2, 3] + + >>> from collections import deque + >>> deque_collections = deque([1, 2, 3, 15182]) + >>> collections_popped = deque_collections.pop() + >>> collections_popped + 15182 + >>> deque_collections + deque([1, 2, 3]) + >>> list(our_deque2) == list(deque_collections) + True + >>> our_popped2 == collections_popped + True + """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." @@ -108,6 +288,34 @@ return topop.val def popleft(self) -> Any: + """ + Removes the first element of the deque and returns it. + Time complexity: O(1) + @returns topop.val: the value of the node to pop. + >>> our_deque1 = Deque([1]) + >>> our_popped1 = our_deque1.pop() + >>> our_popped1 + 1 + >>> our_deque1 + [] + >>> our_deque2 = Deque([15182, 1, 2, 3]) + >>> our_popped2 = our_deque2.popleft() + >>> our_popped2 + 15182 + >>> our_deque2 + [1, 2, 3] + >>> from collections import deque + >>> deque_collections = deque([15182, 1, 2, 3]) + >>> collections_popped = deque_collections.popleft() + >>> collections_popped + 15182 + >>> deque_collections + deque([1, 2, 3]) + >>> list(our_deque2) == list(deque_collections) + True + >>> our_popped2 == collections_popped + True + """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." @@ -126,12 +334,68 @@ return topop.val def is_empty(self) -> bool: + """ + Checks if the deque is empty. + Time complexity: O(1) + >>> our_deque = Deque([1, 2, 3]) + >>> our_deque.is_empty() + False + >>> our_empty_deque = Deque() + >>> our_empty_deque.is_empty() + True + >>> from collections import deque + >>> empty_deque_collections = deque() + >>> list(our_empty_deque) == list(empty_deque_collections) + True + """ return self._front is None def __len__(self) -> int: + """ + Implements len() function. Returns the length of the deque. + Time complexity: O(1) + >>> our_deque = Deque([1, 2, 3]) + >>> len(our_deque) + 3 + >>> our_empty_deque = Deque() + >>> len(our_empty_deque) + 0 + >>> from collections import deque + >>> deque_collections = deque([1, 2, 3]) + >>> len(deque_collections) + 3 + >>> empty_deque_collections = deque() + >>> len(empty_deque_collections) + 0 + >>> len(our_empty_deque) == len(empty_deque_collections) + True + """ return self._len def __eq__(self, other: object) -> bool: + """ + Implements "==" operator. Returns if *self* is equal to *other*. + Time complexity: O(n) + >>> our_deque_1 = Deque([1, 2, 3]) + >>> our_deque_2 = Deque([1, 2, 3]) + >>> our_deque_1 == our_deque_2 + True + >>> our_deque_3 = Deque([1, 2]) + >>> our_deque_1 == our_deque_3 + False + >>> from collections import deque + >>> deque_collections_1 = deque([1, 2, 3]) + >>> deque_collections_2 = deque([1, 2, 3]) + >>> deque_collections_1 == deque_collections_2 + True + >>> deque_collections_3 = deque([1, 2]) + >>> deque_collections_1 == deque_collections_3 + False + >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) + True + >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) + True + """ if not isinstance(other, Deque): return NotImplemented @@ -153,9 +417,34 @@ return True def __iter__(self) -> Deque._Iterator: + """ + Implements iteration. + Time complexity: O(1) + >>> our_deque = Deque([1, 2, 3]) + >>> for v in our_deque: + ... print(v) + 1 + 2 + 3 + >>> from collections import deque + >>> deque_collections = deque([1, 2, 3]) + >>> for v in deque_collections: + ... print(v) + 1 + 2 + 3 + """ return Deque._Iterator(self._front) def __repr__(self) -> str: + """ + Implements representation of the deque. + Represents it as a list, with its values between '[' and ']'. + Time complexity: O(n) + >>> our_deque = Deque([1, 2, 3]) + >>> our_deque + [1, 2, 3] + """ values_list = [] aux = self._front while aux is not None: @@ -171,4 +460,4 @@ doctest.testmod() dq = Deque([3]) - dq.pop()+ dq.pop()
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.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") self.queues[priority].append(data) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2") def dequeue(self) -> int: for queue in self.queues: if queue: return queue.pop(0) raise UnderFlowError("All queues are empty") def __str__(self) -> str: return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues)) class ElementPriorityQueue: def __init__(self): self.queue = [] def enqueue(self, data: int) -> None: if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data) def dequeue(self) -> int: if not self.queue: raise UnderFlowError("The queue is empty") else: data = min(self.queue) self.queue.remove(data) return data def __str__(self) -> str: return str(self.queue) def fixed_priority_queue(): fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) fpq.enqueue(0, 100) fpq.enqueue(2, 1) fpq.enqueue(2, 5) fpq.enqueue(1, 7) fpq.enqueue(2, 4) fpq.enqueue(1, 64) fpq.enqueue(0, 128) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) def element_priority_queue(): epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) epq.enqueue(100) epq.enqueue(1) epq.enqueue(5) epq.enqueue(7) epq.enqueue(4) epq.enqueue(64) epq.enqueue(128) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
--- +++ @@ -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 + are removed then the Task with the highest priority is removed in FIFO order. In + code we will use three levels of priority with priority zero Tasks being the most + urgent (high priority) and priority 2 tasks being the least urgent. + + Examples + >>> fpq = FixedPriorityQueue() + >>> fpq.enqueue(0, 10) + >>> fpq.enqueue(1, 70) + >>> fpq.enqueue(0, 100) + >>> fpq.enqueue(2, 1) + >>> fpq.enqueue(2, 5) + >>> fpq.enqueue(1, 7) + >>> fpq.enqueue(2, 4) + >>> fpq.enqueue(1, 64) + >>> fpq.enqueue(0, 128) + >>> print(fpq) + Priority 0: [10, 100, 128] + Priority 1: [70, 7, 64] + Priority 2: [1, 5, 4] + >>> fpq.dequeue() + 10 + >>> fpq.dequeue() + 100 + >>> fpq.dequeue() + 128 + >>> fpq.dequeue() + 70 + >>> fpq.dequeue() + 7 + >>> print(fpq) + Priority 0: [] + Priority 1: [64] + Priority 2: [1, 5, 4] + >>> fpq.dequeue() + 64 + >>> fpq.dequeue() + 1 + >>> fpq.dequeue() + 5 + >>> fpq.dequeue() + 4 + >>> fpq.dequeue() + Traceback (most recent call last): + ... + data_structures.queues.priority_queue_using_list.UnderFlowError: All queues are empty + >>> print(fpq) + Priority 0: [] + Priority 1: [] + Priority 2: [] + """ # noqa: E501 def __init__(self): self.queues = [ @@ -18,6 +74,11 @@ ] def enqueue(self, priority: int, data: int) -> None: + """ + Add an element to a queue based on its priority. + If the priority is invalid ValueError is raised. + If the queue is full an OverFlowError is raised. + """ try: if len(self.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") @@ -26,6 +87,10 @@ raise ValueError("Valid priorities are 0, 1, and 2") def dequeue(self) -> int: + """ + Return the highest priority element in FIFO order. + If the queue is empty then an under flow exception is raised. + """ for queue in self.queues: if queue: return queue.pop(0) @@ -36,16 +101,68 @@ class ElementPriorityQueue: + """ + Element Priority Queue is the same as Fixed Priority Queue except that the value of + the element itself is the priority. The rules for priorities are the same the as + Fixed Priority Queue. + + >>> epq = ElementPriorityQueue() + >>> epq.enqueue(10) + >>> epq.enqueue(70) + >>> epq.enqueue(4) + >>> epq.enqueue(1) + >>> epq.enqueue(5) + >>> epq.enqueue(7) + >>> epq.enqueue(4) + >>> epq.enqueue(64) + >>> epq.enqueue(128) + >>> print(epq) + [10, 70, 4, 1, 5, 7, 4, 64, 128] + >>> epq.dequeue() + 1 + >>> epq.dequeue() + 4 + >>> epq.dequeue() + 4 + >>> epq.dequeue() + 5 + >>> epq.dequeue() + 7 + >>> epq.dequeue() + 10 + >>> print(epq) + [70, 64, 128] + >>> epq.dequeue() + 64 + >>> epq.dequeue() + 70 + >>> epq.dequeue() + 128 + >>> epq.dequeue() + Traceback (most recent call last): + ... + data_structures.queues.priority_queue_using_list.UnderFlowError: The queue is empty + >>> print(epq) + [] + """ def __init__(self): self.queue = [] def enqueue(self, data: int) -> None: + """ + This function enters the element into the queue + If the queue is full an Exception is raised saying Over Flow! + """ if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data) def dequeue(self) -> int: + """ + Return the highest priority element in FIFO order. + If the queue is empty then an under flow exception is raised. + """ if not self.queue: raise UnderFlowError("The queue is empty") else: @@ -54,6 +171,9 @@ return data def __str__(self) -> str: + """ + Prints all the elements within the Element Priority Queue + """ return str(self.queue) @@ -109,4 +229,4 @@ if __name__ == "__main__": fixed_priority_queue() - element_priority_queue()+ element_priority_queue()
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 | str: if token in OPERATORS: return token try: return float(token) except ValueError: msg = f"{token} is neither a number nor a valid operator" raise ValueError(msg) def evaluate(post_fix: list[str], verbose: bool = False) -> float: if not post_fix: return 0 # Checking the list to find out whether the postfix expression is valid valid_expression = [parse_token(token) for token in post_fix] if verbose: # print table header print("Symbol".center(8), "Action".center(12), "Stack", sep=" | ") print("-" * (30 + len(post_fix))) stack = [] for x in valid_expression: if x not in OPERATORS: stack.append(x) # append x to stack if verbose: # output in tabular format print( f"{x}".rjust(8), f"push({x})".ljust(12), stack, sep=" | ", ) continue # If x is operator # If only 1 value is inside the stack and + or - is encountered # then this is unary + or - case if x in UNARY_OP_SYMBOLS and len(stack) < 2: b = stack.pop() # pop stack if x == "-": b *= -1 # negate b stack.append(b) if verbose: # output in tabular format print( "".rjust(8), f"pop({b})".ljust(12), stack, sep=" | ", ) print( str(x).rjust(8), f"push({x}{b})".ljust(12), stack, sep=" | ", ) continue b = stack.pop() # pop stack if verbose: # output in tabular format print( "".rjust(8), f"pop({b})".ljust(12), stack, sep=" | ", ) a = stack.pop() # pop stack if verbose: # output in tabular format print( "".rjust(8), f"pop({a})".ljust(12), stack, sep=" | ", ) # evaluate the 2 values popped from stack & push result to stack stack.append(OPERATORS[x](a, b)) # type: ignore[index] if verbose: # output in tabular format print( f"{x}".rjust(8), f"push({a}{x}{b})".ljust(12), stack, sep=" | ", ) # If everything is executed correctly, the stack will contain # only one element which is the result if len(stack) != 1: raise ArithmeticError("Input is not a valid postfix expression") return float(stack[0]) if __name__ == "__main__": # Create a loop so that the user can evaluate postfix expressions multiple times while True: expression = input("Enter a Postfix Expression (space separated): ").split(" ") prompt = "Do you want to see stack contents while evaluating? [y/N]: " verbose = input(prompt).strip().lower() == "y" output = evaluate(expression, verbose) print("Result = ", output) prompt = "Do you want to enter another expression? [y/N]: " if input(prompt).strip().lower() != "y": break
--- +++ @@ -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. + +Output: + +Enter a Postfix Equation (space separated) = 5 6 9 * + + Symbol | Action | Stack +----------------------------------- + 5 | push(5) | 5 + 6 | push(6) | 5,6 + 9 | push(9) | 5,6,9 + | pop(9) | 5,6 + | pop(6) | 5 + * | push(6*9) | 5,54 + | pop(54) | 5 + | pop(5) | + + | push(5+54) | 59 + + Result = 59 +""" # Defining valid unary operator symbols UNARY_OP_SYMBOLS = ("-", "+") @@ -13,6 +38,20 @@ def parse_token(token: str | float) -> float | str: + """ + Converts the given data to the appropriate number if it is indeed a number, else + returns the data as it is with a False flag. This function also serves as a check + of whether the input is a number or not. + + Parameters + ---------- + token: The data that needs to be converted to the appropriate operator or number. + + Returns + ------- + float or str + Returns a float if `token` is a number or a str if `token` is an operator + """ if token in OPERATORS: return token try: @@ -23,6 +62,51 @@ def evaluate(post_fix: list[str], verbose: bool = False) -> float: + """ + Evaluate postfix expression using a stack. + >>> evaluate(["0"]) + 0.0 + >>> evaluate(["-0"]) + -0.0 + >>> evaluate(["1"]) + 1.0 + >>> evaluate(["-1"]) + -1.0 + >>> evaluate(["-1.1"]) + -1.1 + >>> evaluate(["2", "1", "+", "3", "*"]) + 9.0 + >>> evaluate(["2", "1.9", "+", "3", "*"]) + 11.7 + >>> evaluate(["2", "-1.9", "+", "3", "*"]) + 0.30000000000000027 + >>> evaluate(["4", "13", "5", "/", "+"]) + 6.6 + >>> evaluate(["2", "-", "3", "+"]) + 1.0 + >>> evaluate(["-4", "5", "*", "6", "-"]) + -26.0 + >>> evaluate([]) + 0 + >>> evaluate(["4", "-", "6", "7", "/", "9", "8"]) + Traceback (most recent call last): + ... + ArithmeticError: Input is not a valid postfix expression + + Parameters + ---------- + post_fix: + The postfix expression is tokenized into operators and operands and stored + as a Python list + + verbose: + Display stack contents while evaluating the expression if verbose is True + + Returns + ------- + float + The evaluated value + """ if not post_fix: return 0 # Checking the list to find out whether the postfix expression is valid @@ -113,4 +197,4 @@ print("Result = ", output) prompt = "Do you want to enter another expression? [y/N]: " if input(prompt).strip().lower() != "y": - break+ break
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 # Speeds up the append() operation def __iter__(self) -> Iterator[int]: node = self.head while node: yield node.data node = node.next_node def __repr__(self) -> str: return " -> ".join([str(data) for data in self]) def append(self, data: int) -> None: if self.tail: self.tail.next_node = self.tail = Node(data) else: self.head = self.tail = Node(data) def extend(self, items: Iterable[int]) -> None: for item in items: self.append(item) def make_linked_list(elements_list: Iterable[int]) -> LinkedList: if not elements_list: raise Exception("The Elements List is empty") linked_list = LinkedList() linked_list.extend(elements_list) return linked_list def in_reverse(linked_list: LinkedList) -> str: return " <- ".join(str(line) for line in reversed(tuple(linked_list))) if __name__ == "__main__": from doctest import testmod testmod() linked_list = make_linked_list((14, 52, 14, 12, 43)) print(f"Linked List: {linked_list}") print(f"Reverse List: {in_reverse(linked_list)}")
--- +++ @@ -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() + >>> (linked_list.head, linked_list.tail) + (None, None) + """ self.head: Node | None = None self.tail: Node | None = None # Speeds up the append() operation def __iter__(self) -> Iterator[int]: + """Iterate the LinkedList yielding each Node's data. + >>> linked_list = LinkedList() + >>> items = (1, 2, 3, 4, 5) + >>> linked_list.extend(items) + >>> tuple(linked_list) == items + True + """ node = self.head while node: yield node.data node = node.next_node def __repr__(self) -> str: + """Returns a string representation of the LinkedList. + >>> linked_list = LinkedList() + >>> str(linked_list) + '' + >>> linked_list.append(1) + >>> str(linked_list) + '1' + >>> linked_list.extend([2, 3, 4, 5]) + >>> str(linked_list) + '1 -> 2 -> 3 -> 4 -> 5' + """ return " -> ".join([str(data) for data in self]) def append(self, data: int) -> None: + """Appends a new node with the given data to the end of the LinkedList. + >>> linked_list = LinkedList() + >>> str(linked_list) + '' + >>> linked_list.append(1) + >>> str(linked_list) + '1' + >>> linked_list.append(2) + >>> str(linked_list) + '1 -> 2' + """ if self.tail: self.tail.next_node = self.tail = Node(data) else: self.head = self.tail = Node(data) def extend(self, items: Iterable[int]) -> None: + """Appends each item to the end of the LinkedList. + >>> linked_list = LinkedList() + >>> linked_list.extend([]) + >>> str(linked_list) + '' + >>> linked_list.extend([1, 2]) + >>> str(linked_list) + '1 -> 2' + >>> linked_list.extend([3,4]) + >>> str(linked_list) + '1 -> 2 -> 3 -> 4' + """ for item in items: self.append(item) def make_linked_list(elements_list: Iterable[int]) -> LinkedList: + """Creates a Linked List from the elements of the given sequence + (list/tuple) and returns the head of the Linked List. + >>> make_linked_list([]) + Traceback (most recent call last): + ... + Exception: The Elements List is empty + >>> make_linked_list([7]) + 7 + >>> make_linked_list(['abc']) + abc + >>> make_linked_list([7, 25]) + 7 -> 25 + """ if not elements_list: raise Exception("The Elements List is empty") @@ -46,6 +108,12 @@ def in_reverse(linked_list: LinkedList) -> str: + """Prints the elements of the given Linked List in reverse order + >>> in_reverse(LinkedList()) + '' + >>> in_reverse(make_linked_list([69, 88, 73])) + '73 <- 88 <- 69' + """ return " <- ".join(str(line) for line in reversed(tuple(linked_list))) @@ -55,4 +123,4 @@ testmod() linked_list = make_linked_list((14, 52, 14, 12, 43)) print(f"Linked List: {linked_list}") - print(f"Reverse List: {in_reverse(linked_list)}")+ print(f"Reverse List: {in_reverse(linked_list)}")
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): next_element: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: next_element = arr[j] break result.append(next_element) return result def next_greatest_element_fast(arr: list[float]) -> list[float]: result = [] for i, outer in enumerate(arr): next_item: float = -1 for inner in arr[i + 1 :]: if outer < inner: next_item = inner break result.append(next_item) return result def next_greatest_element(arr: list[float]) -> list[float]: arr_size = len(arr) stack: list[float] = [] result: list[float] = [-1] * arr_size for index in reversed(range(arr_size)): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: result[index] = stack[-1] stack.append(arr[index]) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) setup = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
--- +++ @@ -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 + of O(n^2), where n is the size of the array. + + Args: + arr: List of numbers for which the NGE is calculated. + + Returns: + List containing the next greatest elements. If no + greater element is found, -1 is placed in the result. + + Example: + >>> next_greatest_element_slow(arr) == expect + True + """ result = [] arr_size = len(arr) @@ -20,6 +38,25 @@ def next_greatest_element_fast(arr: list[float]) -> list[float]: + """ + Find the Next Greatest Element (NGE) for each element in the array + using a more readable approach. This implementation utilizes + enumerate() for the outer loop and slicing for the inner loop. + + While this improves readability over next_greatest_element_slow(), + it still has a time complexity of O(n^2). + + Args: + arr: List of numbers for which the NGE is calculated. + + Returns: + List containing the next greatest elements. If no + greater element is found, -1 is placed in the result. + + Example: + >>> next_greatest_element_fast(arr) == expect + True + """ result = [] for i, outer in enumerate(arr): next_item: float = -1 @@ -32,6 +69,27 @@ def next_greatest_element(arr: list[float]) -> list[float]: + """ + Efficient solution to find the Next Greatest Element (NGE) for all elements + using a stack. The time complexity is reduced to O(n), making it suitable + for larger arrays. + + The stack keeps track of elements for which the next greater element hasn't + been found yet. By iterating through the array in reverse (from the last + element to the first), the stack is used to efficiently determine the next + greatest element for each element. + + Args: + arr: List of numbers for which the NGE is calculated. + + Returns: + List containing the next greatest elements. If no + greater element is found, -1 is placed in the result. + + Example: + >>> next_greatest_element(arr) == expect + True + """ arr_size = len(arr) stack: list[float] = [] result: list[float] = [-1] * arr_size @@ -72,4 +130,4 @@ print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), - )+ )
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_rep def make_linked_list(elements_list: list | tuple) -> Node: # if elements_list is empty if not elements_list: raise ValueError("The Elements List is empty") # Set first element as Head head = Node(elements_list[0]) current = head # Loop through elements from position 1 for data in elements_list[1:]: current.next = Node(data) current = current.next return head
--- +++ @@ -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.""" string_rep = "" temp = self while temp: @@ -16,6 +21,27 @@ def make_linked_list(elements_list: list | tuple) -> Node: + """ + Creates a Linked List from the elements of the given sequence + (list/tuple) and returns the head of the Linked List. + + >>> make_linked_list([]) + Traceback (most recent call last): + ... + ValueError: The Elements List is empty + >>> make_linked_list(()) + Traceback (most recent call last): + ... + ValueError: The Elements List is empty + >>> make_linked_list([1]) + <1> ---> <END> + >>> make_linked_list((1,)) + <1> ---> <END> + >>> make_linked_list([1, 3, 5, 32, 44, 12, 43]) + <1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END> + >>> make_linked_list((1, 3, 5, 32, 44, 12, 43)) + <1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END> + """ # if elements_list is empty if not elements_list: @@ -28,4 +54,4 @@ for data in elements_list[1:]: current.next = Node(data) current = current.next - return head+ return head
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 __repr__(self) -> str: return f"Queue({tuple(self._stack2[::-1] + self._stack1)})" def put(self, item: T) -> None: self._stack1.append(item) def get(self) -> T: # To reduce number of attribute look-ups in `while` loop. stack1_pop = self._stack1.pop stack2_append = self._stack2.append if not self._stack2: while self._stack1: stack2_append(stack1_pop()) if not self._stack2: raise IndexError("Queue is empty") return self._stack2.pop() if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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]) + Queue((10, 20, 30)) + >>> QueueByTwoStacks((i**2 for i in range(1, 4))) + Queue((1, 4, 9)) + """ self._stack1: list[T] = list(iterable or []) self._stack2: list[T] = [] def __len__(self) -> int: + """ + >>> len(QueueByTwoStacks()) + 0 + >>> from string import ascii_lowercase + >>> len(QueueByTwoStacks(ascii_lowercase)) + 26 + >>> queue = QueueByTwoStacks() + >>> for i in range(1, 11): + ... queue.put(i) + ... + >>> len(queue) + 10 + >>> for i in range(2): + ... queue.get() + 1 + 2 + >>> len(queue) + 8 + """ return len(self._stack1) + len(self._stack2) def __repr__(self) -> str: + """ + >>> queue = QueueByTwoStacks() + >>> queue + Queue(()) + >>> str(queue) + 'Queue(())' + >>> queue.put(10) + >>> queue + Queue((10,)) + >>> queue.put(20) + >>> queue.put(30) + >>> queue + Queue((10, 20, 30)) + """ return f"Queue({tuple(self._stack2[::-1] + self._stack1)})" def put(self, item: T) -> None: + """ + Put `item` into the Queue + + >>> queue = QueueByTwoStacks() + >>> queue.put(10) + >>> queue.put(20) + >>> len(queue) + 2 + >>> queue + Queue((10, 20)) + """ self._stack1.append(item) def get(self) -> T: + """ + Get `item` from the Queue + + >>> queue = QueueByTwoStacks((10, 20, 30)) + >>> queue.get() + 10 + >>> queue.put(40) + >>> queue.get() + 20 + >>> queue.get() + 30 + >>> len(queue) + 1 + >>> queue.get() + 40 + >>> queue.get() + Traceback (most recent call last): + ... + IndexError: Queue is empty + """ # To reduce number of attribute look-ups in `while` loop. stack1_pop = self._stack1.pop @@ -36,4 +109,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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("image_data/lena.jpg") as img: # Change contrast to 170 cont_img = change_contrast(img, 170) cont_img.save("image_data/lena_high_contrast.png", format="png")
--- +++ @@ -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__": - # Load image - with Image.open("image_data/lena.jpg") as img: - # Change contrast to 170 - cont_img = change_contrast(img, 170) - cont_img.save("image_data/lena_high_contrast.png", format="png")+""" +Changing contrast with PIL + +This algorithm is used in +https://noivce.pythonanywhere.com/ Python web app. + +psf/black: True +ruff : True +""" + +from PIL import Image + + +def change_contrast(img: Image, level: int) -> Image: + """ + Function to change contrast + """ + factor = (259 * (level + 255)) / (255 * (259 - level)) + + def contrast(c: int) -> int: + """ + Fundamental Transformation/Operation that'll be performed on + every bit. + """ + return int(128 + factor * (c - 128)) + + return img.point(contrast) + + +if __name__ == "__main__": + # Load image + with Image.open("image_data/lena.jpg") as img: + # Change contrast to 170 + cont_img = change_contrast(img, 170) + cont_img.save("image_data/lena_high_contrast.png", format="png")
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 __bool__(self) -> bool: return bool(self.stack) def __str__(self) -> str: return str(self.stack) def push(self, data: T) -> None: if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self) -> T: if not self.stack: raise StackUnderflowError return self.stack.pop() def peek(self) -> T: if not self.stack: raise StackUnderflowError return self.stack[-1] def is_empty(self) -> bool: return not bool(self.stack) def is_full(self) -> bool: return self.size() == self.limit def size(self) -> int: return len(self.stack) def __contains__(self, item: T) -> bool: return item in self.stack def test_stack() -> None: stack: Stack[int] = Stack(10) assert bool(stack) is False assert stack.is_empty() is True assert stack.is_full() is False assert str(stack) == "[]" try: _ = stack.pop() raise AssertionError # This should not happen except StackUnderflowError: assert True # This should happen try: _ = stack.peek() raise AssertionError # This should not happen except StackUnderflowError: assert True # This should happen for i in range(10): assert stack.size() == i stack.push(i) assert bool(stack) assert not stack.is_empty() assert stack.is_full() assert str(stack) == str(list(range(10))) assert stack.pop() == 9 assert stack.peek() == 8 stack.push(100) assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]) try: stack.push(200) raise AssertionError # This should not happen except StackOverflowError: assert True # This should happen assert not stack.is_empty() assert stack.size() == 10 assert 5 in stack assert 55 not in stack if __name__ == "__main__": test_stack() import doctest doctest.testmod()
--- +++ @@ -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 elements come off of a stack are + Last In, First Out (LIFO). + https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + """ def __init__(self, limit: int = 10): self.stack: list[T] = [] @@ -26,34 +33,135 @@ return str(self.stack) def push(self, data: T) -> None: + """ + Push an element to the top of the stack. + + >>> S = Stack(2) # stack size = 2 + >>> S.push(10) + >>> S.push(20) + >>> print(S) + [10, 20] + + >>> S = Stack(1) # stack size = 1 + >>> S.push(10) + >>> S.push(20) + Traceback (most recent call last): + ... + data_structures.stacks.stack.StackOverflowError + + """ if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self) -> T: + """ + Pop an element off of the top of the stack. + + >>> S = Stack() + >>> S.push(-5) + >>> S.push(10) + >>> S.pop() + 10 + + >>> Stack().pop() + Traceback (most recent call last): + ... + data_structures.stacks.stack.StackUnderflowError + """ if not self.stack: raise StackUnderflowError return self.stack.pop() def peek(self) -> T: + """ + Peek at the top-most element of the stack. + + >>> S = Stack() + >>> S.push(-5) + >>> S.push(10) + >>> S.peek() + 10 + + >>> Stack().peek() + Traceback (most recent call last): + ... + data_structures.stacks.stack.StackUnderflowError + """ if not self.stack: raise StackUnderflowError return self.stack[-1] def is_empty(self) -> bool: + """ + Check if a stack is empty. + + >>> S = Stack() + >>> S.is_empty() + True + + >>> S = Stack() + >>> S.push(10) + >>> S.is_empty() + False + """ return not bool(self.stack) def is_full(self) -> bool: + """ + >>> S = Stack() + >>> S.is_full() + False + + >>> S = Stack(1) + >>> S.push(10) + >>> S.is_full() + True + """ return self.size() == self.limit def size(self) -> int: + """ + Return the size of the stack. + + >>> S = Stack(3) + >>> S.size() + 0 + + >>> S = Stack(3) + >>> S.push(10) + >>> S.size() + 1 + + >>> S = Stack(3) + >>> S.push(10) + >>> S.push(20) + >>> S.size() + 2 + """ return len(self.stack) def __contains__(self, item: T) -> bool: + """ + Check if item is in stack + + >>> S = Stack(3) + >>> S.push(10) + >>> 10 in S + True + + >>> S = Stack(3) + >>> S.push(10) + >>> 20 in S + False + """ return item in self.stack def test_stack() -> None: + """ + >>> test_stack() + """ stack: Stack[int] = Stack(10) assert bool(stack) is False assert stack.is_empty() is True @@ -104,4 +212,4 @@ import doctest - doctest.testmod()+ doctest.testmod()
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): # Pop elements from stack while stack is not # empty and top of stack is smaller than price[i] while len(st) > 0 and price[st[-1]] <= price[i]: st.pop() # If stack becomes empty, then price[i] is greater # than all elements on left of it, i.e. price[0], # price[1], ..price[i-1]. Else the price[i] is # greater than elements after top of stack s[i] = i + 1 if len(st) <= 0 else (i - st[-1]) # Push this element to stack st.append(i) return s # A utility function to print elements of array def print_array(arr, n): for i in range(n): print(arr[i], end=" ") # Driver program to test above function price = [10, 4, 5, 90, 120, 80] # Calculate the span values S = calculate_span(price) # Print the calculated span values print_array(S, len(price))
--- +++ @@ -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 the given day, for which the price of the stock +on the current day is less than or equal to its price on the given day. +""" def calculate_span(price: list[int]) -> list[int]: + """ + Calculate the span values for a given list of stock prices. + Args: + price: List of stock prices. + Returns: + List of span values. + + >>> calculate_span([10, 4, 5, 90, 120, 80]) + [1, 1, 2, 4, 5, 1] + >>> calculate_span([100, 50, 60, 70, 80, 90]) + [1, 1, 2, 3, 4, 5] + >>> calculate_span([5, 4, 3, 2, 1]) + [1, 1, 1, 1, 1] + >>> calculate_span([1, 2, 3, 4, 5]) + [1, 2, 3, 4, 5] + >>> calculate_span([10, 20, 30, 40, 50]) + [1, 2, 3, 4, 5] + >>> calculate_span([100, 80, 60, 70, 60, 75, 85]) + [1, 1, 1, 2, 1, 4, 6] + """ n = len(price) s = [0] * n # Create a stack and push index of fist element to it @@ -42,4 +70,4 @@ S = calculate_span(price) # Print the calculated span values -print_array(S, len(price))+print_array(S, len(price))
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.entries)})" def put(self, item: T) -> None: self.entries.append(item) def get(self) -> T: if not self.entries: raise IndexError("Queue is empty") return self.entries.pop(0) def rotate(self, rotation: int) -> None: put = self.entries.append get = self.entries.pop for _ in range(rotation): put(get(0)) def get_front(self) -> T: return self.entries[0] if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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((10, 20, 30)) + >>> QueueByList((i**2 for i in range(1, 4))) + Queue((1, 4, 9)) + """ self.entries: list[T] = list(iterable or []) def __len__(self) -> int: + """ + >>> len(QueueByList()) + 0 + >>> from string import ascii_lowercase + >>> len(QueueByList(ascii_lowercase)) + 26 + >>> queue = QueueByList() + >>> for i in range(1, 11): + ... queue.put(i) + >>> len(queue) + 10 + >>> for i in range(2): + ... queue.get() + 1 + 2 + >>> len(queue) + 8 + """ return len(self.entries) def __repr__(self) -> str: + """ + >>> queue = QueueByList() + >>> queue + Queue(()) + >>> str(queue) + 'Queue(())' + >>> queue.put(10) + >>> queue + Queue((10,)) + >>> queue.put(20) + >>> queue.put(30) + >>> queue + Queue((10, 20, 30)) + """ return f"Queue({tuple(self.entries)})" def put(self, item: T) -> None: + """Put `item` to the Queue + + >>> queue = QueueByList() + >>> queue.put(10) + >>> queue.put(20) + >>> len(queue) + 2 + >>> queue + Queue((10, 20)) + """ self.entries.append(item) def get(self) -> T: + """ + Get `item` from the Queue + + >>> queue = QueueByList((10, 20, 30)) + >>> queue.get() + 10 + >>> queue.put(40) + >>> queue.get() + 20 + >>> queue.get() + 30 + >>> len(queue) + 1 + >>> queue.get() + 40 + >>> queue.get() + Traceback (most recent call last): + ... + IndexError: Queue is empty + """ if not self.entries: raise IndexError("Queue is empty") return self.entries.pop(0) def rotate(self, rotation: int) -> None: + """Rotate the items of the Queue `rotation` times + + >>> queue = QueueByList([10, 20, 30, 40]) + >>> queue + Queue((10, 20, 30, 40)) + >>> queue.rotate(1) + >>> queue + Queue((20, 30, 40, 10)) + >>> queue.rotate(2) + >>> queue + Queue((40, 10, 20, 30)) + """ put = self.entries.append get = self.entries.pop @@ -33,6 +116,18 @@ put(get(0)) def get_front(self) -> T: + """Get the front item from the Queue + + >>> queue = QueueByList((10, 20, 30)) + >>> queue.get_front() + 10 + >>> queue + Queue((10, 20, 30)) + >>> queue.get() + 10 + >>> queue.get_front() + 20 + """ return self.entries[0] @@ -40,4 +135,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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( "Symbol".center(8), "Stack".center(print_width), "Postfix".center(print_width), sep=" | ", ) print("-" * (print_width * 3 + 7)) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(x) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(x) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered if len(stack) == 0: # close bracket without open bracket raise IndexError("list index out of range") while stack[-1] != "(": post_fix.append(stack.pop()) # Pop stack & add the content to Postfix stack.pop() elif len(stack) == 0: stack.append(x) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while stack and stack[-1] != "(" and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop()) # pop stack & add to Postfix stack.append(x) # push x to stack print( x.center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) # Output in tabular format while len(stack) > 0: # while stack is not empty if stack[-1] == "(": # open bracket with no close bracket raise ValueError("invalid expression") post_fix.append(stack.pop()) # pop stack & add to Postfix print( " ".center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) # Output in tabular format return "".join(post_fix) # return Postfix as str def infix_2_prefix(infix: str) -> str: reversed_infix = list(infix[::-1]) # reverse the infix equation for i in range(len(reversed_infix)): if reversed_infix[i] == "(": reversed_infix[i] = ")" # change "(" to ")" elif reversed_infix[i] == ")": reversed_infix[i] = "(" # change ")" to "(" # call infix_2_postfix on Infix, return reverse of Postfix return (infix_2_postfix("".join(reversed_infix)))[::-1] if __name__ == "__main__": from doctest import testmod testmod() Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation Infix = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
--- +++ @@ -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) -> +a^bc (Prefix) +""" def infix_2_postfix(infix: str) -> str: + """ + >>> infix_2_postfix("a+b^c") # doctest: +NORMALIZE_WHITESPACE + Symbol | Stack | Postfix + ---------------------------- + a | | a + + | + | a + b | + | ab + ^ | +^ | ab + c | +^ | abc + | + | abc^ + | | abc^+ + 'abc^+' + + >>> infix_2_postfix("1*((-a)*2+b)") # doctest: +NORMALIZE_WHITESPACE + Symbol | Stack | Postfix + ------------------------------------------- + 1 | | 1 + * | * | 1 + ( | *( | 1 + ( | *(( | 1 + - | *((- | 1 + a | *((- | 1a + ) | *( | 1a- + * | *(* | 1a- + 2 | *(* | 1a-2 + + | *(+ | 1a-2* + b | *(+ | 1a-2*b + ) | * | 1a-2*b+ + | | 1a-2*b+* + '1a-2*b+*' + + >>> infix_2_postfix("") + Symbol | Stack | Postfix + ---------------------------- + '' + + >>> infix_2_postfix("(()") + Traceback (most recent call last): + ... + ValueError: invalid expression + + >>> infix_2_postfix("())") + Traceback (most recent call last): + ... + IndexError: list index out of range + """ stack = [] post_fix = [] priority = { @@ -64,6 +125,51 @@ def infix_2_prefix(infix: str) -> str: + """ + >>> infix_2_prefix("a+b^c") # doctest: +NORMALIZE_WHITESPACE + Symbol | Stack | Postfix + ---------------------------- + c | | c + ^ | ^ | c + b | ^ | cb + + | + | cb^ + a | + | cb^a + | | cb^a+ + '+a^bc' + + >>> infix_2_prefix("1*((-a)*2+b)") # doctest: +NORMALIZE_WHITESPACE + Symbol | Stack | Postfix + ------------------------------------------- + ( | ( | + b | ( | b + + | (+ | b + 2 | (+ | b2 + * | (+* | b2 + ( | (+*( | b2 + a | (+*( | b2a + - | (+*(- | b2a + ) | (+* | b2a- + ) | | b2a-*+ + * | * | b2a-*+ + 1 | * | b2a-*+1 + | | b2a-*+1* + '*1+*-a2b' + + >>> infix_2_prefix('') + Symbol | Stack | Postfix + ---------------------------- + '' + + >>> infix_2_prefix('(()') + Traceback (most recent call last): + ... + IndexError: list index out of range + + >>> infix_2_prefix('())') + Traceback (most recent call last): + ... + ValueError: invalid expression + """ reversed_infix = list(infix[::-1]) # reverse the infix equation for i in range(len(reversed_infix)): @@ -83,4 +189,4 @@ Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation Infix = "".join(Infix.split()) # Remove spaces from the input - print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")+ print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
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 # Initialize next as null self.prev: Node[T] | None = None # Initialize prev as null class Stack[T]: def __init__(self) -> None: self.head: Node[T] | None = None def push(self, data: T) -> None: if self.head is None: self.head = Node(data) else: new_node = Node(data) self.head.prev = new_node new_node.next = self.head new_node.prev = None self.head = new_node def pop(self) -> T | None: if self.head is None: return None else: assert self.head is not None temp = self.head.data self.head = self.head.next if self.head is not None: self.head.prev = None return temp def top(self) -> T | None: return self.head.data if self.head is not None else None def __len__(self) -> int: temp = self.head count = 0 while temp is not None: count += 1 temp = temp.next return count def is_empty(self) -> bool: return self.head is None def print_stack(self) -> None: print("stack elements are:") temp = self.head while temp is not None: print(temp.data, end="->") temp = temp.next # Code execution starts here if __name__ == "__main__": # Start with the empty stack stack: Stack[int] = Stack() # Insert 4 at the beginning. So stack becomes 4->None print("Stack operations using Doubly LinkedList") stack.push(4) # Insert 5 at the beginning. So stack becomes 4->5->None stack.push(5) # Insert 6 at the beginning. So stack becomes 4->5->6->None stack.push(6) # Insert 7 at the beginning. So stack becomes 4->5->6->7->None stack.push(7) # Print the stack stack.print_stack() # Print the top element print("\nTop element is ", stack.top()) # Print the stack size print("Size of the stack is ", len(stack)) # pop the top element stack.pop() # pop the top element stack.pop() # two elements have now been popped off stack.print_stack() # Print True if the stack is empty else False print("\nstack is empty:", stack.is_empty())
--- +++ @@ -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 - self.next: Node[T] | None = None # Initialize next as null - self.prev: Node[T] | None = None # Initialize prev as null - - -class Stack[T]: - - def __init__(self) -> None: - self.head: Node[T] | None = None - - def push(self, data: T) -> None: - if self.head is None: - self.head = Node(data) - else: - new_node = Node(data) - self.head.prev = new_node - new_node.next = self.head - new_node.prev = None - self.head = new_node - - def pop(self) -> T | None: - if self.head is None: - return None - else: - assert self.head is not None - temp = self.head.data - self.head = self.head.next - if self.head is not None: - self.head.prev = None - return temp - - def top(self) -> T | None: - return self.head.data if self.head is not None else None - - def __len__(self) -> int: - temp = self.head - count = 0 - while temp is not None: - count += 1 - temp = temp.next - return count - - def is_empty(self) -> bool: - return self.head is None - - def print_stack(self) -> None: - print("stack elements are:") - temp = self.head - while temp is not None: - print(temp.data, end="->") - temp = temp.next - - -# Code execution starts here -if __name__ == "__main__": - # Start with the empty stack - stack: Stack[int] = Stack() - - # Insert 4 at the beginning. So stack becomes 4->None - print("Stack operations using Doubly LinkedList") - stack.push(4) - - # Insert 5 at the beginning. So stack becomes 4->5->None - stack.push(5) - - # Insert 6 at the beginning. So stack becomes 4->5->6->None - stack.push(6) - - # Insert 7 at the beginning. So stack becomes 4->5->6->7->None - stack.push(7) - - # Print the stack - stack.print_stack() - - # Print the top element - print("\nTop element is ", stack.top()) - - # Print the stack size - print("Size of the stack is ", len(stack)) - - # pop the top element - stack.pop() - - # pop the top element - stack.pop() - - # two elements have now been popped off - stack.print_stack() - - # Print True if the stack is empty else False - print("\nstack is empty:", stack.is_empty())+# 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 # Initialize next as null + self.prev: Node[T] | None = None # Initialize prev as null + + +class Stack[T]: + """ + >>> stack = Stack() + >>> stack.is_empty() + True + >>> stack.print_stack() + stack elements are: + >>> for i in range(4): + ... stack.push(i) + ... + >>> stack.is_empty() + False + >>> stack.print_stack() + stack elements are: + 3->2->1->0-> + >>> stack.top() + 3 + >>> len(stack) + 4 + >>> stack.pop() + 3 + >>> stack.print_stack() + stack elements are: + 2->1->0-> + """ + + def __init__(self) -> None: + self.head: Node[T] | None = None + + def push(self, data: T) -> None: + """add a Node to the stack""" + if self.head is None: + self.head = Node(data) + else: + new_node = Node(data) + self.head.prev = new_node + new_node.next = self.head + new_node.prev = None + self.head = new_node + + def pop(self) -> T | None: + """pop the top element off the stack""" + if self.head is None: + return None + else: + assert self.head is not None + temp = self.head.data + self.head = self.head.next + if self.head is not None: + self.head.prev = None + return temp + + def top(self) -> T | None: + """return the top element of the stack""" + return self.head.data if self.head is not None else None + + def __len__(self) -> int: + temp = self.head + count = 0 + while temp is not None: + count += 1 + temp = temp.next + return count + + def is_empty(self) -> bool: + return self.head is None + + def print_stack(self) -> None: + print("stack elements are:") + temp = self.head + while temp is not None: + print(temp.data, end="->") + temp = temp.next + + +# Code execution starts here +if __name__ == "__main__": + # Start with the empty stack + stack: Stack[int] = Stack() + + # Insert 4 at the beginning. So stack becomes 4->None + print("Stack operations using Doubly LinkedList") + stack.push(4) + + # Insert 5 at the beginning. So stack becomes 4->5->None + stack.push(5) + + # Insert 6 at the beginning. So stack becomes 4->5->6->None + stack.push(6) + + # Insert 7 at the beginning. So stack becomes 4->5->6->7->None + stack.push(7) + + # Print the stack + stack.print_stack() + + # Print the top element + print("\nTop element is ", stack.top()) + + # Print the stack size + print("Size of the stack is ", len(stack)) + + # pop the top element + stack.pop() + + # pop the top element + stack.pop() + + # two elements have now been popped off + stack.print_stack() + + # Print True if the stack is empty else False + print("\nstack is empty:", stack.is_empty())
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, ints: Iterable[int]) -> None: self.head: Node | None = None for i in sorted(ints, reverse=True): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def __str__(self) -> str: return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
--- +++ @@ -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)) == tuple(sorted(test_data_odd)) + True + >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) + True + """ node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: + """ + >>> for i in range(3): + ... len(SortedLinkedList(range(i))) == i + True + True + True + >>> len(SortedLinkedList(test_data_odd)) + 8 + """ return sum(1 for _ in self) def __str__(self) -> str: + """ + >>> str(SortedLinkedList([])) + '' + >>> str(SortedLinkedList(test_data_odd)) + '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' + >>> str(SortedLinkedList(test_data_even)) + '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' + """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: + """ + >>> SSL = SortedLinkedList + >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) + >>> len(merged) + 16 + >>> str(merged) + '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' + >>> list(merged) == list(sorted(test_data_odd + test_data_even)) + True + """ return SortedLinkedList(list(sll_one) + list(sll_two)) @@ -44,4 +80,4 @@ doctest.testmod() SSL = SortedLinkedList - print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))+ print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
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]: def __init__(self) -> None: self.top: Node[T] | None = None def __iter__(self) -> Iterator[T]: node = self.top while node: yield node.data node = node.next def __str__(self) -> str: return "->".join([str(item) for item in self]) def __len__(self) -> int: return len(tuple(iter(self))) def is_empty(self) -> bool: return self.top is None def push(self, item: T) -> None: node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> T: if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> T: if self.is_empty(): raise IndexError("peek from empty stack") assert self.top is not None return self.top.data def clear(self) -> None: self.top = None if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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: - return f"{self.data}" - - -class LinkedStack[T]: - - def __init__(self) -> None: - self.top: Node[T] | None = None - - def __iter__(self) -> Iterator[T]: - node = self.top - while node: - yield node.data - node = node.next - - def __str__(self) -> str: - return "->".join([str(item) for item in self]) - - def __len__(self) -> int: - return len(tuple(iter(self))) - - def is_empty(self) -> bool: - return self.top is None - - def push(self, item: T) -> None: - node = Node(item) - if not self.is_empty(): - node.next = self.top - self.top = node - - def pop(self) -> T: - if self.is_empty(): - raise IndexError("pop from empty stack") - assert isinstance(self.top, Node) - pop_node = self.top - self.top = self.top.next - return pop_node.data - - def peek(self) -> T: - if self.is_empty(): - raise IndexError("peek from empty stack") - - assert self.top is not None - return self.top.data - - def clear(self) -> None: - self.top = None - - -if __name__ == "__main__": - from doctest import testmod - - testmod()+"""A Stack using a linked list like structure""" + +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]: + """ + Linked List Stack implementing push (to top), + pop (from top) and is_empty + + >>> stack = LinkedStack() + >>> stack.is_empty() + True + >>> stack.push(5) + >>> stack.push(9) + >>> stack.push('python') + >>> stack.is_empty() + False + >>> stack.pop() + 'python' + >>> stack.push('algorithms') + >>> stack.pop() + 'algorithms' + >>> stack.pop() + 9 + >>> stack.pop() + 5 + >>> stack.is_empty() + True + >>> stack.pop() + Traceback (most recent call last): + ... + IndexError: pop from empty stack + """ + + def __init__(self) -> None: + self.top: Node[T] | None = None + + def __iter__(self) -> Iterator[T]: + node = self.top + while node: + yield node.data + node = node.next + + def __str__(self) -> str: + """ + >>> stack = LinkedStack() + >>> stack.push("c") + >>> stack.push("b") + >>> stack.push("a") + >>> str(stack) + 'a->b->c' + """ + return "->".join([str(item) for item in self]) + + def __len__(self) -> int: + """ + >>> stack = LinkedStack() + >>> len(stack) == 0 + True + >>> stack.push("c") + >>> stack.push("b") + >>> stack.push("a") + >>> len(stack) == 3 + True + """ + return len(tuple(iter(self))) + + def is_empty(self) -> bool: + """ + >>> stack = LinkedStack() + >>> stack.is_empty() + True + >>> stack.push(1) + >>> stack.is_empty() + False + """ + return self.top is None + + def push(self, item: T) -> None: + """ + >>> stack = LinkedStack() + >>> stack.push("Python") + >>> stack.push("Java") + >>> stack.push("C") + >>> str(stack) + 'C->Java->Python' + """ + node = Node(item) + if not self.is_empty(): + node.next = self.top + self.top = node + + def pop(self) -> T: + """ + >>> stack = LinkedStack() + >>> stack.pop() + Traceback (most recent call last): + ... + IndexError: pop from empty stack + >>> stack.push("c") + >>> stack.push("b") + >>> stack.push("a") + >>> stack.pop() == 'a' + True + >>> stack.pop() == 'b' + True + >>> stack.pop() == 'c' + True + """ + if self.is_empty(): + raise IndexError("pop from empty stack") + assert isinstance(self.top, Node) + pop_node = self.top + self.top = self.top.next + return pop_node.data + + def peek(self) -> T: + """ + >>> stack = LinkedStack() + >>> stack.push("Java") + >>> stack.push("C") + >>> stack.push("Python") + >>> stack.peek() + 'Python' + """ + if self.is_empty(): + raise IndexError("peek from empty stack") + + assert self.top is not None + return self.top.data + + def clear(self) -> None: + """ + >>> stack = LinkedStack() + >>> stack.push("Java") + >>> stack.push("C") + >>> stack.push("Python") + >>> str(stack) + 'Python->C->Java' + >>> stack.clear() + >>> len(stack) == 0 + True + """ + self.top = None + + +if __name__ == "__main__": + from doctest import testmod + + testmod()
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: curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True def find(self, word: str) -> bool: curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf def delete(self, word: str) -> None: def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): # If word does not exist if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] char_node = curr.nodes.get(char) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr _delete(self, word, 0) def print_words(node: TrieNode, word: str) -> None: if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) # print_words(root, "") assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_trie() def main() -> None: print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": main()
--- +++ @@ -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 optimal approach when space is not an issue. +""" class TrieNode: @@ -6,10 +12,20 @@ self.is_leaf = False def insert_many(self, words: list[str]) -> None: + """ + Inserts a list of words into the Trie + :param words: list of string words + :return: None + """ for word in words: self.insert(word) def insert(self, word: str) -> None: + """ + Inserts a word into the Trie + :param word: word to be inserted + :return: None + """ curr = self for char in word: if char not in curr.nodes: @@ -18,6 +34,11 @@ curr.is_leaf = True def find(self, word: str) -> bool: + """ + Tries to find word in a Trie + :param word: word to look for + :return: Returns True if word is found, False otherwise + """ curr = self for char in word: if char not in curr.nodes: @@ -26,6 +47,11 @@ return curr.is_leaf def delete(self, word: str) -> None: + """ + Deletes a word in a Trie + :param word: word to delete + :return: None + """ def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): @@ -50,6 +76,12 @@ def print_words(node: TrieNode, word: str) -> None: + """ + Prints all the words in a Trie + :param node: root node of Trie + :param word: Word variable should be empty at start + :return: None + """ if node.is_leaf: print(word, end=" ") @@ -85,8 +117,11 @@ def main() -> None: + """ + >>> pytests() + """ print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": - main()+ main()
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.prefix = prefix def match(self, word: str) -> tuple[str, str, str]: x = 0 for q, w in zip(self.prefix, word): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def insert_many(self, words: list[str]) -> None: for word in words: self.insert(word) def insert(self, word: str) -> None: # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word and not self.is_leaf: self.is_leaf = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: self.nodes[word[0]] = RadixNode(prefix=word, is_leaf=True) else: incoming_node = self.nodes[word[0]] matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(remaining_word) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: incoming_node.prefix = remaining_prefix aux_node = self.nodes[matching_string[0]] self.nodes[matching_string[0]] = RadixNode(matching_string, False) self.nodes[matching_string[0]].nodes[remaining_prefix[0]] = aux_node if remaining_word == "": self.nodes[matching_string[0]].is_leaf = True else: self.nodes[matching_string[0]].insert(remaining_word) def find(self, word: str) -> bool: incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: _matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(remaining_word) def delete(self, word: str) -> bool: incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: _matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(remaining_word) # If it is not a leaf, we don't have to delete elif not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes) == 1 and not self.is_leaf: merging_node = next(iter(self.nodes.values())) self.is_leaf = merging_node.is_leaf self.prefix += merging_node.prefix self.nodes = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes) > 1: incoming_node.is_leaf = False # If there is 1 edge, we merge it with its child else: merging_node = next(iter(incoming_node.nodes.values())) incoming_node.is_leaf = merging_node.is_leaf incoming_node.prefix += merging_node.prefix incoming_node.nodes = merging_node.nodes return True def print_tree(self, height: int = 0) -> None: if self.prefix != "": print("-" * height, self.prefix, " (leaf)" if self.is_leaf else "") for value in self.nodes.values(): value.print_tree(height + 1) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = RadixNode() root.insert_many(words) assert all(root.find(word) for word in words) assert not root.find("bandanas") assert not root.find("apps") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def pytests() -> None: assert test_trie() def main() -> None: root = RadixNode() words = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(words) print("Words:", words) print("Tree:") root.print_tree() if __name__ == "__main__": main()
--- +++ @@ -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(self, word: str) -> tuple[str, str, str]: + """Compute the common substring of the prefix of the node and a word + + Args: + word (str): word to compare + + Returns: + (str, str, str): common substring, remaining prefix, remaining word + + >>> RadixNode("myprefix").match("mystring") + ('my', 'prefix', 'string') + """ x = 0 for q, w in zip(self.prefix, word): if q != w: @@ -21,10 +37,31 @@ return self.prefix[:x], self.prefix[x:], word[x:] def insert_many(self, words: list[str]) -> None: + """Insert many words in the tree + + Args: + words (list[str]): list of words + + >>> RadixNode("myprefix").insert_many(["mystring", "hello"]) + """ for word in words: self.insert(word) def insert(self, word: str) -> None: + """Insert a word into the tree + + Args: + word (str): word to insert + + >>> RadixNode("myprefix").insert("mystring") + + >>> root = RadixNode() + >>> root.insert_many(['myprefix', 'myprefixA', 'myprefixAA']) + >>> root.print_tree() + - myprefix (leaf) + -- A (leaf) + --- A (leaf) + """ # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word and not self.is_leaf: @@ -63,6 +100,17 @@ self.nodes[matching_string[0]].insert(remaining_word) def find(self, word: str) -> bool: + """Returns if the word is on the tree + + Args: + word (str): word to check + + Returns: + bool: True if the word appears on the tree + + >>> RadixNode("myprefix").find("mystring") + False + """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False @@ -81,6 +129,17 @@ return incoming_node.find(remaining_word) def delete(self, word: str) -> bool: + """Deletes a word from the tree if it exists + + Args: + word (str): word to be deleted + + Returns: + bool: True if the word was found and deleted. False if word is not found + + >>> RadixNode("myprefix").delete("mystring") + False + """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False @@ -120,6 +179,11 @@ return True def print_tree(self, height: int = 0) -> None: + """Print the tree + + Args: + height (int, optional): Height of the printed node + """ if self.prefix != "": print("-" * height, self.prefix, " (leaf)" if self.is_leaf else "") @@ -149,6 +213,9 @@ def main() -> None: + """ + >>> pytests() + """ root = RadixNode() words = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(words) @@ -159,4 +226,4 @@ if __name__ == "__main__": - main()+ main()
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_coordinate: int, y_coordinate: int) -> int: center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] # skip get_neighbors_pixel if center is null if center is None: return 0 # Starting from the top right, assigning value to pixels clockwise binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] # Converting the binary value to decimal. return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the # local binary pattern value for each pixel. for i in range(image.shape[0]): for j in range(image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
--- +++ @@ -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. values present at boundaries. + + :param image: The image we're working with + :param x_coordinate: x-coordinate of the pixel + :param y_coordinate: The y coordinate of the pixel + :param center: center pixel value + :return: The value of the pixel is being returned. + """ try: return int(image[x_coordinate][y_coordinate] >= center) @@ -13,6 +24,17 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: + """ + It takes an image, an x and y coordinate, and returns the + decimal value of the local binary patternof the pixel + at that coordinate + + :param image: the image to be processed + :param x_coordinate: x coordinate of the pixel + :param y_coordinate: the y coordinate of the pixel + :return: The decimal value of the binary value of the pixels + around the center pixel. + """ center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] @@ -55,4 +77,4 @@ cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) - cv2.destroyAllWindows()+ cv2.destroyAllWindows()
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_threshold < threshold < self.max_threshold: msg = f"Factor value should be from 0 to {self.max_threshold}" raise ValueError(msg) self.input_img = input_img self.threshold = threshold self.width, self.height = self.input_img.shape[1], self.input_img.shape[0] # error table size (+4 columns and +1 row) greater than input image because of # lack of if statements self.error_table = [ [0 for _ in range(self.height + 4)] for __ in range(self.width + 1) ] self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255 @classmethod def get_greyscale(cls, blue: int, green: int, red: int) -> float: """ Formula from https://en.wikipedia.org/wiki/HSL_and_HSV cf Lightness section, and Fig 13c. We use the first of four possible. """ return 0.114 * blue + 0.587 * green + 0.299 * red def process(self) -> None: for y in range(self.height): for x in range(self.width): greyscale = int(self.get_greyscale(*self.input_img[y][x])) if self.threshold > greyscale + self.error_table[y][x]: self.output_img[y][x] = (0, 0, 0) current_error = greyscale + self.error_table[y][x] else: self.output_img[y][x] = (255, 255, 255) current_error = greyscale + self.error_table[y][x] - 255 """ Burkes error propagation (`*` is current pixel): * 8/32 4/32 2/32 4/32 8/32 4/32 2/32 """ self.error_table[y][x + 1] += int(8 / 32 * current_error) self.error_table[y][x + 2] += int(4 / 32 * current_error) self.error_table[y + 1][x] += int(8 / 32 * current_error) self.error_table[y + 1][x + 1] += int(4 / 32 * current_error) self.error_table[y + 1][x + 2] += int(2 / 32 * current_error) self.error_table[y + 1][x - 1] += int(4 / 32 * current_error) self.error_table[y + 1][x - 2] += int(2 / 32 * current_error) if __name__ == "__main__": # create Burke's instances with original images in greyscale burkes_instances = [ Burkes(imread("image_data/lena.jpg", 1), threshold) for threshold in (1, 126, 130, 140) ] for burkes in burkes_instances: burkes.process() for burkes in burkes_instances: imshow( f"Original image with dithering threshold: {burkes.threshold}", burkes.output_img, ) waitKey(0) destroyAllWindows()
--- +++ @@ -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.wikipedia.org/wiki/Dither + + Note: + * Best results are given with threshold= ~1/2 * max greyscale value. + * This implementation get RGB image and converts it to greyscale in runtime. + """ def __init__(self, input_img, threshold: int): self.min_threshold = 0 @@ -27,6 +38,14 @@ @classmethod def get_greyscale(cls, blue: int, green: int, red: int) -> float: + """ + >>> Burkes.get_greyscale(3, 4, 5) + 4.185 + >>> Burkes.get_greyscale(0, 0, 0) + 0.0 + >>> Burkes.get_greyscale(255, 255, 255) + 255.0 + """ """ Formula from https://en.wikipedia.org/wiki/HSL_and_HSV cf Lightness section, and Fig 13c. @@ -76,4 +95,4 @@ ) waitKey(0) - destroyAllWindows()+ destroyAllWindows()
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 dilation(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation > 0) return output if __name__ == "__main__": # read original image lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) output = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
--- +++ @@ -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: - return (gray > 127) & (gray <= 255) - - -def dilation(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: - output = np.zeros_like(image) - image_padded = np.zeros( - (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) - ) - - # Copy image to padded image - image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image - - # Iterate over image & apply kernel - for x in range(image.shape[1]): - for y in range(image.shape[0]): - summation = ( - kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] - ).sum() - output[y, x] = int(summation > 0) - return output - - -if __name__ == "__main__": - # read original image - lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" - lena = np.array(Image.open(lena_path)) - # kernel to be applied - structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) - output = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) - # Save the output image - pil_img = Image.fromarray(output).convert("RGB") - pil_img.save("result_dilation.png")+from pathlib import Path + +import numpy as np +from PIL import Image + + +def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: + """ + Return gray image from rgb image + >>> rgb_to_gray(np.array([[[127, 255, 0]]])) + array([[187.6453]]) + >>> rgb_to_gray(np.array([[[0, 0, 0]]])) + array([[0.]]) + >>> rgb_to_gray(np.array([[[2, 4, 1]]])) + array([[3.0598]]) + >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) + array([[159.0524, 90.0635, 117.6989]]) + """ + 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 binary image from gray image + >>> gray_to_binary(np.array([[127, 255, 0]])) + array([[False, True, False]]) + >>> gray_to_binary(np.array([[0]])) + array([[False]]) + >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]])) + array([[False, False, False]]) + >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) + array([[False, True, False], + [False, True, False], + [False, True, False]]) + """ + return (gray > 127) & (gray <= 255) + + +def dilation(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: + """ + Return dilated image + >>> dilation(np.array([[True, False, True]]), np.array([[0, 1, 0]])) + array([[False, False, False]]) + >>> dilation(np.array([[False, False, True]]), np.array([[1, 0, 1]])) + array([[False, False, False]]) + """ + output = np.zeros_like(image) + image_padded = np.zeros( + (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) + ) + + # Copy image to padded image + image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image + + # Iterate over image & apply kernel + for x in range(image.shape[1]): + for y in range(image.shape[0]): + summation = ( + kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] + ).sum() + output[y, x] = int(summation > 0) + return output + + +if __name__ == "__main__": + # read original image + lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" + lena = np.array(Image.open(lena_path)) + # kernel to be applied + structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) + output = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) + # Save the output image + pil_img = Image.fromarray(output).convert("RGB") + pil_img.save("result_dilation.png")
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_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None): if red is not None: self.red = red if green is not None: self.green = green if blue is not None: self.blue = blue if red_edge is not None: self.redEdge = red_edge if nir is not None: self.nir = nir return True def calculation( self, index="", red=None, green=None, blue=None, red_edge=None, nir=None ): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) funcs = { "ARVI2": self.arv12, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!") return False def arv12(self): return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def ccci(self): return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def cvi(self): return self.nir * (self.red / (self.green**2)) def gli(self): return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def ndvi(self): return (self.nir - self.red) / (self.nir + self.red) def bndvi(self): return (self.nir - self.blue) / (self.nir + self.blue) def red_edge_ndvi(self): return (self.redEdge - self.red) / (self.redEdge + self.red) def gndvi(self): return (self.nir - self.green) / (self.nir + self.green) def gbndvi(self): return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def grndvi(self): return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def rbndvi(self): return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def pndvi(self): return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def atsavi(self, x=0.08, a=1.22, b=0.03): return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def bwdrvi(self): return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def ci_green(self): return (self.nir / self.green) - 1 def ci_rededge(self): return (self.nir / self.redEdge) - 1 def ci(self): return (self.red - self.blue) / self.red def ctvi(self): ndvi = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def gdvi(self): return self.nir - self.green def evi(self): return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def gemi(self): n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def gosavi(self, y=0.16): return (self.nir - self.green) / (self.nir + self.green + y) def gsavi(self, n=0.5): return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def hue(self): return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def ivi(self, a=None, b=None): return (self.nir - b) / (a * self.red) def ipvi(self): return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def i(self): return (self.red + self.green + self.blue) / 30.5 def rvi(self): return self.nir / self.red def mrvi(self): return (self.rvi() - 1) / (self.rvi() + 1) def m_savi(self): return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def norm_g(self): return self.green / (self.nir + self.red + self.green) def norm_nir(self): return self.nir / (self.nir + self.red + self.green) def norm_r(self): return self.red / (self.nir + self.red + self.green) def ngrdi(self): return (self.green - self.red) / (self.green + self.red) def ri(self): return (self.red - self.green) / (self.red + self.green) def s(self): max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (max_value - min_value) / max_value def _if(self): return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def dvi(self): return self.nir / self.red def tvi(self): return (self.ndvi() + 0.5) ** (1 / 2) def ndre(self): return (self.nir - self.redEdge) / (self.nir + self.redEdge) """ # genering a random matrices to test this class red = np.ones((1000,1000, 1),dtype="float64") * 46787 green = np.ones((1000,1000, 1),dtype="float64") * 23487 blue = np.ones((1000,1000, 1),dtype="float64") * 14578 redEdge = np.ones((1000,1000, 1),dtype="float64") * 51045 nir = np.ones((1000,1000, 1),dtype="float64") * 52200 # Examples of how to use the class # instantiating the class cl = IndexCalculation() # instantiating the class with the values #cl = indexCalculation(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # how set the values after instantiate the class cl, (for update the data or when don't # instantiating the class with the values) cl.setMatrices(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # calculating the indices for the instantiated values in the class # Note: the CCCI index can be changed to any index implemented in the class. indexValue_form1 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) indexValue_form2 = cl.CCCI() # calculating the index with the values directly -- you can set just the values # preferred note: the *calculation* function performs the function *setMatrices* indexValue_form3 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) print("Form 1: "+np.array2string(indexValue_form1, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 2: "+np.array2string(indexValue_form2, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 3: "+np.array2string(indexValue_form3, precision=20, separator=', ', floatmode='maxprec_equal')) # A list of examples results for different type of data at NDVI # float16 -> 0.31567383 #NDVI (red = 50, nir = 100) # float32 -> 0.31578946 #NDVI (red = 50, nir = 100) # float64 -> 0.3157894736842105 #NDVI (red = 50, nir = 100) # longdouble -> 0.3157894736842105 #NDVI (red = 50, nir = 100) """
--- +++ @@ -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 to define the data and to calculate the + implemented indices. + + # Vegetation index + https://en.wikipedia.org/wiki/Vegetation_Index + A Vegetation Index (VI) is a spectral transformation of two or more bands + designed to enhance the contribution of vegetation properties and allow + reliable spatial and temporal inter-comparisons of terrestrial + photosynthetic activity and canopy structural variations + + # Information about channels (Wavelength range for each) + * nir - near-infrared + https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy + Wavelength Range 700 nm to 2500 nm + * Red Edge + https://en.wikipedia.org/wiki/Red_edge + Wavelength Range 680 nm to 730 nm + * red + https://en.wikipedia.org/wiki/Color + Wavelength Range 635 nm to 700 nm + * blue + https://en.wikipedia.org/wiki/Color + Wavelength Range 450 nm to 490 nm + * green + https://en.wikipedia.org/wiki/Color + Wavelength Range 520 nm to 560 nm + + + # Implemented index list + #"abbreviationOfIndexName" -- list of channels used + + #"ARVI2" -- red, nir + #"CCCI" -- red, redEdge, nir + #"CVI" -- red, green, nir + #"GLI" -- red, green, blue + #"NDVI" -- red, nir + #"BNDVI" -- blue, nir + #"redEdgeNDVI" -- red, redEdge + #"GNDVI" -- green, nir + #"GBNDVI" -- green, blue, nir + #"GRNDVI" -- red, green, nir + #"RBNDVI" -- red, blue, nir + #"PNDVI" -- red, green, blue, nir + #"ATSAVI" -- red, nir + #"BWDRVI" -- blue, nir + #"CIgreen" -- green, nir + #"CIrededge" -- redEdge, nir + #"CI" -- red, blue + #"CTVI" -- red, nir + #"GDVI" -- green, nir + #"EVI" -- red, blue, nir + #"GEMI" -- red, nir + #"GOSAVI" -- green, nir + #"GSAVI" -- green, nir + #"Hue" -- red, green, blue + #"IVI" -- red, nir + #"IPVI" -- red, nir + #"I" -- red, green, blue + #"RVI" -- red, nir + #"MRVI" -- red, nir + #"MSAVI" -- red, nir + #"NormG" -- red, green, nir + #"NormNIR" -- red, green, nir + #"NormR" -- red, green, nir + #"NGRDI" -- red, green + #"RI" -- red, green + #"S" -- red, green, blue + #"IF" -- red, green, blue + #"DVI" -- red, nir + #"TVI" -- red, nir + #"NDRE" -- redEdge, nir + + #list of all index implemented + #allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI", + "GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI", + "BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI", + "GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI", + "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", + "S", "IF", "DVI", "TVI", "NDRE"] + + #list of index with not blue channel + #notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI", + "GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI", + "GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI", + "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI", + "TVI", "NDRE"] + + #list of index just with RGB channels + #RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"] + """ def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) @@ -29,6 +123,10 @@ def calculation( self, index="", red=None, green=None, blue=None, red_edge=None, nir=None ): + """ + performs the calculation of the index with the values instantiated in the class + :str index: abbreviation of index name to perform + """ self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) funcs = { "ARVI2": self.arv12, @@ -80,146 +178,351 @@ return False def arv12(self): + """ + Atmospherically Resistant Vegetation Index 2 + https://www.indexdatabase.de/db/i-single.php?id=396 + :return: index + -0.18+1.17*(self.nir-self.red)/(self.nir+self.red) + """ return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def ccci(self): + """ + Canopy Chlorophyll Content Index + https://www.indexdatabase.de/db/i-single.php?id=224 + :return: index + """ return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def cvi(self): + """ + Chlorophyll vegetation index + https://www.indexdatabase.de/db/i-single.php?id=391 + :return: index + """ return self.nir * (self.red / (self.green**2)) def gli(self): + """ + self.green leaf index + https://www.indexdatabase.de/db/i-single.php?id=375 + :return: index + """ return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def ndvi(self): + """ + Normalized Difference self.nir/self.red Normalized Difference Vegetation + Index, Calibrated NDVI - CDVI + https://www.indexdatabase.de/db/i-single.php?id=58 + :return: index + """ return (self.nir - self.red) / (self.nir + self.red) def bndvi(self): + """ + Normalized Difference self.nir/self.blue self.blue-normalized difference + vegetation index + https://www.indexdatabase.de/db/i-single.php?id=135 + :return: index + """ return (self.nir - self.blue) / (self.nir + self.blue) def red_edge_ndvi(self): + """ + Normalized Difference self.rededge/self.red + https://www.indexdatabase.de/db/i-single.php?id=235 + :return: index + """ return (self.redEdge - self.red) / (self.redEdge + self.red) def gndvi(self): + """ + Normalized Difference self.nir/self.green self.green NDVI + https://www.indexdatabase.de/db/i-single.php?id=401 + :return: index + """ return (self.nir - self.green) / (self.nir + self.green) def gbndvi(self): + """ + self.green-self.blue NDVI + https://www.indexdatabase.de/db/i-single.php?id=186 + :return: index + """ return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def grndvi(self): + """ + self.green-self.red NDVI + https://www.indexdatabase.de/db/i-single.php?id=185 + :return: index + """ return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def rbndvi(self): + """ + self.red-self.blue NDVI + https://www.indexdatabase.de/db/i-single.php?id=187 + :return: index + """ return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def pndvi(self): + """ + Pan NDVI + https://www.indexdatabase.de/db/i-single.php?id=188 + :return: index + """ return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def atsavi(self, x=0.08, a=1.22, b=0.03): + """ + Adjusted transformed soil-adjusted VI + https://www.indexdatabase.de/db/i-single.php?id=209 + :return: index + """ return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def bwdrvi(self): + """ + self.blue-wide dynamic range vegetation index + https://www.indexdatabase.de/db/i-single.php?id=136 + :return: index + """ return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def ci_green(self): + """ + Chlorophyll Index self.green + https://www.indexdatabase.de/db/i-single.php?id=128 + :return: index + """ return (self.nir / self.green) - 1 def ci_rededge(self): + """ + Chlorophyll Index self.redEdge + https://www.indexdatabase.de/db/i-single.php?id=131 + :return: index + """ return (self.nir / self.redEdge) - 1 def ci(self): + """ + Coloration Index + https://www.indexdatabase.de/db/i-single.php?id=11 + :return: index + """ return (self.red - self.blue) / self.red def ctvi(self): + """ + Corrected Transformed Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=244 + :return: index + """ ndvi = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def gdvi(self): + """ + Difference self.nir/self.green self.green Difference Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=27 + :return: index + """ return self.nir - self.green def evi(self): + """ + Enhanced Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=16 + :return: index + """ return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def gemi(self): + """ + Global Environment Monitoring Index + https://www.indexdatabase.de/db/i-single.php?id=25 + :return: index + """ n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def gosavi(self, y=0.16): + """ + self.green Optimized Soil Adjusted Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=29 + mit Y = 0,16 + :return: index + """ return (self.nir - self.green) / (self.nir + self.green + y) def gsavi(self, n=0.5): + """ + self.green Soil Adjusted Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=31 + mit N = 0,5 + :return: index + """ return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def hue(self): + """ + Hue + https://www.indexdatabase.de/db/i-single.php?id=34 + :return: index + """ return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def ivi(self, a=None, b=None): + """ + Ideal vegetation index + https://www.indexdatabase.de/db/i-single.php?id=276 + b=intercept of vegetation line + a=soil line slope + :return: index + """ return (self.nir - b) / (a * self.red) def ipvi(self): + """ + Infraself.red percentage vegetation index + https://www.indexdatabase.de/db/i-single.php?id=35 + :return: index + """ return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def i(self): + """ + Intensity + https://www.indexdatabase.de/db/i-single.php?id=36 + :return: index + """ return (self.red + self.green + self.blue) / 30.5 def rvi(self): + """ + Ratio-Vegetation-Index + http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html + :return: index + """ return self.nir / self.red def mrvi(self): + """ + Modified Normalized Difference Vegetation Index RVI + https://www.indexdatabase.de/db/i-single.php?id=275 + :return: index + """ return (self.rvi() - 1) / (self.rvi() + 1) def m_savi(self): + """ + Modified Soil Adjusted Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=44 + :return: index + """ return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def norm_g(self): + """ + Norm G + https://www.indexdatabase.de/db/i-single.php?id=50 + :return: index + """ return self.green / (self.nir + self.red + self.green) def norm_nir(self): + """ + Norm self.nir + https://www.indexdatabase.de/db/i-single.php?id=51 + :return: index + """ return self.nir / (self.nir + self.red + self.green) def norm_r(self): + """ + Norm R + https://www.indexdatabase.de/db/i-single.php?id=52 + :return: index + """ return self.red / (self.nir + self.red + self.green) def ngrdi(self): + """ + Normalized Difference self.green/self.red Normalized self.green self.red + difference index, Visible Atmospherically Resistant Indices self.green + (VIself.green) + https://www.indexdatabase.de/db/i-single.php?id=390 + :return: index + """ return (self.green - self.red) / (self.green + self.red) def ri(self): + """ + Normalized Difference self.red/self.green self.redness Index + https://www.indexdatabase.de/db/i-single.php?id=74 + :return: index + """ return (self.red - self.green) / (self.red + self.green) def s(self): + """ + Saturation + https://www.indexdatabase.de/db/i-single.php?id=77 + :return: index + """ max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (max_value - min_value) / max_value def _if(self): + """ + Shape Index + https://www.indexdatabase.de/db/i-single.php?id=79 + :return: index + """ return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def dvi(self): + """ + Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index + Number (VIN) + https://www.indexdatabase.de/db/i-single.php?id=12 + :return: index + """ return self.nir / self.red def tvi(self): + """ + Transformed Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=98 + :return: index + """ return (self.ndvi() + 0.5) ** (1 / 2) def ndre(self): @@ -269,4 +572,4 @@ # float32 -> 0.31578946 #NDVI (red = 50, nir = 100) # float64 -> 0.3157894736842105 #NDVI (red = 50, nir = 100) # longdouble -> 0.3157894736842105 #NDVI (red = 50, nir = 100) -"""+"""
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 erosion(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output if __name__ == "__main__": # read original image lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) # Apply erosion operation to a binary image output = erosion(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
--- +++ @@ -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: - return (gray > 127) & (gray <= 255) - - -def erosion(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: - output = np.zeros_like(image) - image_padded = np.zeros( - (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) - ) - - # Copy image to padded image - image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image - - # Iterate over image & apply kernel - for x in range(image.shape[1]): - for y in range(image.shape[0]): - summation = ( - kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] - ).sum() - output[y, x] = int(summation == 5) - return output - - -if __name__ == "__main__": - # read original image - lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" - lena = np.array(Image.open(lena_path)) - - # kernel to be applied - structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) - - # Apply erosion operation to a binary image - output = erosion(gray_to_binary(rgb_to_gray(lena)), structuring_element) - - # Save the output image - pil_img = Image.fromarray(output).convert("RGB") - pil_img.save("result_erosion.png")+from pathlib import Path + +import numpy as np +from PIL import Image + + +def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: + """ + Return gray image from rgb image + + >>> rgb_to_gray(np.array([[[127, 255, 0]]])) + array([[187.6453]]) + >>> rgb_to_gray(np.array([[[0, 0, 0]]])) + array([[0.]]) + >>> rgb_to_gray(np.array([[[2, 4, 1]]])) + array([[3.0598]]) + >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) + array([[159.0524, 90.0635, 117.6989]]) + """ + 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 binary image from gray image + + >>> gray_to_binary(np.array([[127, 255, 0]])) + array([[False, True, False]]) + >>> gray_to_binary(np.array([[0]])) + array([[False]]) + >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]])) + array([[False, False, False]]) + >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) + array([[False, True, False], + [False, True, False], + [False, True, False]]) + """ + return (gray > 127) & (gray <= 255) + + +def erosion(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: + """ + Return eroded image + + >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) + array([[False, False, False]]) + >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) + array([[False, False, False]]) + """ + output = np.zeros_like(image) + image_padded = np.zeros( + (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) + ) + + # Copy image to padded image + image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image + + # Iterate over image & apply kernel + for x in range(image.shape[1]): + for y in range(image.shape[0]): + summation = ( + kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] + ).sum() + output[y, x] = int(summation == 5) + return output + + +if __name__ == "__main__": + # read original image + lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" + lena = np.array(Image.open(lena_path)) + + # kernel to be applied + structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) + + # Apply erosion operation to a binary image + output = erosion(gray_to_binary(rgb_to_gray(lena)), structuring_element) + + # Save the output image + pil_img = Image.fromarray(output).convert("RGB") + pil_img.save("result_erosion.png")
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] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(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 size + :return: image with median filter + """ # set image borders bd = int(mask / 2) # copy image size @@ -31,4 +39,4 @@ # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) - waitKey(0)+ waitKey(0)
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 - center] g = ( 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma))) ) return g def suppress_non_maximum(image_shape, gradient_direction, sobel_grad): destination = np.zeros(image_shape) for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): direction = gradient_direction[row, col] if ( 0 <= direction < PI / 8 or 15 * PI / 8 <= direction <= 2 * PI or 7 * PI / 8 <= direction <= 9 * PI / 8 ): w = sobel_grad[row, col - 1] e = sobel_grad[row, col + 1] if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e: destination[row, col] = sobel_grad[row, col] elif ( PI / 8 <= direction < 3 * PI / 8 or 9 * PI / 8 <= direction < 11 * PI / 8 ): sw = sobel_grad[row + 1, col - 1] ne = sobel_grad[row - 1, col + 1] if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne: destination[row, col] = sobel_grad[row, col] elif ( 3 * PI / 8 <= direction < 5 * PI / 8 or 11 * PI / 8 <= direction < 13 * PI / 8 ): n = sobel_grad[row - 1, col] s = sobel_grad[row + 1, col] if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s: destination[row, col] = sobel_grad[row, col] elif ( 5 * PI / 8 <= direction < 7 * PI / 8 or 13 * PI / 8 <= direction < 15 * PI / 8 ): nw = sobel_grad[row - 1, col - 1] se = sobel_grad[row + 1, col + 1] if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se: destination[row, col] = sobel_grad[row, col] return destination def detect_high_low_threshold( image_shape, destination, threshold_low, threshold_high, weak, strong ): for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): if destination[row, col] >= threshold_high: destination[row, col] = strong elif destination[row, col] <= threshold_low: destination[row, col] = 0 else: destination[row, col] = weak def track_edge(image_shape, destination, weak, strong): for row in range(1, image_shape[0]): for col in range(1, image_shape[1]): if destination[row, col] == weak: if 255 in ( destination[row, col + 1], destination[row, col - 1], destination[row - 1, col], destination[row + 1, col], destination[row - 1, col - 1], destination[row + 1, col - 1], destination[row - 1, col + 1], destination[row + 1, col + 1], ): destination[row, col] = strong else: destination[row, col] = 0 def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255): # gaussian_filter gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4)) # get the gradient and degree by sobel_filter sobel_grad, sobel_theta = sobel_filter(gaussian_out) gradient_direction = PI + np.rad2deg(sobel_theta) destination = suppress_non_maximum(image.shape, gradient_direction, sobel_grad) detect_high_low_threshold( image.shape, destination, threshold_low, threshold_high, weak, strong ) track_edge(image.shape, destination, weak, strong) return destination if __name__ == "__main__": # read original image in gray mode lena = cv2.imread(r"../image_data/lena.jpg", 0) # canny edge detection canny_destination = canny(lena) cv2.imshow("canny", canny_destination) cv2.waitKey(0)
--- +++ @@ -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 value will be suppressed. + """ destination = np.zeros(image_shape) for row in range(1, image_shape[0] - 1): @@ -68,6 +73,14 @@ def detect_high_low_threshold( image_shape, destination, threshold_low, threshold_high, weak, strong ): + """ + High-Low threshold detection. If an edge pixel's gradient value is higher + than the high threshold value, it is marked as a strong edge pixel. If an + edge pixel's gradient value is smaller than the high threshold value and + larger than the low threshold value, it is marked as a weak edge pixel. If + an edge pixel's value is smaller than the low threshold value, it will be + suppressed. + """ for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): if destination[row, col] >= threshold_high: @@ -79,6 +92,12 @@ def track_edge(image_shape, destination, weak, strong): + """ + Edge tracking. Usually a weak edge pixel caused from true edges will be connected + to a strong edge pixel while noise responses are unconnected. As long as there is + one strong edge pixel that is involved in its 8-connected neighborhood, that weak + edge point can be identified as one that should be preserved. + """ for row in range(1, image_shape[0]): for col in range(1, image_shape[1]): if destination[row, col] == weak: @@ -121,4 +140,4 @@ # canny edge detection canny_destination = canny(lena) cv2.imshow("canny", canny_destination) - cv2.waitKey(0)+ cv2.waitKey(0)
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] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 and b="ABC" +daBcd -> capitalize a and c(dABCd) -> remove d (ABC) +""" def abbr(a: str, b: str) -> bool: + """ + >>> abbr("daBcd", "ABC") + True + >>> abbr("dBcd", "ABC") + False + """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] @@ -18,4 +36,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
--- +++ @@ -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: list) -> list: + """ + Pure python implementation of the iterative Heap's algorithm, + returning all permutations of a list. + >>> heaps([]) + [()] + >>> heaps([0]) + [(0,)] + >>> heaps([-1, 1]) + [(-1, 1), (1, -1)] + >>> heaps([1, 2, 3]) + [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] + >>> from itertools import permutations + >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) + True + >>> all(sorted(heaps(x)) == sorted(permutations(x)) + ... for x in ([], [0], [-1, 1], [1, 2, 3])) + True + """ if len(arr) <= 1: return [tuple(arr)] @@ -32,4 +57,4 @@ if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] - print(heaps(arr))+ print(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): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) min_dis = min(min_dis, current_dis) return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) min_dis = min(min_dis, current_dis) return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
--- +++ @@ -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. + +>> Closest points can lie on different sides of partition. +This case handled by forming a strip of points +whose Xco-ords distance is less than closest_pair_dis +from mid-point's Xco-ords. Points sorted based on Yco-ords +are used in this step to reduce sorting time. +Closest pair distance is found in the strip of points. (closest_in_strip) + +min(closest_pair_dis, closest_in_strip) would be the final answer. + +Time complexity: O(n * log n) +""" def euclidean_distance_sqr(point1, point2): + """ + >>> euclidean_distance_sqr([1,2],[2,4]) + 5 + """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): + """ + >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) + [(3, 0), (5, 1), (4, 2)] + """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): + """ + brute force approach to find distance between closest pair points + + Parameters : + points, points_count, min_dis (list(tuple(int, int)), int, int) + + Returns : + min_dis (float): distance between closest pair of points + + >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) + 5 + + """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): @@ -18,6 +59,18 @@ def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): + """ + closest pair of points in strip + + Parameters : + points, points_count, min_dis (list(tuple(int, int)), int, int) + + Returns : + min_dis (float): distance btw closest pair of points in the strip (< min_dis) + + >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) + 85 + """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): @@ -27,6 +80,17 @@ def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): + """divide and conquer approach + + Parameters : + points, points_count (list(tuple(int, int)), int) + + Returns : + (float): distance btw closest pair of points + + >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) + 8 + """ # base case if points_counts <= 3: @@ -59,6 +123,10 @@ def closest_pair_of_points(points, points_counts): + """ + >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) + 28.792360097775937 + """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( @@ -70,4 +138,4 @@ if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] - print("Distance:", closest_pair_of_points(points, len(points)))+ print("Distance:", closest_pair_of_points(points, len(points)))
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 = len(arr) // 2 p = arr[0:mid] q = arr[mid:] a, inversion_p = count_inversions_recursive(p) b, inversions_q = count_inversions_recursive(q) c, cross_inversions = _count_cross_inversions(a, b) num_inversions = inversion_p + inversions_q + cross_inversions return c, num_inversions def _count_cross_inversions(p, q): r = [] i = j = num_inversion = 0 while i < len(p) and j < len(q): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(p) - i r.append(q[j]) j += 1 else: r.append(p[i]) i += 1 if i < len(p): r.extend(p[i:]) else: r.extend(q[j:]) return r, num_inversion def main(): arr_1 = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 8 print("number of inversions = ", num_inversions_bf) # testing an array with zero inversion (a sorted arr_1) arr_1.sort() num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) # an empty list should also have zero inversions arr_1 = [] num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) if __name__ == "__main__": main()
--- +++ @@ -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 determine how close a given array is to being sorted. +In this implementation, I provide two algorithms, a divide-and-conquer +algorithm which runs in nlogn and the brute-force n^2 algorithm. +""" def count_inversions_bf(arr): + """ + Counts the number of inversions using a naive brute-force algorithm + Parameters + ---------- + arr: arr: array-like, the list containing the items for which the number + of inversions is desired. The elements of `arr` must be comparable. + Returns + ------- + num_inversions: The total number of inversions in `arr` + Examples + --------- + >>> count_inversions_bf([1, 4, 2, 4, 1]) + 4 + >>> count_inversions_bf([1, 1, 2, 4, 4]) + 0 + >>> count_inversions_bf([]) + 0 + """ num_inversions = 0 n = len(arr) @@ -14,6 +41,25 @@ def count_inversions_recursive(arr): + """ + Counts the number of inversions using a divide-and-conquer algorithm + Parameters + ----------- + arr: array-like, the list containing the items for which the number + of inversions is desired. The elements of `arr` must be comparable. + Returns + ------- + C: a sorted copy of `arr`. + num_inversions: int, the total number of inversions in 'arr' + Examples + -------- + >>> count_inversions_recursive([1, 4, 2, 4, 1]) + ([1, 1, 2, 4, 4], 4) + >>> count_inversions_recursive([1, 1, 2, 4, 4]) + ([1, 1, 2, 4, 4], 0) + >>> count_inversions_recursive([]) + ([], 0) + """ if len(arr) <= 1: return arr, 0 mid = len(arr) // 2 @@ -29,6 +75,26 @@ def _count_cross_inversions(p, q): + """ + Counts the inversions across two sorted arrays. + And combine the two arrays into one sorted array + For all 1<= i<=len(P) and for all 1 <= j <= len(Q), + if P[i] > Q[j], then (i, j) is a cross inversion + Parameters + ---------- + P: array-like, sorted in non-decreasing order + Q: array-like, sorted in non-decreasing order + Returns + ------ + R: array-like, a sorted array of the elements of `P` and `Q` + num_inversion: int, the number of inversions across `P` and `Q` + Examples + -------- + >>> _count_cross_inversions([1, 2, 3], [0, 2, 5]) + ([0, 1, 2, 2, 3, 5], 4) + >>> _count_cross_inversions([1, 2, 3], [3, 4, 5]) + ([1, 2, 3, 3, 4, 5], 0) + """ r = [] i = j = num_inversion = 0 @@ -84,4 +150,4 @@ if __name__ == "__main__": - main()+ main()
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.src_w = img.shape[1] self.src_h = img.shape[0] self.dst_w = dst_width self.dst_h = dst_height self.ratio_x = self.src_w / self.dst_w self.ratio_y = self.src_h / self.dst_h self.output = self.output_img = ( np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 ) def process(self): for i in range(self.dst_h): for j in range(self.dst_w): self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] def get_x(self, x: int) -> int: return int(self.ratio_x * x) def get_y(self, y: int) -> int: return int(self.ratio_y * y) if __name__ == "__main__": dst_w, dst_h = 800, 600 im = imread("image_data/lena.jpg", 1) n = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
--- +++ @@ -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 + """ def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: @@ -28,9 +33,29 @@ self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] def get_x(self, x: int) -> int: + """ + Get parent X coordinate for destination X + :param x: Destination X coordinate + :return: Parent X coordinate based on `x ratio` + >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", + ... 1), 100, 100) + >>> nn.ratio_x = 0.5 + >>> nn.get_x(4) + 2 + """ return int(self.ratio_x * x) def get_y(self, y: int) -> int: + """ + Get parent Y coordinate for destination Y + :param y: Destination X coordinate + :return: Parent X coordinate based on `y ratio` + >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", + ... 1), 100, 100) + >>> nn.ratio_y = 0.5 + >>> nn.get_y(4) + 2 + """ return int(self.ratio_y * y) @@ -44,4 +69,4 @@ f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) - destroyAllWindows()+ destroyAllWindows()
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 __gt__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y > other.y return False def __lt__(self, other): return not self > other def __ge__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y >= other.y return False def __le__(self, other): if self.x < other.x: return True elif self.x == other.x: return self.y <= other.y return False def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: points: list[Point] = [] if list_of_tuples: for p in list_of_tuples: if isinstance(p, Point): points.append(p) else: try: points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." ) return points def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: if not hasattr(points, "__iter__"): msg = f"Expecting an iterable object but got an non-iterable type {points}" raise ValueError(msg) if not points: msg = f"Expecting a list of points but got {points}" raise ValueError(msg) return _construct_points(points) def _det(a: Point, b: Point, c: Point) -> float: det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: points = sorted(_validate_input(points)) n = len(points) convex_set = set() for i in range(n - 1): for j in range(i + 1, n): points_left_of_ij = points_right_of_ij = False ij_part_of_convex_hull = True for k in range(n): if k not in {i, j}: det_k = _det(points[i], points[j], points[k]) if det_k > 0: points_left_of_ij = True elif det_k < 0: points_right_of_ij = True # point[i], point[j], point[k] all lie on a straight line # if point[k] is to the left of point[i] or it's to the # right of point[j], then point[i], point[j] cannot be # part of the convex hull of A elif points[k] < points[i] or points[k] > points[j]: ij_part_of_convex_hull = False break if points_left_of_ij and points_right_of_ij: ij_part_of_convex_hull = False break if ij_part_of_convex_hull: convex_set.update([points[i], points[j]]) return sorted(convex_set) def convex_hull_recursive(points: list[Point]) -> list[Point]: points = sorted(_validate_input(points)) n = len(points) # divide all the points into an upper hull and a lower hull # the left most point and the right most point are definitely # members of the convex hull by definition. # use these two anchors to divide all the points into two hulls, # an upper hull and a lower hull. # all points to the left (above) the line joining the extreme points belong to the # upper hull # all points to the right (below) the line joining the extreme points below to the # lower hull # ignore all points on the line joining the extreme points since they cannot be # part of the convex hull left_most_point = points[0] right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} upper_hull = [] lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: upper_hull.append(points[i]) elif det < 0: lower_hull.append(points[i]) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: if points: extreme_point = None extreme_point_distance = float("-inf") candidate_points = [] for p in points: det = _det(left, right, p) if det > 0: candidate_points.append(p) if det > extreme_point_distance: extreme_point_distance = det extreme_point = p if extreme_point: _construct_hull(candidate_points, left, extreme_point, convex_set) convex_set.add(extreme_point) _construct_hull(candidate_points, extreme_point, right, convex_set) def convex_hull_melkman(points: list[Point]) -> list[Point]: points = sorted(_validate_input(points)) n = len(points) convex_hull = points[:2] for i in range(2, n): det = _det(convex_hull[1], convex_hull[0], points[i]) if det > 0: convex_hull.insert(0, points[i]) break elif det < 0: convex_hull.append(points[i]) break else: convex_hull[1] = points[i] i += 1 for j in range(i, n): if ( _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): # The point lies within the convex hull continue convex_hull.insert(0, points[j]) convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: del convex_hull[-2] # `convex_hull` is contains the convex hull in circular order return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) def main(): points = [ (0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3), ] # the convex set of points is # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)] results_bf = convex_hull_bf(points) results_recursive = convex_hull_recursive(points) assert results_bf == results_recursive results_melkman = convex_hull_melkman(points) assert results_bf == results_melkman print(results_bf) if __name__ == "__main__": main()
--- +++ @@ -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 development. + +Two algorithms have been implemented for the convex hull problem here. +1. A brute-force algorithm which runs in O(n^3) +2. A divide-and-conquer algorithm which runs in O(n log(n)) + +There are other several other algorithms for the convex hull problem +which have not been implemented here, yet. + +""" from __future__ import annotations @@ -5,6 +19,31 @@ class Point: + """ + Defines a 2-d point for use by all convex-hull algorithms. + + Parameters + ---------- + x: an int or a float, the x-coordinate of the 2-d point + y: an int or a float, the y-coordinate of the 2-d point + + Examples + -------- + >>> Point(1, 2) + (1.0, 2.0) + >>> Point("1", "2") + (1.0, 2.0) + >>> Point(1, 2) > Point(0, 1) + True + >>> Point(1, 1) == Point(1, 1) + True + >>> Point(-0.5, 1) == Point(0.5, 1) + False + >>> Point("pi", "e") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'pi' + """ def __init__(self, x, y): self.x, self.y = float(x), float(y) @@ -49,6 +88,33 @@ def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: + """ + constructs a list of points from an array-like object of numbers + + Arguments + --------- + + list_of_tuples: array-like object of type numbers. Acceptable types so far + are lists, tuples and sets. + + Returns + -------- + points: a list where each item is of type Point. This contains only objects + which can be converted into a Point. + + Examples + ------- + >>> _construct_points([[1, 1], [2, -1], [0.3, 4]]) + [(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)] + >>> _construct_points([1, 2]) + Ignoring deformed point 1. All points must have at least 2 coordinates. + Ignoring deformed point 2. All points must have at least 2 coordinates. + [] + >>> _construct_points([]) + [] + >>> _construct_points(None) + [] + """ points: list[Point] = [] if list_of_tuples: @@ -67,6 +133,46 @@ def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: + """ + validates an input instance before a convex-hull algorithms uses it + + Parameters + --------- + points: array-like, the 2d points to validate before using with + a convex-hull algorithm. The elements of points must be either lists, tuples or + Points. + + Returns + ------- + points: array_like, an iterable of all well-defined Points constructed passed in. + + + Exception + --------- + ValueError: if points is empty or None, or if a wrong data structure like a scalar + is passed + + TypeError: if an iterable but non-indexable object (eg. dictionary) is passed. + The exception to this a set which we'll convert to a list before using + + + Examples + ------- + >>> _validate_input([[1, 2]]) + [(1.0, 2.0)] + >>> _validate_input([(1, 2)]) + [(1.0, 2.0)] + >>> _validate_input([Point(2, 1), Point(-1, 2)]) + [(2.0, 1.0), (-1.0, 2.0)] + >>> _validate_input([]) + Traceback (most recent call last): + ... + ValueError: Expecting a list of points but got [] + >>> _validate_input(1) + Traceback (most recent call last): + ... + ValueError: Expecting an iterable object but got an non-iterable type 1 + """ if not hasattr(points, "__iter__"): msg = f"Expecting an iterable object but got an non-iterable type {points}" @@ -80,12 +186,77 @@ def _det(a: Point, b: Point, c: Point) -> float: + """ + Computes the sign perpendicular distance of a 2d point c from a line segment + ab. The sign indicates the direction of c relative to ab. + A Positive value means c is above ab (to the left), while a negative value + means c is below ab (to the right). 0 means all three points are on a straight line. + + As a side note, 0.5 * abs|det| is the area of triangle abc + + Parameters + ---------- + a: point, the point on the left end of line segment ab + b: point, the point on the right end of line segment ab + c: point, the point for which the direction and location is desired. + + Returns + -------- + det: float, abs(det) is the distance of c from ab. The sign + indicates which side of line segment ab c is. det is computed as + (a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x) + + Examples + ---------- + >>> _det(Point(1, 1), Point(1, 2), Point(1, 5)) + 0.0 + >>> _det(Point(0, 0), Point(10, 0), Point(0, 10)) + 100.0 + >>> _det(Point(0, 0), Point(10, 0), Point(0, -10)) + -100.0 + """ det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: + """ + Constructs the convex hull of a set of 2D points using a brute force algorithm. + The algorithm basically considers all combinations of points (i, j) and uses the + definition of convexity to determine whether (i, j) is part of the convex hull or + not. (i, j) is part of the convex hull if and only iff there are no points on both + sides of the line segment connecting the ij, and there is no point k such that k is + on either end of the ij. + + Runtime: O(n^3) - definitely horrible + + Parameters + --------- + points: array-like of object of Points, lists or tuples. + The set of 2d points for which the convex-hull is needed + + Returns + ------ + convex_set: list, the convex-hull of points sorted in non-decreasing order. + + See Also + -------- + convex_hull_recursive, + + Examples + --------- + >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]]) + [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] + >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]]) + [(0.0, 0.0), (10.0, 0.0)] + >>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], + ... [-0.75, 1]]) + [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] + >>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), + ... (2, -1), (2, -4), (1, -3)]) + [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] + """ points = sorted(_validate_input(points)) n = len(points) @@ -122,6 +293,38 @@ def convex_hull_recursive(points: list[Point]) -> list[Point]: + """ + Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy + The algorithm exploits the geometric properties of the problem by repeatedly + partitioning the set of points into smaller hulls, and finding the convex hull of + these smaller hulls. The union of the convex hull from smaller hulls is the + solution to the convex hull of the larger problem. + + Parameter + --------- + points: array-like of object of Points, lists or tuples. + The set of 2d points for which the convex-hull is needed + + Runtime: O(n log n) + + Returns + ------- + convex_set: list, the convex-hull of points sorted in non-decreasing order. + + Examples + --------- + >>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]]) + [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] + >>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]]) + [(0.0, 0.0), (10.0, 0.0)] + >>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], + ... [-0.75, 1]]) + [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] + >>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), + ... (2, -1), (2, -4), (1, -3)]) + [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] + + """ points = sorted(_validate_input(points)) n = len(points) @@ -162,6 +365,26 @@ def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: + """ + + Parameters + --------- + points: list or None, the hull of points from which to choose the next convex-hull + point + left: Point, the point to the left of line segment joining left and right + right: The point to the right of the line segment joining left and right + convex_set: set, the current convex-hull. The state of convex-set gets updated by + this function + + Note + ---- + For the line segment 'ab', 'a' is on the left and 'b' on the right. + but the reverse is true for the line segment 'ba'. + + Returns + ------- + Nothing, only updates the state of convex-set + """ if points: extreme_point = None extreme_point_distance = float("-inf") @@ -184,6 +407,41 @@ def convex_hull_melkman(points: list[Point]) -> list[Point]: + """ + Constructs the convex hull of a set of 2D points using the melkman algorithm. + The algorithm works by iteratively inserting points of a simple polygonal chain + (meaning that no line segments between two consecutive points cross each other). + Sorting the points yields such a polygonal chain. + + For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html + + Runtime: O(n log n) - O(n) if points are already sorted in the input + + Parameters + --------- + points: array-like of object of Points, lists or tuples. + The set of 2d points for which the convex-hull is needed + + Returns + ------ + convex_set: list, the convex-hull of points sorted in non-decreasing order. + + See Also + -------- + + Examples + --------- + >>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]]) + [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] + >>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]]) + [(0.0, 0.0), (10.0, 0.0)] + >>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], + ... [-0.75, 1]]) + [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] + >>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), + ... (2, -1), (2, -4), (1, -3)]) + [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] + """ points = sorted(_validate_input(points)) n = len(points) @@ -246,4 +504,4 @@ if __name__ == "__main__": - main()+ main()
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 - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: n = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: n = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
--- +++ @@ -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 together are used for this algorithm. +* https://en.wikipedia.org/wiki/Partition_(number_theory) +* https://en.wikipedia.org/wiki/Partition_function_(number_theory) +""" def partition(m: int) -> int: + """ + >>> partition(5) + 7 + >>> partition(7) + 15 + >>> partition(100) + 190569292 + >>> partition(1_000) + 24061467864032622473692149727991 + >>> partition(-7) + Traceback (most recent call last): + ... + IndexError: list index out of range + >>> partition(0) + Traceback (most recent call last): + ... + IndexError: list assignment index out of range + >>> partition(7.8) + Traceback (most recent call last): + ... + TypeError: 'float' object cannot be interpreted as an integer + """ memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 @@ -28,4 +58,4 @@ n = int(sys.argv[1]) print(partition(n)) except ValueError: - print("Please pass a number.")+ print("Please pass a number.")
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) if __name__ == "__main__": print(power(-2, -3)) # output -0.125
--- +++ @@ -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: The result of a^b. + + Examples: + >>> actual_power(3, 2) + 9 + >>> actual_power(5, 3) + 125 + >>> actual_power(2, 5) + 32 + >>> actual_power(7, 0) + 1 + """ if b == 0: return 1 half = actual_power(a, b // 2) @@ -10,10 +28,26 @@ def power(a: int, b: int) -> float: + """ + :param a: The base (integer). + :param b: The exponent (integer). + :return: The result of a^b, as a float for negative exponents. + + >>> power(4,6) + 4096 + >>> power(2,3) + 8 + >>> power(-2,3) + -8 + >>> power(2,-3) + 0.125 + >>> power(-2,-3) + -0.125 + """ if b < 0: return 1 / actual_power(a, -b) return actual_power(a, b) if __name__ == "__main__": - print(power(-2, -3)) # output -0.125+ print(power(-2, -3)) # output -0.125
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 right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. Algorithm Design. +Addison Wesley 2006: Chapter 5 Solved Exercise 1) +""" from __future__ import annotations def peak(lst: list[int]) -> int: + """ + Return the peak value of `lst`. + >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) + 5 + >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) + 10 + >>> peak([1, 9, 8, 7]) + 9 + >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) + 7 + >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) + 4 + """ # middle index m = len(lst) // 2 @@ -29,4 +51,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 for the sorted array Half while pointer1 < len(left_half) and pointer2 < len(right_half): if left_half[pointer1] < right_half[pointer2]: sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 else: sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 while pointer1 < len(left_half): sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 while pointer2 < len(right_half): sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 return sorted_array def merge_sort(array: list) -> list: if len(array) <= 1: return array # the actual formula to calculate the middle element = left + (right - left) // 2 # this avoids integer overflow in case of large N middle = 0 + (len(array) - 0) // 2 # Split the array into halves till the array length becomes equal to One # merge the arrays of single length returned by mergeSort function and # pass them into the merge arrays function which merges the array left_half = array[:middle] right_half = array[middle:] return merge(merge_sort(left_half), merge_sort(right_half)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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, right_half) + [1, 2, 3, 4, 5, 6] + + >>> left_half = [-2] + >>> right_half = [-1] + >>> merge(left_half, right_half) + [-2, -1] + + >>> left_half = [12, 15] + >>> right_half = [13, 14] + >>> merge(left_half, right_half) + [12, 13, 14, 15] + + >>> left_half = [] + >>> right_half = [] + >>> merge(left_half, right_half) + [] + """ sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 # pointer to current index for left Half @@ -31,6 +58,39 @@ def merge_sort(array: list) -> list: + """Returns a list of sorted array elements using merge sort. + + >>> from random import shuffle + >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] + >>> shuffle(array) + >>> merge_sort(array) + [-200, -10, -2, 3, 11, 99, 100, 100000] + + >>> shuffle(array) + >>> merge_sort(array) + [-200, -10, -2, 3, 11, 99, 100, 100000] + + >>> array = [-200] + >>> merge_sort(array) + [-200] + + >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] + >>> shuffle(array) + >>> sorted(array) == merge_sort(array) + True + + >>> array = [-2] + >>> merge_sort(array) + [-2] + + >>> array = [] + >>> merge_sort(array) + [] + + >>> array = [10000000, 1, -1111111111, 101111111112, 9000002] + >>> sorted(array) == merge_sort(array) + True + """ if len(array) <= 1: return array # the actual formula to calculate the middle element = left + (right - left) // 2 @@ -49,4 +109,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
--- +++ @@ -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) + """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): + """ + Helper function to create pixel's greyscale representation + Src: https://pl.wikipedia.org/wiki/YUV + """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): + """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): @@ -36,4 +48,4 @@ imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) - destroyAllWindows()+ destroyAllWindows()
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) matrix = [[0 for _ in range(n)] for _ in range(n)] sol = [[0 for _ in range(n)] for _ in range(n)] for chain_length in range(2, n): for a in range(1, n - chain_length + 1): b = a + chain_length - 1 matrix[a][b] = sys.maxsize for c in range(a, b): cost = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: matrix[a][b] = cost sol[a][b] = c return matrix, sol def print_optimal_solution(optimal_solution: list[list[int]], i: int, j: int): if i == j: print("A" + str(i), end=" ") else: print("(", end=" ") print_optimal_solution(optimal_solution, i, optimal_solution[i][j]) print_optimal_solution(optimal_solution, optimal_solution[i][j] + 1, j) print(")", end=" ") def main(): array = [30, 35, 15, 5, 10, 20, 25] n = len(array) matrix, optimal_solution = matrix_chain_order(array) print("No. of Operation required: " + str(matrix[1][n - 1])) print_optimal_solution(optimal_solution, 1, n - 1) if __name__ == "__main__": main()
--- +++ @@ -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 range(n)] sol = [[0 for _ in range(n)] for _ in range(n)] @@ -31,6 +35,9 @@ def print_optimal_solution(optimal_solution: list[list[int]], i: int, j: int): + """ + Print order of matrix with Ai as Matrix. + """ if i == j: print("A" + str(i), end=" ") @@ -42,6 +49,10 @@ def main(): + """ + Size of matrix created from array [30, 35, 15, 5, 10, 20, 25] will be: + 30*35 35*15 15*5 5*10 10*20 20*25 + """ array = [30, 35, 15, 5, 10, 20, 25] n = len(array) @@ -53,4 +64,4 @@ if __name__ == "__main__": - main()+ main()
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 or equal to the value of the # picked coin for coin_val in s: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 +""" def dp_count(s, n): + """ + >>> dp_count([1, 2, 3], 4) + 4 + >>> dp_count([1, 2, 3], 7) + 8 + >>> dp_count([2, 5, 3, 6], 10) + 5 + >>> dp_count([10], 99) + 0 + >>> dp_count([4, 5, 6], 0) + 1 + >>> dp_count([1, 2, 3], -5) + 0 + """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i @@ -22,4 +43,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 arr[i], arr[k - 1] = arr[k - 1], arr[i] else: # k is odd arr[0], arr[k - 1] = arr[k - 1], arr[0] generate(k - 1, arr) generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
--- +++ @@ -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) -> list: + """ + Pure python implementation of the Heap's algorithm (recursive version), + returning all permutations of a list. + >>> heaps([]) + [()] + >>> heaps([0]) + [(0,)] + >>> heaps([-1, 1]) + [(-1, 1), (1, -1)] + >>> heaps([1, 2, 3]) + [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] + >>> from itertools import permutations + >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) + True + >>> all(sorted(heaps(x)) == sorted(permutations(x)) + ... for x in ([], [0], [-1, 1], [1, 2, 3])) + True + """ if len(arr) <= 1: return [tuple(arr)] @@ -28,4 +53,4 @@ if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] - print(heaps(arr))+ print(heaps(arr))
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([]) # seed value table[0] = [[]] # because empty string has empty combination # iterate through the indices for i in range(table_size): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(word)] == word: new_combinations: list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(word)] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(target)]: combination.reverse() return table[len(target)] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "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 possible + combinations a string(`target`) can be constructed from + the given list of substrings(`word_bank`) + + >>> all_construct("hello", ["he", "l", "o"]) + [['he', 'l', 'l', 'o']] + >>> all_construct("purple",["purp","p","ur","le","purpl"]) + [['purp', 'le'], ['p', 'ur', 'p', 'le']] + """ word_bank = word_bank or [] # create a table @@ -43,4 +57,4 @@ "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) - )+ )
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_possible_combinations(target) def combination_sum_iv_dp_array(array: list[int], target: int) -> int: def count_of_possible_combinations_with_dp_array( target: int, dp_array: list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] answer = sum( count_of_possible_combinations_with_dp_array(target - item, dp_array) for item in array ) dp_array[target] = answer return answer dp_array = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(target, dp_array) def combination_sum_iv_bottom_up(n: int, array: list[int], target: int) -> int: dp_array = [0] * (target + 1) dp_array[0] = 1 for i in range(1, target + 1): for j in range(n): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() target = 5 array = [1, 2, 5] print(combination_sum_iv(array, target))
--- +++ @@ -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 + * array = [1, 2, 5] + +Output: + 9 + +Approach: + The basic idea is to go over recursively to find the way such that the sum + of chosen elements is `target`. For every element, we have two choices + + 1. Include the element in our set of chosen elements. + 2. Don't include the element in our set of chosen elements. +""" def combination_sum_iv(array: list[int], target: int) -> int: + """ + Function checks the all possible combinations, and returns the count + of possible combination in exponential Time Complexity. + + >>> combination_sum_iv([1,2,5], 5) + 9 + """ def count_of_possible_combinations(target: int) -> int: if target < 0: @@ -13,6 +43,14 @@ def combination_sum_iv_dp_array(array: list[int], target: int) -> int: + """ + Function checks the all possible combinations, and returns the count + of possible combination in O(N^2) Time Complexity as we are using Dynamic + programming array here. + + >>> combination_sum_iv_dp_array([1,2,5], 5) + 9 + """ def count_of_possible_combinations_with_dp_array( target: int, dp_array: list[int] @@ -35,6 +73,14 @@ def combination_sum_iv_bottom_up(n: int, array: list[int], target: int) -> int: + """ + Function checks the all possible combinations with using bottom up approach, + and returns the count of possible combination in O(N^2) Time Complexity + as we are using Dynamic programming array here. + + >>> combination_sum_iv_bottom_up(3, [1,2,5], 5) + 9 + """ dp_array = [0] * (target + 1) dp_array[0] = 1 @@ -53,4 +99,4 @@ doctest.testmod() target = 5 array = [1, 2, 5] - print(combination_sum_iv(array, target))+ print(combination_sum_iv(array, target))
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][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def matrix_addition(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def matrix_subtraction(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def split_matrix(a: list) -> tuple[list, list, list, list]: if len(a) % 2 != 0 or len(a[0]) % 2 != 0: raise Exception("Odd matrices are not supported!") matrix_length = len(a) mid = matrix_length // 2 top_right = [[a[i][j] for j in range(mid, matrix_length)] for i in range(mid)] bot_right = [ [a[i][j] for j in range(mid, matrix_length)] for i in range(mid, matrix_length) ] top_left = [[a[i][j] for j in range(mid)] for i in range(mid)] bot_left = [[a[i][j] for j in range(mid)] for i in range(mid, matrix_length)] return top_left, top_right, bot_left, bot_right def matrix_dimensions(matrix: list) -> tuple[int, int]: return len(matrix), len(matrix[0]) def print_matrix(matrix: list) -> None: print("\n".join(str(line) for line in matrix)) def actual_strassen(matrix_a: list, matrix_b: list) -> list: if matrix_dimensions(matrix_a) == (2, 2): return default_matrix_multiplication(matrix_a, matrix_b) a, b, c, d = split_matrix(matrix_a) e, f, g, h = split_matrix(matrix_b) t1 = actual_strassen(a, matrix_subtraction(f, h)) t2 = actual_strassen(matrix_addition(a, b), h) t3 = actual_strassen(matrix_addition(c, d), e) t4 = actual_strassen(d, matrix_subtraction(g, e)) t5 = actual_strassen(matrix_addition(a, d), matrix_addition(e, h)) t6 = actual_strassen(matrix_subtraction(b, d), matrix_addition(g, h)) t7 = actual_strassen(matrix_subtraction(a, c), matrix_addition(e, f)) top_left = matrix_addition(matrix_subtraction(matrix_addition(t5, t4), t2), t6) top_right = matrix_addition(t1, t2) bot_left = matrix_addition(t3, t4) bot_right = matrix_subtraction(matrix_subtraction(matrix_addition(t1, t5), t3), t7) # construct the new matrix from our 4 quadrants new_matrix = [] for i in range(len(top_right)): new_matrix.append(top_left[i] + top_right[i]) for i in range(len(bot_right)): new_matrix.append(bot_left[i] + bot_right[i]) return new_matrix def strassen(matrix1: list, matrix2: list) -> list: if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: msg = ( "Unable to multiply these matrices, please check the dimensions.\n" f"Matrix A: {matrix1}\n" f"Matrix B: {matrix2}" ) raise Exception(msg) dimension1 = matrix_dimensions(matrix1) dimension2 = matrix_dimensions(matrix2) if dimension1[0] == dimension1[1] and dimension2[0] == dimension2[1]: return [matrix1, matrix2] maximum = max(*dimension1, *dimension2) maxim = int(math.pow(2, math.ceil(math.log2(maximum)))) new_matrix1 = matrix1 new_matrix2 = matrix2 # Adding zeros to the matrices to convert them both into square matrices of equal # dimensions that are a power of 2 for i in range(maxim): if i < dimension1[0]: for _ in range(dimension1[1], maxim): new_matrix1[i].append(0) else: new_matrix1.append([0] * maxim) if i < dimension2[0]: for _ in range(dimension2[1], maxim): new_matrix2[i].append(0) else: new_matrix2.append([0] * maxim) final_matrix = actual_strassen(new_matrix1, new_matrix2) # Removing the additional zeros for i in range(maxim): if i < dimension1[0]: for _ in range(dimension2[1], maxim): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": matrix1 = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrix1, matrix2))
--- +++ @@ -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 split_matrix(a: list) -> tuple[list, list, list, list]: + """ + Given an even length matrix, returns the top_left, top_right, bot_left, bot_right + quadrant. + + >>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]]) + ([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]]) + >>> split_matrix([ + ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6], + ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6] + ... ]) # doctest: +NORMALIZE_WHITESPACE + ([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], + [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], + [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], + [8, 4, 1, 6]]) + """ if len(a) % 2 != 0 or len(a[0]) % 2 != 0: raise Exception("Odd matrices are not supported!") @@ -54,6 +72,10 @@ def actual_strassen(matrix_a: list, matrix_b: list) -> list: + """ + Recursive function to calculate the product of two matrices, using the Strassen + Algorithm. It only supports square matrices of any size that is a power of 2. + """ if matrix_dimensions(matrix_a) == (2, 2): return default_matrix_multiplication(matrix_a, matrix_b) @@ -83,6 +105,12 @@ def strassen(matrix1: list, matrix2: list) -> list: + """ + >>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]]) + [[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]] + >>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]]) + [[139, 163], [121, 134], [100, 121]] + """ if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: msg = ( "Unable to multiply these matrices, please check the dimensions.\n" @@ -141,4 +169,4 @@ [6, 2, 3, 1], ] matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] - print(strassen(matrix1, matrix2))+ print(strassen(matrix1, matrix2))
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(text2) dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)] end_pos = 0 max_length = 0 for i in range(1, text1_length + 1): for j in range(1, text2_length + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] if dp[i][j] > max_length: end_pos = i max_length = dp[i][j] return text1[end_pos - max_length : end_pos] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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, algorithm should return any one of them. +""" def longest_common_substring(text1: str, text2: str) -> str: + """ + Finds the longest common substring between two strings. + + >>> longest_common_substring("", "") + '' + >>> longest_common_substring("a","") + '' + >>> longest_common_substring("", "a") + '' + >>> longest_common_substring("a", "a") + 'a' + >>> longest_common_substring("abcdef", "bcd") + 'bcd' + >>> longest_common_substring("abcdef", "xabded") + 'ab' + >>> longest_common_substring("GeeksforGeeks", "GeeksQuiz") + 'Geeks' + >>> longest_common_substring("abcdxyz", "xyzabcd") + 'abcd' + >>> longest_common_substring("zxabcdezy", "yzabcdezx") + 'abcdez' + >>> longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com") + 'Site:Geeks' + >>> longest_common_substring(1, 1) + Traceback (most recent call last): + ... + ValueError: longest_common_substring() takes two strings for inputs + """ if not (isinstance(text1, str) and isinstance(text2, str)): raise ValueError("longest_common_substring() takes two strings for inputs") @@ -29,4 +67,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 self.sequence[:index] def main() -> None: print( "Fibonacci Series Using Dynamic Programming\n", "Enter the index of the Fibonacci number you want to calculate ", "in the prompt below. (To exit enter exit or Ctrl-C)\n", sep="", ) fibonacci = Fibonacci() while True: prompt: str = input(">> ") if prompt in {"exit", "quit"}: break try: index: int = int(prompt) except ValueError: print("Enter a number or 'exit'") continue print(fibonacci.get(index)) if __name__ == "__main__": main()
--- +++ @@ -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 number does not exist, + calculate all missing numbers leading up to the number of `index`. + + >>> Fibonacci().get(10) + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] + >>> Fibonacci().get(5) + [0, 1, 1, 2, 3] + """ if (difference := index - (len(self.sequence) - 2)) >= 1: for _ in range(difference): self.sequence.append(self.sequence[-1] + self.sequence[-2]) @@ -35,4 +48,4 @@ if __name__ == "__main__": - main()+ main()
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) ] # dp[i][j] stores minimum distance from i to j def add_edge(self, u, v, w): self.dp[u][v] = w def floyd_warshall(self): for k in range(self.n): for i in range(self.n): for j in range(self.n): self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j]) def show_min(self, u, v): return self.dp[u][v] if __name__ == "__main__": import doctest doctest.testmod() # Example usage graph = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() print( graph.show_min(1, 4) ) # Should output the minimum distance from node 1 to node 4 print( graph.show_min(0, 3) ) # Should output the minimum distance from node 0 to node 3
--- +++ @@ -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(n)] for i in range(n) - ] # dp[i][j] stores minimum distance from i to j - - def add_edge(self, u, v, w): - self.dp[u][v] = w - - def floyd_warshall(self): - for k in range(self.n): - for i in range(self.n): - for j in range(self.n): - self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j]) - - def show_min(self, u, v): - return self.dp[u][v] - - -if __name__ == "__main__": - import doctest - - doctest.testmod() - - # Example usage - graph = Graph(5) - graph.add_edge(0, 2, 9) - graph.add_edge(0, 4, 10) - graph.add_edge(1, 3, 5) - graph.add_edge(2, 3, 7) - graph.add_edge(3, 0, 10) - graph.add_edge(3, 1, 2) - graph.add_edge(3, 2, 1) - graph.add_edge(3, 4, 6) - graph.add_edge(4, 1, 3) - graph.add_edge(4, 2, 4) - graph.add_edge(4, 3, 9) - graph.floyd_warshall() - print( - graph.show_min(1, 4) - ) # Should output the minimum distance from node 1 to node 4 - print( - graph.show_min(0, 3) - ) # Should output the minimum distance from node 0 to node 3+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) + ] # dp[i][j] stores minimum distance from i to j + + def add_edge(self, u, v, w): + """ + Adds a directed edge from node u + to node v with weight w. + + >>> g = Graph(3) + >>> g.add_edge(0, 1, 5) + >>> g.dp[0][1] + 5 + """ + self.dp[u][v] = w + + def floyd_warshall(self): + """ + Computes the shortest paths between all pairs of + nodes using the Floyd-Warshall algorithm. + + >>> g = Graph(3) + >>> g.add_edge(0, 1, 1) + >>> g.add_edge(1, 2, 2) + >>> g.floyd_warshall() + >>> g.show_min(0, 2) + 3 + >>> g.show_min(2, 0) + inf + """ + for k in range(self.n): + for i in range(self.n): + for j in range(self.n): + self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j]) + + def show_min(self, u, v): + """ + Returns the minimum distance from node u to node v. + + >>> g = Graph(3) + >>> g.add_edge(0, 1, 3) + >>> g.add_edge(1, 2, 4) + >>> g.floyd_warshall() + >>> g.show_min(0, 2) + 7 + >>> g.show_min(1, 0) + inf + """ + return self.dp[u][v] + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + + # Example usage + graph = Graph(5) + graph.add_edge(0, 2, 9) + graph.add_edge(0, 4, 10) + graph.add_edge(1, 3, 5) + graph.add_edge(2, 3, 7) + graph.add_edge(3, 0, 10) + graph.add_edge(3, 1, 2) + graph.add_edge(3, 2, 1) + graph.add_edge(3, 4, 6) + graph.add_edge(4, 1, 3) + graph.add_edge(4, 2, 4) + graph.add_edge(4, 3, 9) + graph.floyd_warshall() + print( + graph.show_min(1, 4) + ) # Should output the minimum distance from node 1 to node 4 + print( + graph.show_min(0, 3) + ) # Should output the minimum distance from node 0 to node 3
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) # F(2n) = F(n)[2F(n+1) - F(n)] # F(2n+1) = F(n+1)^2+F(n)^2 a, b = _fib(n // 2) c = a * (b * 2 - a) d = a * a + b * b return (d, c + d) if n % 2 else (c, d) if __name__ == "__main__": n = int(sys.argv[1]) print(f"fibonacci({n}) is {fibonacci(n)}")
--- +++ @@ -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) + >>> [fibonacci(i) for i in range(13)] + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] + """ if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] @@ -27,4 +36,4 @@ if __name__ == "__main__": n = int(sys.argv[1]) - print(f"fibonacci({n}) is {fibonacci(n)}")+ print(f"fibonacci({n}) is {fibonacci(n)}")
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: return self.dp[m][n] else: if self.word1[m] == self.word2[n]: self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1) else: insert = self.__min_dist_top_down_dp(m, n - 1) delete = self.__min_dist_top_down_dp(m - 1, n) replace = self.__min_dist_top_down_dp(m - 1, n - 1) self.dp[m][n] = 1 + min(insert, delete, replace) return self.dp[m][n] def min_dist_top_down(self, word1: str, word2: str) -> int: self.word1 = word1 self.word2 = word2 self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))] return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1) def min_dist_bottom_up(self, word1: str, word2: str) -> int: self.word1 = word1 self.word2 = word2 m = len(word1) n = len(word2) self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0: # first string is empty self.dp[i][j] = j elif j == 0: # second string is empty self.dp[i][j] = i elif word1[i - 1] == word2[j - 1]: # last characters are equal self.dp[i][j] = self.dp[i - 1][j - 1] else: insert = self.dp[i][j - 1] delete = self.dp[i - 1][j] replace = self.dp[i - 1][j - 1] self.dp[i][j] = 1 + min(insert, delete, replace) return self.dp[m][n] if __name__ == "__main__": solver = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() S1 = input("Enter the first string: ").strip() S2 = input("Enter the second string: ").strip() print() print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}") print(f"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}") print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
--- +++ @@ -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 operations are removal, insertion, and substitution. +""" class EditDistance: + """ + Use : + solver = EditDistance() + editDistanceResult = solver.solve(firstString, secondString) + """ def __init__(self): self.word1 = "" @@ -26,6 +42,14 @@ return self.dp[m][n] def min_dist_top_down(self, word1: str, word2: str) -> int: + """ + >>> EditDistance().min_dist_top_down("intention", "execution") + 5 + >>> EditDistance().min_dist_top_down("intention", "") + 9 + >>> EditDistance().min_dist_top_down("", "") + 0 + """ self.word1 = word1 self.word2 = word2 self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))] @@ -33,6 +57,14 @@ return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1) def min_dist_bottom_up(self, word1: str, word2: str) -> int: + """ + >>> EditDistance().min_dist_bottom_up("intention", "execution") + 5 + >>> EditDistance().min_dist_bottom_up("intention", "") + 9 + >>> EditDistance().min_dist_bottom_up("", "") + 0 + """ self.word1 = word1 self.word2 = word2 m = len(word1) @@ -68,4 +100,4 @@ print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}") print(f"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}") print() - print("*************** End of Testing Edit Distance DP Algorithm ***************")+ print("*************** End of Testing Edit Distance DP Algorithm ***************")
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 == high: return low, high, arr[low] mid = (low + high) // 2 left_low, left_high, left_sum = max_subarray(arr, low, mid) right_low, right_high, right_sum = max_subarray(arr, mid + 1, high) cross_left, cross_right, cross_sum = max_cross_sum(arr, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def max_cross_sum( arr: Sequence[float], low: int, mid: int, high: int ) -> tuple[int, int, float]: left_sum, max_left = float("-inf"), -1 right_sum, max_right = float("-inf"), -1 summ: int | float = 0 for i in range(mid, low - 1, -1): summ += arr[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += arr[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def time_max_subarray(input_size: int) -> float: arr = [randint(1, input_size) for _ in range(input_size)] start = time.time() max_subarray(arr, 0, input_size - 1) end = time.time() return end - start def plot_runtimes() -> None: input_sizes = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] runtimes = [time_max_subarray(input_size) for input_size in input_sizes] print("No of Inputs\t\tTime Taken") for input_size, runtime in zip(input_sizes, runtimes): print(input_size, "\t\t", runtime) plt.plot(input_sizes, runtimes) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds") plt.show() if __name__ == "__main__": """ A random simulation of this algorithm. """ from doctest import testmod testmod()
--- +++ @@ -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. + +This divide-and-conquer algorithm finds the maximum subarray in O(n log n) time. +""" from __future__ import annotations @@ -11,6 +19,32 @@ def max_subarray( arr: Sequence[float], low: int, high: int ) -> tuple[int | None, int | None, float]: + """ + Solves the maximum subarray problem using divide and conquer. + :param arr: the given array of numbers + :param low: the start index + :param high: the end index + :return: the start index of the maximum subarray, the end index of the + maximum subarray, and the maximum subarray sum + + >>> nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] + >>> max_subarray(nums, 0, len(nums) - 1) + (3, 6, 6) + >>> nums = [2, 8, 9] + >>> max_subarray(nums, 0, len(nums) - 1) + (0, 2, 19) + >>> nums = [0, 0] + >>> max_subarray(nums, 0, len(nums) - 1) + (0, 0, 0) + >>> nums = [-1.0, 0.0, 1.0] + >>> max_subarray(nums, 0, len(nums) - 1) + (2, 2, 1.0) + >>> nums = [-2, -3, -1, -4, -6] + >>> max_subarray(nums, 0, len(nums) - 1) + (2, 2, -1) + >>> max_subarray([], 0, 0) + (None, None, 0) + """ if not arr: return None, None, 0 if low == high: @@ -76,4 +110,4 @@ """ from doctest import testmod - testmod()+ testmod()
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_palindromic[j + 1][i - 1]): is_palindromic[j][i] = True mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1)) cut[i] = mincut return cut[length - 1] if __name__ == "__main__": s = input("Enter the string: ").strip() ans = find_minimum_partitions(s) print(f"Minimum number of partitions required for the '{s}' is {ans}")
--- +++ @@ -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 +""" def find_minimum_partitions(string: str) -> int: + """ + Returns the minimum cuts needed for a palindrome partitioning of string + + >>> find_minimum_partitions("aab") + 1 + >>> find_minimum_partitions("aaa") + 0 + >>> find_minimum_partitions("ababbbabbababa") + 3 + """ length = len(string) cut = [0] * length is_palindromic = [[False for i in range(length)] for j in range(length)] @@ -17,4 +36,4 @@ if __name__ == "__main__": s = input("Enter the string: ").strip() ans = find_minimum_partitions(s) - print(f"Minimum number of partitions required for the '{s}' is {ans}")+ print(f"Minimum number of partitions required for the '{s}' is {ans}")
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 in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 algorithm: +https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf +""" from __future__ import annotations @@ -5,10 +15,28 @@ def random_pivot(lst): + """ + Choose a random pivot for the list. + We can use a more sophisticated algorithm here, such as the median-of-medians + algorithm. + """ return choice(lst) def kth_number(lst: list[int], k: int) -> int: + """ + Return the kth smallest number in lst. + >>> kth_number([2, 1, 3, 4, 5], 3) + 3 + >>> kth_number([2, 1, 3, 4, 5], 1) + 1 + >>> kth_number([2, 1, 3, 4, 5], 5) + 5 + >>> kth_number([3, 2, 5, 6, 7, 8], 2) + 3 + >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) + 43 + """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) @@ -35,4 +63,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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, match: int = 1, mismatch: int = -1, gap: int = -2, ) -> list[list[int]]: # make both query and subject uppercase query = query.upper() subject = subject.upper() # Initialize score matrix m = len(query) n = len(subject) score = [[0] * (n + 1) for _ in range(m + 1)] kwargs = {"match": match, "mismatch": mismatch, "gap": gap} for i in range(1, m + 1): for j in range(1, n + 1): # Calculate scores for each cell match = score[i - 1][j - 1] + score_function( query[i - 1], subject[j - 1], **kwargs ) delete = score[i - 1][j] + gap insert = score[i][j - 1] + gap # Take maximum score score[i][j] = max(0, match, delete, insert) return score def traceback(score: list[list[int]], query: str, subject: str) -> str: # make both query and subject uppercase query = query.upper() subject = subject.upper() # find the indices of the maximum value in the score matrix max_value = float("-inf") i_max = j_max = 0 for i, row in enumerate(score): for j, value in enumerate(row): if value > max_value: max_value = value i_max, j_max = i, j # Traceback logic to find optimal alignment i = i_max j = j_max align1 = "" align2 = "" gap = score_function("-", "-") # guard against empty query or subject if i == 0 or j == 0: return "" while i > 0 and j > 0: if score[i][j] == score[i - 1][j - 1] + score_function( query[i - 1], subject[j - 1] ): # optimal path is a diagonal take both letters align1 = query[i - 1] + align1 align2 = subject[j - 1] + align2 i -= 1 j -= 1 elif score[i][j] == score[i - 1][j] + gap: # optimal path is a vertical align1 = query[i - 1] + align1 align2 = f"-{align2}" i -= 1 else: # optimal path is a horizontal align1 = f"-{align1}" align2 = subject[j - 1] + align2 j -= 1 return f"{align1}\n{align2}" if __name__ == "__main__": query = "HEAGAWGHEE" subject = "PAWHEAE" score = smith_waterman(query, subject, match=1, mismatch=-1, gap=-2) print(traceback(score, query, subject))
--- +++ @@ -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, gaps are penalized +linearly, meaning that the score is reduced by a fixed amount for each gap introduced +in the alignment. However, it's important to note that the Smith-Waterman algorithm +supports other gap penalty methods as well. +""" def score_function( @@ -7,6 +16,21 @@ mismatch: int = -1, gap: int = -2, ) -> int: + """ + Calculate the score for a character pair based on whether they match or mismatch. + Returns 1 if the characters match, -1 if they mismatch, and -2 if either of the + characters is a gap. + >>> score_function('A', 'A') + 1 + >>> score_function('A', 'C') + -1 + >>> score_function('-', 'A') + -2 + >>> score_function('A', '-') + -2 + >>> score_function('-', '-') + -2 + """ if "-" in (source_char, target_char): return gap return match if source_char == target_char else mismatch @@ -19,6 +43,64 @@ mismatch: int = -1, gap: int = -2, ) -> list[list[int]]: + """ + Perform the Smith-Waterman local sequence alignment algorithm. + Returns a 2D list representing the score matrix. Each value in the matrix + corresponds to the score of the best local alignment ending at that point. + >>> smith_waterman('ACAC', 'CA') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + >>> smith_waterman('acac', 'ca') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + >>> smith_waterman('ACAC', 'ca') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + >>> smith_waterman('acac', 'CA') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + >>> smith_waterman('ACAC', '') + [[0], [0], [0], [0], [0]] + >>> smith_waterman('', 'CA') + [[0, 0, 0]] + >>> smith_waterman('ACAC', 'CA') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + + >>> smith_waterman('acac', 'ca') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + + >>> smith_waterman('ACAC', 'ca') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + + >>> smith_waterman('acac', 'CA') + [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] + + >>> smith_waterman('ACAC', '') + [[0], [0], [0], [0], [0]] + + >>> smith_waterman('', 'CA') + [[0, 0, 0]] + + >>> smith_waterman('AGT', 'AGT') + [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]] + + >>> smith_waterman('AGT', 'GTA') + [[0, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 2, 0]] + + >>> smith_waterman('AGT', 'GTC') + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0]] + + >>> smith_waterman('AGT', 'G') + [[0, 0], [0, 0], [0, 1], [0, 0]] + + >>> smith_waterman('G', 'AGT') + [[0, 0, 0, 0], [0, 0, 1, 0]] + + >>> smith_waterman('AGT', 'AGTCT') + [[0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 2, 0, 0, 0], [0, 0, 0, 3, 1, 1]] + + >>> smith_waterman('AGTCT', 'AGT') + [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3], [0, 0, 0, 1], [0, 0, 0, 1]] + + >>> smith_waterman('AGTCT', 'GTC') + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3], [0, 0, 1, 1]] + """ # make both query and subject uppercase query = query.upper() subject = subject.upper() @@ -45,6 +127,21 @@ def traceback(score: list[list[int]], query: str, subject: str) -> str: + r""" + Perform traceback to find the optimal local alignment. + Starts from the highest scoring cell in the matrix and traces back recursively + until a 0 score is found. Returns the alignment strings. + >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'ACAC', 'CA') + 'CA\nCA' + >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'acac', 'ca') + 'CA\nCA' + >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'ACAC', 'ca') + 'CA\nCA' + >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'acac', 'CA') + 'CA\nCA' + >>> traceback([[0, 0, 0]], 'ACAC', '') + '' + """ # make both query and subject uppercase query = query.upper() subject = subject.upper() @@ -93,4 +190,4 @@ subject = "PAWHEAE" score = smith_waterman(query, subject, match=1, mismatch=-1, gap=-2) - print(traceback(score, query, subject))+ print(traceback(score, query, subject))
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, n + 1): match = 1 if x[i - 1] == y[j - 1] else 0 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] + match) seq = "" i, j = m, n while i > 0 and j > 0: match = 1 if x[i - 1] == y[j - 1] else 0 if dp[i][j] == dp[i - 1][j - 1] + match: if match == 1: seq = x[i - 1] + seq i -= 1 j -= 1 elif dp[i][j] == dp[i - 1][j]: i -= 1 else: j -= 1 return dp[m][n], seq if __name__ == "__main__": a = "AGGTAB" b = "GXTXAYB" expected_ln = 4 expected_subseq = "GTAB" ln, subseq = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
--- +++ @@ -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_common_subsequence(x: str, y: str): + """ + Finds the longest common subsequence between two strings. Also returns the + The subsequence found + + Parameters + ---------- + + x: str, one of the strings + y: str, the other string + + Returns + ------- + L[m][n]: int, the length of the longest subsequence. Also equal to len(seq) + Seq: str, the subsequence found + + >>> longest_common_subsequence("programming", "gaming") + (6, 'gaming') + >>> longest_common_subsequence("physics", "smartphone") + (2, 'ph') + >>> longest_common_subsequence("computer", "food") + (1, 'o') + >>> longest_common_subsequence("", "abc") # One string is empty + (0, '') + >>> longest_common_subsequence("abc", "") # Other string is empty + (0, '') + >>> longest_common_subsequence("", "") # Both strings are empty + (0, '') + >>> longest_common_subsequence("abc", "def") # No common subsequence + (0, '') + >>> longest_common_subsequence("abc", "abc") # Identical strings + (3, 'abc') + >>> longest_common_subsequence("a", "a") # Single character match + (1, 'a') + >>> longest_common_subsequence("a", "b") # Single character no match + (0, '') + >>> longest_common_subsequence("abcdef", "ace") # Interleaved subsequence + (3, 'ace') + >>> longest_common_subsequence("ABCD", "ACBD") # No repeated characters + (3, 'ABD') + """ # find the length of strings assert x is not None @@ -46,4 +92,4 @@ print("len =", ln, ", sub-sequence =", subseq) import doctest - doctest.testmod()+ doctest.testmod()
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 till we reach empty submask that is zero ( zero is not included in final submasks list ) """ all_submasks = [] submask = mask while submask: all_submasks.append(submask) submask = (submask - 1) & mask return all_submasks if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 def list_of_submasks(mask: int) -> list[int]: + """ + Args: + mask : number which shows mask ( always integer > 0, zero does not have any + submasks ) + + Returns: + all_submasks : the list of submasks of mask (mask s is called submask of mask + m if only bits that were included in original mask are set + + Raises: + AssertionError: mask not positive integer + + >>> list_of_submasks(15) + [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + >>> list_of_submasks(13) + [13, 12, 9, 8, 5, 4, 1] + >>> list_of_submasks(-7) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + AssertionError: mask needs to be positive integer, your input -7 + >>> list_of_submasks(0) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + AssertionError: mask needs to be positive integer, your input 0 + + """ assert isinstance(mask, int) and mask > 0, ( f"mask needs to be positive integer, your input {mask}" @@ -26,4 +59,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 for i in range(1, n + 1): for j in range(1, m + 1): # If characters at i and j are the same # include them in the palindromic subsequence if input_string[i - 1] == rev[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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/ +""" def longest_palindromic_subsequence(input_string: str) -> int: + """ + This function returns the longest palindromic subsequence in a string + >>> longest_palindromic_subsequence("bbbab") + 4 + >>> longest_palindromic_subsequence("bbabcbcab") + 7 + """ n = len(input_string) rev = input_string[::-1] m = len(rev) @@ -26,4 +41,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 pivot = array[0] is_found = False i = 1 longest_subseq: list[int] = [] while not is_found and i < array_length: if array[i] < pivot: is_found = True temp_array = array[i:] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot, *longest_subsequence(temp_array)] if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: + ``[10, 22, 9, 33, 21, 50, 41, 60, 80]`` as input will return + ``[10, 22, 33, 41, 60, 80]`` as output +""" from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive + """ + Some examples + + >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) + [10, 22, 33, 41, 60, 80] + >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) + [1, 2, 3, 9] + >>> longest_subsequence([28, 26, 12, 23, 35, 39]) + [12, 23, 35, 39] + >>> longest_subsequence([9, 8, 7, 6, 5, 7]) + [5, 7] + >>> longest_subsequence([1, 1, 1]) + [1, 1, 1] + >>> longest_subsequence([]) + [] + """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) @@ -34,4 +64,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2, upper_limit + 1): for j in range(i): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: N = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
--- +++ @@ -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 number well-formed expressions with n pairs of parentheses + * (e.g., `()()` is valid but `())(` is not) + * - The number of different ways n + 1 factors can be completely + * parenthesized (e.g., for n = 2, C(n) = 2 and (ab)c and a(bc) + * are the two valid ways to parenthesize. + * - The number of full binary trees with n + 1 leaves + + * A Catalan number satisfies the following recurrence relation + * which we will use in this algorithm [1]. + * C(0) = C(1) = 1 + * C(n) = sum(C(i).C(n-i-1)), from i = 0 to n-1 + + * In addition, the n-th Catalan number can be calculated using + * the closed form formula below [1]: + * C(n) = (1 / (n + 1)) * (2n choose n) + + * Sources: + * [1] https://brilliant.org/wiki/catalan-numbers/ + * [2] https://en.wikipedia.org/wiki/Catalan_number +""" def catalan_numbers(upper_limit: int) -> "list[int]": + """ + Return a list of the Catalan number sequence from 0 through `upper_limit`. + + >>> catalan_numbers(5) + [1, 1, 2, 5, 14, 42] + >>> catalan_numbers(2) + [1, 1, 2] + >>> catalan_numbers(-1) + Traceback (most recent call last): + ValueError: Limit for the Catalan sequence must be ≥ 0 + """ if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") @@ -38,4 +76,4 @@ import doctest - doctest.testmod()+ doctest.testmod()
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 value!" raise ValueError(msg) sum_c += capacitor return sum_c def capacitor_series(capacitors: list[float]) -> float: first_sum = 0.0 for index, capacitor in enumerate(capacitors): if capacitor <= 0: msg = f"Capacitor at index {index} has a negative or zero value!" raise ValueError(msg) first_sum += 1 / capacitor return 1 / first_sum if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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]) + Traceback (most recent call last): + ... + ValueError: Capacitor at index 2 has a negative value! + """ sum_c = 0.0 for index, capacitor in enumerate(capacitors): if capacitor < 0: @@ -14,6 +24,19 @@ def capacitor_series(capacitors: list[float]) -> float: + """ + Ceq = 1/ (1/C1 + 1/C2 + ... + 1/Cn) + >>> capacitor_series([5.71389, 12, 3]) + 1.6901062252507735 + >>> capacitor_series([5.71389, 12, -3]) + Traceback (most recent call last): + ... + ValueError: Capacitor at index 2 has a negative or zero value! + >>> capacitor_series([5.71389, 12, 0.000]) + Traceback (most recent call last): + ... + ValueError: Capacitor at index 2 has a negative or zero value! + """ first_sum = 0.0 for index, capacitor in enumerate(capacitors): @@ -27,4 +50,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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]) + val[i - 1], ) f[i][j] = val return f[i][j] def knapsack(w, wt, val, n): dp = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w_ in range(1, w + 1): if wt[i - 1] <= w_: dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_]) else: dp[i][w_] = dp[i - 1][w_] return dp[n][w_], dp def knapsack_with_example_solution(w: int, wt: list, val: list): if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): msg = ( "The number of weights must be the same as the number of values.\n" f"But got {num_items} weights and {len(val)} values" ) raise ValueError(msg) for i in range(num_items): if not isinstance(wt[i], int): msg = ( "All weights must be integers but got weight of " f"type {type(wt[i])} at index {i}" ) raise TypeError(msg) optimal_val, dp_table = knapsack(w, wt, val, num_items) example_optional_set: set = set() _construct_solution(dp_table, wt, num_items, w, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 f = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
--- +++ @@ -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 code involves the concept of memory functions. Here we solve the subproblems + which are needed unlike the below example + F is a 2D array with ``-1`` s filled up + """ global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: @@ -28,6 +40,39 @@ def knapsack_with_example_solution(w: int, wt: list, val: list): + """ + Solves the integer weights knapsack problem returns one of + the several possible optimal subsets. + + Parameters + ---------- + + * `w`: int, the total maximum weight for the given knapsack problem. + * `wt`: list, the vector of weights for all items where ``wt[i]`` is the weight + of the ``i``-th item. + * `val`: list, the vector of values for all items where ``val[i]`` is the value + of the ``i``-th item + + Returns + ------- + + * `optimal_val`: float, the optimal value for the given knapsack problem + * `example_optional_set`: set, the indices of one of the optimal subsets + which gave rise to the optimal value. + + Examples + -------- + + >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) + (142, {2, 3, 4}) + >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) + (8, {3, 4}) + >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) + Traceback (most recent call last): + ... + ValueError: The number of weights must be the same as the number of values. + But got 4 weights and 3 values + """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" @@ -56,6 +101,25 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): + """ + Recursively reconstructs one of the optimal subsets given + a filled DP table and the vector of weights + + Parameters + ---------- + + * `dp`: list of list, the table of a solved integer weight dynamic programming + problem + * `wt`: list or tuple, the vector of weights of the items + * `i`: int, the index of the item under consideration + * `j`: int, the current possible maximum weight + * `optimal_set`: set, the optimal subset so far. This gets modified by the function. + + Returns + ------- + + ``None`` + """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight @@ -86,4 +150,4 @@ assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) - print("An optimal subset corresponding to the optimal value", optimal_subset)+ print("An optimal subset corresponding to the optimal value", optimal_subset)
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: return len_word2 - index2 # if second word index overflows - delete all from the first word if index2 >= len_word2: return len_word1 - index1 diff = int(word1[index1] != word2[index2]) # current letters not identical return min( 1 + min_distance(index1 + 1, index2), 1 + min_distance(index1, index2 + 1), diff + min_distance(index1 + 1, index2 + 1), ) return min_distance(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. +""" import functools def min_distance_up_bottom(word1: str, word2: str) -> int: + """ + >>> min_distance_up_bottom("intention", "execution") + 5 + >>> min_distance_up_bottom("intention", "") + 9 + >>> min_distance_up_bottom("", "") + 0 + >>> min_distance_up_bottom("zooicoarchaeologist", "zoologist") + 10 + """ len_word1 = len(word1) len_word2 = len(word2) @@ -27,4 +46,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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, transition_probabilities, emission_probabilities, ) # Creates data structures and fill initial step probabilities: dict = {} pointers: dict = {} for state in states_space: observation = observations_space[0] probabilities[(state, observation)] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1, len(observations_space)): observation = observations_space[o] prior_observation = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function arg_max = "" max_probability = -1 for k_state in states_space: probability = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: max_probability = probability arg_max = k_state # Update probabilities and pointers dicts probabilities[(state, observation)] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = arg_max # The final observation final_observation = observations_space[len(observations_space) - 1] # argmax for given final observation arg_max = "" max_probability = -1 for k_state in states_space: probability = probabilities[(k_state, final_observation)] if probability > max_probability: max_probability = probability arg_max = k_state last_state = arg_max # Process pointers backwards previous = last_state result = [] for o in range(len(observations_space) - 1, -1, -1): result.append(previous) previous = pointers[previous, observations_space[o]] result.reverse() return result def _validation( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: _validate_not_empty( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) _validate_lists(observations_space, states_space) _validate_dicts( initial_probabilities, transition_probabilities, emission_probabilities ) def _validate_not_empty( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter") def _validate_lists(observations_space: Any, states_space: Any) -> None: _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: if not isinstance(_object, list): msg = f"{var_name} must be a list" raise ValueError(msg) else: for x in _object: if not isinstance(x, str): msg = f"{var_name} must be a list of strings" raise ValueError(msg) def _validate_dicts( initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: if not isinstance(_object, dict): msg = f"{var_name} must be a dict" raise ValueError(msg) if not all(isinstance(x, str) for x in _object): msg = f"{var_name} all keys must be strings" raise ValueError(msg) if not all(isinstance(x, value_type) for x in _object.values()): nested_text = "nested dictionary " if nested else "" msg = f"{var_name} {nested_text}all values must be {value_type.__name__}" raise ValueError(msg) if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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 + + >>> observations = ["normal", "cold", "dizzy"] + >>> states = ["Healthy", "Fever"] + >>> start_p = {"Healthy": 0.6, "Fever": 0.4} + >>> trans_p = { + ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, + ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, + ... } + >>> emit_p = { + ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, + ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, + ... } + >>> viterbi(observations, states, start_p, trans_p, emit_p) + ['Healthy', 'Healthy', 'Fever'] + >>> viterbi((), states, start_p, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + >>> viterbi(observations, (), start_p, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + >>> viterbi(observations, states, {}, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + >>> viterbi(observations, states, start_p, {}, emit_p) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + >>> viterbi(observations, states, start_p, trans_p, {}) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + >>> viterbi("invalid", states, start_p, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: observations_space must be a list + >>> viterbi(["valid", 123], states, start_p, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: observations_space must be a list of strings + >>> viterbi(observations, "invalid", start_p, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: states_space must be a list + >>> viterbi(observations, ["valid", 123], start_p, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: states_space must be a list of strings + >>> viterbi(observations, states, "invalid", trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: initial_probabilities must be a dict + >>> viterbi(observations, states, {2:2}, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: initial_probabilities all keys must be strings + >>> viterbi(observations, states, {"a":2}, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: initial_probabilities all values must be float + >>> viterbi(observations, states, start_p, "invalid", emit_p) + Traceback (most recent call last): + ... + ValueError: transition_probabilities must be a dict + >>> viterbi(observations, states, start_p, {"a":2}, emit_p) + Traceback (most recent call last): + ... + ValueError: transition_probabilities all values must be dict + >>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p) + Traceback (most recent call last): + ... + ValueError: transition_probabilities all keys must be strings + >>> viterbi(observations, states, start_p, {"a":{2:2}}, emit_p) + Traceback (most recent call last): + ... + ValueError: transition_probabilities all keys must be strings + >>> viterbi(observations, states, start_p, {"a":{"b":2}}, emit_p) + Traceback (most recent call last): + ... + ValueError: transition_probabilities nested dictionary all values must be float + >>> viterbi(observations, states, start_p, trans_p, "invalid") + Traceback (most recent call last): + ... + ValueError: emission_probabilities must be a dict + >>> viterbi(observations, states, start_p, trans_p, None) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + + """ _validation( observations_space, states_space, @@ -84,6 +183,24 @@ transition_probabilities: Any, emission_probabilities: Any, ) -> None: + """ + >>> observations = ["normal", "cold", "dizzy"] + >>> states = ["Healthy", "Fever"] + >>> start_p = {"Healthy": 0.6, "Fever": 0.4} + >>> trans_p = { + ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, + ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, + ... } + >>> emit_p = { + ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, + ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, + ... } + >>> _validation(observations, states, start_p, trans_p, emit_p) + >>> _validation([], states, start_p, trans_p, emit_p) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + """ _validate_not_empty( observations_space, states_space, @@ -104,6 +221,18 @@ transition_probabilities: Any, emission_probabilities: Any, ) -> None: + """ + >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, + ... {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) + >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, {}, {"f": {"g": 0.7}}) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + >>> _validate_not_empty(["a"], ["b"], None, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) + Traceback (most recent call last): + ... + ValueError: There's an empty parameter + """ if not all( [ observations_space, @@ -117,11 +246,33 @@ def _validate_lists(observations_space: Any, states_space: Any) -> None: + """ + >>> _validate_lists(["a"], ["b"]) + >>> _validate_lists(1234, ["b"]) + Traceback (most recent call last): + ... + ValueError: observations_space must be a list + >>> _validate_lists(["a"], [3]) + Traceback (most recent call last): + ... + ValueError: states_space must be a list of strings + """ _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: + """ + >>> _validate_list(["a"], "mock_name") + >>> _validate_list("a", "mock_name") + Traceback (most recent call last): + ... + ValueError: mock_name must be a list + >>> _validate_list([0.5], "mock_name") + Traceback (most recent call last): + ... + ValueError: mock_name must be a list of strings + """ if not isinstance(_object, list): msg = f"{var_name} must be a list" raise ValueError(msg) @@ -137,12 +288,50 @@ transition_probabilities: Any, emission_probabilities: Any, ) -> None: + """ + >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) + >>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) + Traceback (most recent call last): + ... + ValueError: initial_probabilities must be a dict + >>> _validate_dicts({"c":0.5}, {2: {"e": 0.6}}, {"f": {"g": 0.7}}) + Traceback (most recent call last): + ... + ValueError: transition_probabilities all keys must be strings + >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {2: 0.7}}) + Traceback (most recent call last): + ... + ValueError: emission_probabilities all keys must be strings + >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": "h"}}) + Traceback (most recent call last): + ... + ValueError: emission_probabilities nested dictionary all values must be float + """ _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: + """ + >>> _validate_nested_dict({"a":{"b": 0.5}}, "mock_name") + >>> _validate_nested_dict("invalid", "mock_name") + Traceback (most recent call last): + ... + ValueError: mock_name must be a dict + >>> _validate_nested_dict({"a": 8}, "mock_name") + Traceback (most recent call last): + ... + ValueError: mock_name all values must be dict + >>> _validate_nested_dict({"a":{2: 0.5}}, "mock_name") + Traceback (most recent call last): + ... + ValueError: mock_name all keys must be strings + >>> _validate_nested_dict({"a":{"b": 4}}, "mock_name") + Traceback (most recent call last): + ... + ValueError: mock_name nested dictionary all values must be float + """ _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) @@ -151,6 +340,25 @@ def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: + """ + >>> _validate_dict({"b": 0.5}, "mock_name", float) + >>> _validate_dict("invalid", "mock_name", float) + Traceback (most recent call last): + ... + ValueError: mock_name must be a dict + >>> _validate_dict({"a": 8}, "mock_name", dict) + Traceback (most recent call last): + ... + ValueError: mock_name all values must be dict + >>> _validate_dict({2: 0.5}, "mock_name",float, True) + Traceback (most recent call last): + ... + ValueError: mock_name all keys must be strings + >>> _validate_dict({"b": 4}, "mock_name", float,True) + Traceback (most recent call last): + ... + ValueError: mock_name nested dictionary all values must be float + """ if not isinstance(_object, dict): msg = f"{var_name} must be a dict" raise ValueError(msg) @@ -166,4 +374,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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 in enumerate(string, 1): for j, p_char in enumerate(pattern, 1): if p_char in (s_char, "?"): dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": dp[i][j] = dp[i - 1][j] or dp[i][j - 1] return dp[len(string)][len(pattern)] if __name__ == "__main__": import doctest doctest.testmod() print(f"{is_match('baaabab','*****ba*****ab') = }")
--- +++ @@ -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 should cover the entire input string (not partial). + +Runtime complexity: O(m * n) + +The implementation was tested on the +leetcode: https://leetcode.com/problems/wildcard-matching/ +""" def is_match(string: str, pattern: str) -> bool: + """ + >>> is_match("", "") + True + >>> is_match("aa", "a") + False + >>> is_match("abc", "abc") + True + >>> is_match("abc", "*c") + True + >>> is_match("abc", "a*") + True + >>> is_match("abc", "*a*") + True + >>> is_match("abc", "?b?") + True + >>> is_match("abc", "*?") + True + >>> is_match("abc", "a*d") + False + >>> is_match("abc", "a*c?") + False + >>> is_match('baaabab','*****ba*****ba') + False + >>> is_match('baaabab','*****ba*****ab') + True + >>> is_match('aa','*') + True + """ dp = [[False] * (len(pattern) + 1) for _ in string + "1"] dp[0][0] = True # Fill in the first row @@ -21,4 +65,4 @@ import doctest doctest.testmod() - print(f"{is_match('baaabab','*****ba*****ab') = }")+ print(f"{is_match('baaabab','*****ba*****ab') = }")
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, right = query res = dp[right] if left > 0: res -= dp[left - 1] result.append(res) return result if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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) + +Example: + arr = [1, 4, 6, 2, 61, 12] + queries = 3 + l_1 = 2, r_1 = 5 + l_2 = 1, r_2 = 5 + l_3 = 3, r_3 = 4 + + as input will return + + [81, 85, 63] + + as output + +0-indexing: +NOTE: 0-indexing means the indexing of the array starts from 0 +Example: a = [1, 2, 3, 4, 5, 6] + Here, the 0th index of a is 1, + the 1st index of a is 2, + and so forth + +Time Complexity: O(N + Q) +* O(N) pre-calculation time to calculate the prefix sum array +* and O(1) time per each query = O(1 * Q) = O(Q) time + +Space Complexity: O(N) +* O(N) to store the prefix sum + +Algorithm: +So, first we calculate the prefix sum (dp) of the array. +The prefix sum of the index i is the sum of all elements indexed +from 0 to i (inclusive). +The prefix sum of the index i is the prefix sum of index (i - 1) + the current element. +So, the state of the dp is dp[i] = dp[i - 1] + a[i]. + +After we calculate the prefix sum, +for each query [l, r] +the answer is dp[r] - dp[l - 1] (we need to be careful because l might be 0). +For example take this array: + [4, 2, 1, 6, 3] +The prefix sum calculated for this array would be: + [4, 4 + 2, 4 + 2 + 1, 4 + 2 + 1 + 6, 4 + 2 + 1 + 6 + 3] + ==> [4, 6, 7, 13, 16] +If the query was l = 3, r = 4, +the answer would be 6 + 3 = 9 but this would require O(r - l + 1) time ≈ O(N) time + +If we use prefix sums we can find it in O(1) by using the formula +prefix[r] - prefix[l - 1]. +This formula works because prefix[r] is the sum of elements from [0, r] +and prefix[l - 1] is the sum of elements from [0, l - 1], +so if we do prefix[r] - prefix[l - 1] it will be +[0, r] - [0, l - 1] = [0, l - 1] + [l, r] - [0, l - 1] = [l, r] +""" def prefix_sum(array: list[int], queries: list[tuple[int, int]]) -> list[int]: + """ + >>> prefix_sum([1, 4, 6, 2, 61, 12], [(2, 5), (1, 5), (3, 4)]) + [81, 85, 63] + >>> prefix_sum([4, 2, 1, 6, 3], [(3, 4), (1, 3), (0, 2)]) + [9, 9, 7] + """ # The prefix sum array dp = [0] * len(array) dp[0] = array[0] @@ -22,4 +89,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 ValueError("Capacitance cannot be 0 or negative") else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance)))), ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 as an electrical resonator, an electrical analogue of a +tuning fork, storing energy oscillating at the circuit's resonant frequency. +Source: https://en.wikipedia.org/wiki/LC_circuit +""" from __future__ import annotations @@ -7,6 +14,22 @@ def resonant_frequency(inductance: float, capacitance: float) -> tuple: + """ + This function can calculate the resonant frequency of LC circuit, + for the given value of inductance and capacitnace. + + Examples are given below: + >>> resonant_frequency(inductance=10, capacitance=5) + ('Resonant frequency', 0.022507907903927652) + >>> resonant_frequency(inductance=0, capacitance=5) + Traceback (most recent call last): + ... + ValueError: Inductance cannot be 0 or negative + >>> resonant_frequency(inductance=10, capacitance=0) + Traceback (most recent call last): + ... + ValueError: Capacitance cannot be 0 or negative + """ if inductance <= 0: raise ValueError("Inductance cannot be 0 or negative") @@ -24,4 +47,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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(n)] # we want minimum cost of multiplication of matrices # of dimension (i*k) and (k*j). This cost is arr[i-1]*arr[k]*arr[j]. for i in range(n - 1, 0, -1): for j in range(i, n): if i == j: dp[i][j] = 0 continue for k in range(i, j): dp[i][j] = min( dp[i][j], dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j] ) return dp[1][n - 1] def matrix_chain_order(dims: list[int]) -> int: @cache def a(i: int, j: int) -> int: return min( (a(i, k) + dims[i] * dims[k] * dims[j] + a(k, j) for k in range(i + 1, j)), default=0, ) return a(0, len(dims) - 1) @contextmanager def elapsed_time(msg: str) -> Iterator: # print(f"Starting: {msg}") from time import perf_counter_ns start = perf_counter_ns() yield print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10**9} seconds.") if __name__ == "__main__": import doctest doctest.testmod() with elapsed_time("matrix_chain_order"): print(f"{matrix_chain_order(list(range(1, 251))) = }") with elapsed_time("matrix_chain_multiply"): print(f"{matrix_chain_multiply(list(range(1, 251))) = }") with elapsed_time("matrix_chain_order"): print(f"{matrix_chain_order(list(range(1, 251))) = }") with elapsed_time("matrix_chain_multiply"): print(f"{matrix_chain_multiply(list(range(1, 251))) = }")
--- +++ @@ -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 are composed of matrix. + 2. Solve complex polynomial equations in the field of algebra using least processing + power. + 3. Calculate overall impact of macroeconomic decisions as economic equations involve a + number of variables. + 4. Self-driving car navigation can be made more accurate as matrix multiplication can + accurately determine position and orientation of obstacles in short time. + +Python doctests can be run with the following command:: + + python -m doctest -v matrix_chain_multiply.py + +Given a sequence ``arr[]`` that represents chain of 2D matrices such that the dimension +of the ``i`` th matrix is ``arr[i-1]*arr[i]``. +So suppose ``arr = [40, 20, 30, 10, 30]`` means we have ``4`` matrices of dimensions +``40*20``, ``20*30``, ``30*10`` and ``10*30``. + +``matrix_chain_multiply()`` returns an integer denoting minimum number of +multiplications to multiply the chain. + +We do not need to perform actual multiplication here. +We only need to decide the order in which to perform the multiplication. + +Hints: + 1. Number of multiplications (ie cost) to multiply ``2`` matrices + of size ``m*p`` and ``p*n`` is ``m*p*n``. + 2. Cost of matrix multiplication is not associative ie ``(M1*M2)*M3 != M1*(M2*M3)`` + 3. Matrix multiplication is not commutative. So, ``M1*M2`` does not mean ``M2*M1`` + can be done. + 4. To determine the required order, we can try different combinations. + +So, this problem has overlapping sub-problems and can be solved using recursion. +We use Dynamic Programming for optimal time complexity. + +Example input: + ``arr = [40, 20, 30, 10, 30]`` +output: + ``26000`` +""" from collections.abc import Iterator from contextlib import contextmanager @@ -6,6 +52,30 @@ def matrix_chain_multiply(arr: list[int]) -> int: + """ + Find the minimum number of multiplcations required to multiply the chain of matrices + + Args: + `arr`: The input array of integers. + + Returns: + Minimum number of multiplications needed to multiply the chain + + Examples: + + >>> matrix_chain_multiply([1, 2, 3, 4, 3]) + 30 + >>> matrix_chain_multiply([10]) + 0 + >>> matrix_chain_multiply([10, 20]) + 0 + >>> matrix_chain_multiply([19, 2, 19]) + 722 + >>> matrix_chain_multiply(list(range(1, 100))) + 323398 + >>> # matrix_chain_multiply(list(range(1, 251))) + # 2626798 + """ if len(arr) < 2: return 0 # initialising 2D dp matrix @@ -27,6 +97,25 @@ def matrix_chain_order(dims: list[int]) -> int: + """ + Source: https://en.wikipedia.org/wiki/Matrix_chain_multiplication + + The dynamic programming solution is faster than cached the recursive solution and + can handle larger inputs. + + >>> matrix_chain_order([1, 2, 3, 4, 3]) + 30 + >>> matrix_chain_order([10]) + 0 + >>> matrix_chain_order([10, 20]) + 0 + >>> matrix_chain_order([19, 2, 19]) + 722 + >>> matrix_chain_order(list(range(1, 100))) + 323398 + >>> # matrix_chain_order(list(range(1, 251))) # Max before RecursionError is raised + # 2626798 + """ @cache def a(i: int, j: int) -> int: @@ -59,4 +148,4 @@ with elapsed_time("matrix_chain_order"): print(f"{matrix_chain_order(list(range(1, 251))) = }") with elapsed_time("matrix_chain_multiply"): - print(f"{matrix_chain_multiply(list(range(1, 251))) = }")+ print(f"{matrix_chain_multiply(list(range(1, 251))) = }")
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): dp[i][j] = dp[i - 1][j] if numbers[i - 1] <= j: dp[i][j] = dp[i][j] or dp[i - 1][j - numbers[i - 1]] for j in range(int(s / 2), -1, -1): if dp[n][j] is True: diff = s - 2 * j break return diff if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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]) + 3 + >>> find_min([]) + 0 + >>> find_min([1, 2, 3, 4]) + 0 + >>> find_min([0, 0, 0, 0]) + 0 + >>> find_min([-1, -5, 5, 1]) + 0 + >>> find_min([-1, -5, 5, 1]) + 0 + >>> find_min([9, 9, 9, 9, 9]) + 9 + >>> find_min([1, 5, 10, 3]) + 1 + >>> find_min([-1, 0, 1]) + 0 + >>> find_min(range(10, 0, -1)) + 1 + >>> find_min([-1]) + Traceback (most recent call last): + -- + IndexError: list assignment index out of range + >>> find_min([0, 0, 0, 1, 2, -4]) + Traceback (most recent call last): + ... + IndexError: list assignment index out of range + >>> find_min([-1, -5, -10, -3]) + Traceback (most recent call last): + ... + IndexError: list assignment index out of range + """ n = len(numbers) s = sum(numbers) @@ -30,4 +73,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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] == "*": return recursive_match(text[:-1], pattern) or recursive_match( text, pattern[:-2] ) return False def dp_match(text: str, pattern: str) -> bool: m = len(text) n = len(pattern) dp = [[False for _ in range(n + 1)] for _ in range(m + 1)] dp[0][0] = True for j in range(1, n + 1): dp[0][j] = pattern[j - 1] == "*" and dp[0][j - 2] for i in range(1, m + 1): for j in range(1, n + 1): if pattern[j - 1] in {".", text[i - 1]}: dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": dp[i][j] = dp[i][j - 2] if pattern[j - 2] in {".", text[i - 1]}: dp[i][j] |= dp[i - 1][j] else: dp[i][j] = False return dp[m][n] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 recursive_match(text: str, pattern: str) -> bool: + r""" + Recursive matching algorithm. + + | Time complexity: O(2^(\|text\| + \|pattern\|)) + | Space complexity: Recursion depth is O(\|text\| + \|pattern\|). + + :param text: Text to match. + :param pattern: Pattern to match. + :return: ``True`` if `text` matches `pattern`, ``False`` otherwise. + + >>> recursive_match('abc', 'a.c') + True + >>> recursive_match('abc', 'af*.c') + True + >>> recursive_match('abc', 'a.c*') + True + >>> recursive_match('abc', 'a.c*d') + False + >>> recursive_match('aa', '.*') + True + """ if not pattern: return not text @@ -19,6 +50,27 @@ def dp_match(text: str, pattern: str) -> bool: + r""" + Dynamic programming matching algorithm. + + | Time complexity: O(\|text\| * \|pattern\|) + | Space complexity: O(\|text\| * \|pattern\|) + + :param text: Text to match. + :param pattern: Pattern to match. + :return: ``True`` if `text` matches `pattern`, ``False`` otherwise. + + >>> dp_match('abc', 'a.c') + True + >>> dp_match('abc', 'af*.c') + True + >>> dp_match('abc', 'a.c*') + True + >>> dp_match('abc', 'a.c*d') + False + >>> dp_match('aa', '.*') + True + """ m = len(text) n = len(pattern) dp = [[False for _ in range(n + 1)] for _ in range(m + 1)] @@ -44,4 +96,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 frequency # of the node is defined as how many time the node is being searched. # The search cost of binary search tree is given by this formula: # # cost(1, n) = sum{i = 1 to n}((depth(node_i) + 1) * node_i_freq) # # where n is number of nodes in the BST. The characteristic of low-cost # BSTs is having a faster overall search time than other implementations. # The reason for their fast search time is that the nodes with high # frequencies will be placed near the root of the tree while the nodes # with low frequencies will be placed near the leaves of the tree thus # reducing search time in the most frequent instances. import sys from random import randint class Node: def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): return f"Node(key={self.key}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: # root does not have a parent print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False) def find_optimal_binary_search_tree(nodes): # Tree nodes must be sorted first, the code below sorts the keys in # increasing order and rearrange its frequencies accordingly. nodes.sort(key=lambda node: node.key) n = len(nodes) keys = [nodes[i].key for i in range(n)] freqs = [nodes[i].freq for i in range(n)] # This 2D array stores the overall tree cost (which's as minimized as possible); # for a single key, cost is equal to frequency of the key. dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes # array total = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # stores tree roots that will be used later for constructing binary search tree root = [[i if i == j else 0 for j in range(n)] for i in range(n)] for interval_length in range(2, n + 1): for i in range(n - interval_length + 1): j = i + interval_length - 1 dp[i][j] = sys.maxsize # set the value to "infinity" total[i][j] = total[i][j - 1] + freqs[j] # Apply Knuth's optimization # Loop without optimization: for r in range(i, j + 1): for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree cost = left + total[i][j] + right if dp[i][j] > cost: dp[i][j] = cost root[i][j] = r print("Binary search tree nodes:") for node in nodes: print(node) print(f"\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.") print_binary_search_tree(root, keys, 0, n - 1, -1, False) def main(): # A sample binary search tree nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) if __name__ == "__main__": main()
--- +++ @@ -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}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): + """ + Recursive function to print a BST from a root table. + + >>> key = [3, 8, 9, 10, 17, 21] + >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \ + [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]] + >>> print_binary_search_tree(root, key, 0, 5, -1, False) + 8 is the root of the binary search tree. + 3 is the left child of key 8. + 10 is the right child of key 8. + 9 is the left child of key 10. + 21 is the right child of key 10. + 17 is the left child of key 21. + """ if i > j or i < 0 or j > len(root) - 1: return @@ -47,6 +66,30 @@ def find_optimal_binary_search_tree(nodes): + """ + This function calculates and prints the optimal binary search tree. + The dynamic programming algorithm below runs in O(n^2) time. + Implemented from CLRS (Introduction to Algorithms) book. + https://en.wikipedia.org/wiki/Introduction_to_Algorithms + + >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), \ + Node(42, 3), Node(25, 40), Node(37, 30)]) + Binary search tree nodes: + Node(key=10, freq=34) + Node(key=12, freq=8) + Node(key=20, freq=50) + Node(key=25, freq=40) + Node(key=37, freq=30) + Node(key=42, freq=3) + <BLANKLINE> + The cost of optimal BST for given tree nodes is 324. + 20 is the root of the binary search tree. + 10 is the left child of key 20. + 12 is the right child of key 10. + 25 is the right child of key 20. + 37 is the right child of key 25. + 42 is the right child of key 37. + """ # Tree nodes must be sorted first, the code below sorts the keys in # increasing order and rearrange its frequencies accordingly. nodes.sort(key=lambda node: node.key) @@ -98,4 +141,4 @@ if __name__ == "__main__": - main()+ main()
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 range(1, number): table[i + 1] = min(table[i + 1], table[i] + 1) # check if out of bounds if i * 2 <= number: table[i * 2] = min(table[i * 2], table[i] + 1) # check if out of bounds if i * 3 <= number: table[i * 3] = min(table[i * 3], table[i] + 1) return table[number] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 -> 1 +Result: 3 steps + +Example 2: n = 15 +15 -> 5 -> 4 -> 2 -> 1 +Result: 4 steps + +Example 3: n = 6 +6 -> 2 -> 1 +Result: 2 step +""" from __future__ import annotations @@ -5,6 +28,18 @@ def min_steps_to_one(number: int) -> int: + """ + Minimum steps to 1 implemented using tabulation. + >>> min_steps_to_one(10) + 3 + >>> min_steps_to_one(15) + 4 + >>> min_steps_to_one(6) + 2 + + :param number: + :return int: + """ if number <= 0: msg = f"n must be greater than 0. Got n = {number}" @@ -28,4 +63,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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): left_max[i] = max(height, left_max[i - 1]) right_max = [0] * length right_max[-1] = heights[-1] for i in range(length - 2, -1, -1): right_max[i] = max(heights[i], right_max[i + 1]) return sum( min(left, right) - height for left, right, height in zip(left_max, right_max, heights) ) if __name__ == "__main__": import doctest doctest.testmod() print(f"{trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) = }") print(f"{trapped_rainwater((7, 1, 5, 3, 6, 4)) = }")
--- +++ @@ -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 "DYNAMIC PROGRAMMING". + +We calculate the maximum height of bars on the left and right of every bar in array. +Then iterate over the width of structure and at each index. +The amount of water that will be stored is equal to minimum of maximum height of bars +on both sides minus height of bar at current position. +""" def trapped_rainwater(heights: tuple[int, ...]) -> int: + """ + The trapped_rainwater function calculates the total amount of rainwater that can be + trapped given an array of bar heights. + It uses a dynamic programming approach, determining the maximum height of bars on + both sides for each bar, and then computing the trapped water above each bar. + The function returns the total trapped water. + + >>> trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) + 6 + >>> trapped_rainwater((7, 1, 5, 3, 6, 4)) + 9 + >>> trapped_rainwater((7, 1, 5, 3, 6, -1)) + Traceback (most recent call last): + ... + ValueError: No height can be negative + """ if not heights: return 0 if any(h < 0 for h in heights): @@ -28,4 +57,4 @@ doctest.testmod() print(f"{trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) = }") - print(f"{trapped_rainwater((7, 1, 5, 3, 6, 4)) = }")+ print(f"{trapped_rainwater((7, 1, 5, 3, 6, 4)) = }")
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) for cost in costs): raise ValueError("The parameter costs should be a list of three integers") if len(days) == 0: return 0 if min(days) <= 0: raise ValueError("All days elements should be greater than 0") if max(days) >= 366: raise ValueError("All days elements should be less than 366") days_set = set(days) @functools.cache def dynamic_programming(index: int) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1) return min( costs[0] + dynamic_programming(index + 1), costs[1] + dynamic_programming(index + 7), costs[2] + dynamic_programming(index + 30), ) return dynamic_programming(1) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 in the given list of days. + +Implementation notes: +implementation Dynamic Programming up bottom approach. + +Runtime complexity: O(n) + +The implementation was tested on the +leetcode: https://leetcode.com/problems/minimum-cost-for-tickets/ + + +Minimum Cost For Tickets +Dynamic Programming: up -> down. +""" import functools def mincost_tickets(days: list[int], costs: list[int]) -> int: + """ + >>> mincost_tickets([1, 4, 6, 7, 8, 20], [2, 7, 15]) + 11 + + >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 7, 15]) + 17 + + >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150]) + 24 + + >>> mincost_tickets([2], [2, 90, 150]) + 2 + + >>> mincost_tickets([], [2, 90, 150]) + 0 + + >>> mincost_tickets('hello', [2, 90, 150]) + Traceback (most recent call last): + ... + ValueError: The parameter days should be a list of integers + + >>> mincost_tickets([], 'world') + Traceback (most recent call last): + ... + ValueError: The parameter costs should be a list of three integers + + >>> mincost_tickets([0.25, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150]) + Traceback (most recent call last): + ... + ValueError: The parameter days should be a list of integers + + >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 0.9, 150]) + Traceback (most recent call last): + ... + ValueError: The parameter costs should be a list of three integers + + >>> mincost_tickets([-1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150]) + Traceback (most recent call last): + ... + ValueError: All days elements should be greater than 0 + + >>> mincost_tickets([2, 367], [2, 90, 150]) + Traceback (most recent call last): + ... + ValueError: All days elements should be less than 366 + + >>> mincost_tickets([2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], []) + Traceback (most recent call last): + ... + ValueError: The parameter costs should be a list of three integers + + >>> mincost_tickets([], []) + Traceback (most recent call last): + ... + ValueError: The parameter costs should be a list of three integers + + >>> mincost_tickets([2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [1, 2, 3, 4]) + Traceback (most recent call last): + ... + ValueError: The parameter costs should be a list of three integers + """ # Validation if not isinstance(days, list) or not all(isinstance(day, int) for day in days): @@ -42,4 +126,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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_down_cut_rod(n: int, prices: list): _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max( max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev), ) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): if n < 0: msg = f"n must be greater than or equal to 0. Got n = {n}" raise ValueError(msg) if n > len(prices): msg = ( "Each integral piece of rod must have a corresponding price. " f"Got n = {n} but length of prices = {len(prices)}" ) raise ValueError(msg) def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
--- +++ @@ -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 revenue +obtainable from a rod of length ``n`` given a list of prices for each integral piece +of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the +pieces separately or not cutting it at all if the price of it is the maximum obtainable. + +""" def naive_cut_rod_recursive(n: int, prices: list): + """ + Solves the rod-cutting problem via naively without using the benefit of dynamic + programming. The results is the same sub-problems are solved several times + leading to an exponential runtime + + Runtime: O(2^n) + + Arguments + --------- + + * `n`: int, the length of the rod + * `prices`: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` + + Returns + ------- + + The maximum revenue obtainable for a rod of length `n` given the list of prices + for each piece. + + Examples + -------- + + >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) + 10 + >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) + 30 + """ _enforce_args(n, prices) if n == 0: @@ -15,12 +54,65 @@ def top_down_cut_rod(n: int, prices: list): + """ + Constructs a top-down dynamic programming solution for the rod-cutting + problem via memoization. This function serves as a wrapper for + ``_top_down_cut_rod_recursive`` + + Runtime: O(n^2) + + Arguments + --------- + + * `n`: int, the length of the rod + * `prices`: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` + + .. note:: + For convenience and because Python's lists using ``0``-indexing, ``length(max_rev) + = n + 1``, to accommodate for the revenue obtainable from a rod of length ``0``. + + Returns + ------- + + The maximum revenue obtainable for a rod of length `n` given the list of prices + for each piece. + + Examples + -------- + + >>> top_down_cut_rod(4, [1, 5, 8, 9]) + 10 + >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) + 30 + """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): + """ + Constructs a top-down dynamic programming solution for the rod-cutting problem + via memoization. + + Runtime: O(n^2) + + Arguments + --------- + + * `n`: int, the length of the rod + * `prices`: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` + * `max_rev`: list, the computed maximum revenue for a piece of rod. + ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` + + Returns + ------- + + The maximum revenue obtainable for a rod of length `n` given the list of prices + for each piece. + """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: @@ -39,6 +131,32 @@ def bottom_up_cut_rod(n: int, prices: list): + """ + Constructs a bottom-up dynamic programming solution for the rod-cutting problem + + Runtime: O(n^2) + + Arguments + --------- + + * `n`: int, the maximum length of the rod. + * `prices`: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` + + Returns + ------- + + The maximum revenue obtainable from cutting a rod of length `n` given + the prices for each piece of rod p. + + Examples + -------- + + >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) + 10 + >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) + 30 + """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of @@ -57,6 +175,16 @@ def _enforce_args(n: int, prices: list): + """ + Basic checks on the arguments to the rod-cutting algorithms + + * `n`: int, the length of the rod + * `prices`: list, the price list for each piece of rod. + + Throws ``ValueError``: + if `n` is negative or there are fewer items in the price list than the length of + the rod + """ if n < 0: msg = f"n must be greater than or equal to 0. Got n = {n}" raise ValueError(msg) @@ -87,4 +215,4 @@ if __name__ == "__main__": - main()+ main()
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 range(1, n): for prev in range(i): # If array[prev] is less than or equal to array[i], then # longest_increasing_subsequence[prev] + array[i] # is a valid increasing subsequence # longest_increasing_subsequence[i] is only set to # longest_increasing_subsequence[prev] + array[i] if the length is longer. if array[prev] <= array[i] and len( longest_increasing_subsequence[prev] ) + 1 > len(longest_increasing_subsequence[i]): longest_increasing_subsequence[i] = copy.copy( longest_increasing_subsequence[prev] ) longest_increasing_subsequence[i].append(array[i]) result: list[int] = [] for i in range(n): if len(longest_increasing_subsequence[i]) > len(result): result = longest_increasing_subsequence[i] return result if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 array and + return it. + +Example: + ``[10, 22, 9, 33, 21, 50, 41, 60, 80]`` as input will return + ``[10, 22, 33, 50, 60, 80]`` as output +""" from __future__ import annotations @@ -5,6 +19,22 @@ def longest_subsequence(array: list[int]) -> list[int]: + """ + Some examples + + >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) + [10, 22, 33, 50, 60, 80] + >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) + [1, 2, 3, 9] + >>> longest_subsequence([9, 8, 7, 6, 5, 7]) + [7, 7] + >>> longest_subsequence([28, 26, 12, 23, 35, 39]) + [12, 23, 35, 39] + >>> longest_subsequence([1, 1, 1]) + [1, 1, 1] + >>> longest_subsequence([]) + [] + """ n = len(array) # The longest increasing subsequence ending at array[i] longest_increasing_subsequence = [] @@ -39,4 +69,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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_power(digit: int, power: int) -> int: if (power, digit) not in power_cache: power_cache[(power, digit)] = digit**power return power_cache[(power, digit)] # Check each number up to the limit for number in range(limit): # Count digits num_digits = len(str(number)) # Calculate sum of powered digits using memoized powers remaining = number digit_sum = 0 while remaining > 0: digit = remaining % 10 digit_sum += get_digit_power(digit, num_digits) remaining //= 10 # Check if narcissistic if digit_sum == number: narcissistic_nums.append(number) return narcissistic_nums if __name__ == "__main__": import doctest doctest.testmod() # Demonstrate the dynamic programming approach print("Finding all narcissistic numbers up to 10000:") print("(Using memoization to cache digit power calculations)") print() narcissistic_numbers = find_narcissistic_numbers(10000) print(f"Found {len(narcissistic_numbers)} narcissistic numbers:") print(narcissistic_numbers)
--- +++ @@ -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 narcissistic number because 153 = 1^3 + 5^3 + 3^3. + +This implementation uses dynamic programming with memoization to efficiently +compute digit powers and find all narcissistic numbers up to a specified limit. + +The DP optimization caches digit^power calculations. When searching through many +numbers, the same digit power calculations occur repeatedly (e.g., 153, 351, 135 +all need 1^3, 5^3, 3^3). Memoization avoids these redundant calculations. + +Examples of narcissistic numbers: + Single digit: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + Three digit: 153, 370, 371, 407 + Four digit: 1634, 8208, 9474 + Five digit: 54748, 92727, 93084 + +Reference: https://en.wikipedia.org/wiki/Narcissistic_number +""" def find_narcissistic_numbers(limit: int) -> list[int]: + """ + Find all narcissistic numbers up to the given limit using dynamic programming. + + This function uses memoization to cache digit power calculations, avoiding + redundant computations across different numbers with the same digit count. + + Args: + limit: The upper bound for searching narcissistic numbers (exclusive) + + Returns: + list[int]: A sorted list of all narcissistic numbers below the limit + + Examples: + >>> find_narcissistic_numbers(10) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> find_narcissistic_numbers(160) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153] + >>> find_narcissistic_numbers(400) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371] + >>> find_narcissistic_numbers(1000) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407] + >>> find_narcissistic_numbers(10000) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474] + >>> find_narcissistic_numbers(1) + [0] + >>> find_narcissistic_numbers(0) + [] + """ if limit <= 0: return [] @@ -11,6 +63,7 @@ power_cache: dict[tuple[int, int], int] = {} def get_digit_power(digit: int, power: int) -> int: + """Get digit^power using memoization (DP optimization).""" if (power, digit) not in power_cache: power_cache[(power, digit)] = digit**power return power_cache[(power, digit)] @@ -47,4 +100,4 @@ narcissistic_numbers = find_narcissistic_numbers(10000) print(f"Found {len(narcissistic_numbers)} narcissistic numbers:") - print(narcissistic_numbers)+ print(narcissistic_numbers)
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 in farads. time_sec: float, # time in seconds after charging initiation of capacitor. ) -> float: if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if capacitance <= 0: raise ValueError("Capacitance must be positive.") return round(source_voltage * (1 - exp(-time_sec / (resistance * capacitance))), 3) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 with in series to +a capacitor then the capacitor charges slowly means it will take more time than usual. +while the capacitor is being charged, the voltage is in exponential function with time. + +'resistance(ohms) * capacitance(farads)' is called RC-timeconstant which may also be +represented as τ (tau). By using this RC-timeconstant we can find the voltage at any +time 't' from the initiation of charging a capacitor with the help of the exponential +function containing RC. Both at charging and discharging of a capacitor. +""" from math import exp # value of exp = 2.718281828459… @@ -11,6 +24,38 @@ capacitance: float, # capacitance in farads. time_sec: float, # time in seconds after charging initiation of capacitor. ) -> float: + """ + Find capacitor voltage at any nth second after initiating its charging. + + Examples + -------- + >>> charging_capacitor(source_voltage=.2,resistance=.9,capacitance=8.4,time_sec=.5) + 0.013 + + >>> charging_capacitor(source_voltage=2.2,resistance=3.5,capacitance=2.4,time_sec=9) + 1.446 + + >>> charging_capacitor(source_voltage=15,resistance=200,capacitance=20,time_sec=2) + 0.007 + + >>> charging_capacitor(20, 2000, 30*pow(10,-5), 4) + 19.975 + + >>> charging_capacitor(source_voltage=0,resistance=10.0,capacitance=.30,time_sec=3) + Traceback (most recent call last): + ... + ValueError: Source voltage must be positive. + + >>> charging_capacitor(source_voltage=20,resistance=-2000,capacitance=30,time_sec=4) + Traceback (most recent call last): + ... + ValueError: Resistance must be positive. + + >>> charging_capacitor(source_voltage=30,resistance=1500,capacitance=0,time_sec=4) + Traceback (most recent call last): + ... + ValueError: Capacitance must be positive. + """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") @@ -24,4 +69,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 len(item) > 0 for item in words ): raise ValueError("the words should be a list of non-empty strings") # Build trie trie: dict[str, Any] = {} word_keeper_key = "WORD_KEEPER" for word in words: trie_node = trie for c in word: if c not in trie_node: trie_node[c] = {} trie_node = trie_node[c] trie_node[word_keeper_key] = True len_string = len(string) # Dynamic programming method @functools.cache def is_breakable(index: int) -> bool: if index == len_string: return True trie_node: Any = trie for i in range(index, len_string): trie_node = trie_node.get(string[i], None) if trie_node is None: return False if trie_node.get(word_keeper_key, False) and is_breakable(i + 1): return True return False return is_breakable(0) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. + +Implementation notes: Trie + Dynamic programming up -> down. +The Trie will be used to store the words. It will be useful for scanning +available words for the current position in the string. + +Leetcode: +https://leetcode.com/problems/word-break/description/ + +Runtime: O(n * n) +Space: O(n) +""" import functools from typing import Any def word_break(string: str, words: list[str]) -> bool: + """ + Return True if numbers have opposite signs False otherwise. + + >>> word_break("applepenapple", ["apple","pen"]) + True + >>> word_break("catsandog", ["cats","dog","sand","and","cat"]) + False + >>> word_break("cars", ["car","ca","rs"]) + True + >>> word_break('abc', []) + False + >>> word_break(123, ['a']) + Traceback (most recent call last): + ... + ValueError: the string should be not empty string + >>> word_break('', ['a']) + Traceback (most recent call last): + ... + ValueError: the string should be not empty string + >>> word_break('abc', [123]) + Traceback (most recent call last): + ... + ValueError: the words should be a list of non-empty strings + >>> word_break('abc', ['']) + Traceback (most recent call last): + ... + ValueError: the words should be a list of non-empty strings + """ # Validation if not isinstance(string, str) or len(string) == 0: @@ -33,6 +82,11 @@ # Dynamic programming method @functools.cache def is_breakable(index: int) -> bool: + """ + >>> string = 'a' + >>> is_breakable(1) + True + """ if index == len_string: return True @@ -54,4 +108,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 else num, curr_sum + num) max_sum = max(max_sum, curr_sum) return max_sum if __name__ == "__main__": from doctest import testmod testmod() nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"{max_subarray_sum(nums) = }")
--- +++ @@ -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 maximum subarray sum is 6. + +Kadane's algorithm is a simple dynamic programming algorithm that solves the maximum +subarray sum problem in O(n) time and O(1) space. + +Reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem +""" from collections.abc import Sequence @@ -5,6 +16,30 @@ def max_subarray_sum( arr: Sequence[float], allow_empty_subarrays: bool = False ) -> float: + """ + Solves the maximum subarray sum problem using Kadane's algorithm. + :param arr: the given array of numbers + :param allow_empty_subarrays: if True, then the algorithm considers empty subarrays + + >>> max_subarray_sum([2, 8, 9]) + 19 + >>> max_subarray_sum([0, 0]) + 0 + >>> max_subarray_sum([-1.0, 0.0, 1.0]) + 1.0 + >>> max_subarray_sum([1, 2, 3, 4, -2]) + 10 + >>> max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) + 6 + >>> max_subarray_sum([2, 3, -9, 8, -2]) + 8 + >>> max_subarray_sum([-2, -3, -1, -4, -6]) + -1 + >>> max_subarray_sum([-2, -3, -1, -4, -6], allow_empty_subarrays=True) + 0 + >>> max_subarray_sum([]) + 0 + """ if not arr: return 0 @@ -23,4 +58,4 @@ testmod() nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] - print(f"{max_subarray_sum(nums) = }")+ print(f"{max_subarray_sum(nums) = }")
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]: length_first_signal = len(self.first_signal) length_second_signal = len(self.second_signal) max_length = max(length_first_signal, length_second_signal) # create a zero matrix of max_length x max_length matrix = [[0] * max_length for i in range(max_length)] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) """ Fills the matrix in the following way assuming 'x' is the signal of length 4 [ [x[0], x[3], x[2], x[1]], [x[1], x[0], x[3], x[2]], [x[2], x[1], x[0], x[3]], [x[3], x[2], x[1], x[0]] ] """ for i in range(max_length): rotated_signal = deque(self.second_signal) rotated_signal.rotate(i) for j, item in enumerate(rotated_signal): matrix[i][j] += item # multiply the matrix with the first signal final_signal = np.matmul(np.transpose(matrix), np.transpose(self.first_signal)) # rounding-off to two decimal places return [float(round(i, 2)) for i in final_signal] if __name__ == "__main__": doctest.testmod()
--- +++ @@ -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 context of the discrete-time Fourier transform (DTFT). +In particular, the DTFT of the product of two discrete sequences is the periodic +convolution of the DTFTs of the individual sequences. And each DTFT is a periodic +summation of a continuous Fourier transform function. + +Source: https://en.wikipedia.org/wiki/Circular_convolution +""" import doctest from collections import deque @@ -8,13 +19,44 @@ class CircularConvolution: + """ + This class stores the first and second signal and performs the circular convolution + """ def __init__(self) -> None: + """ + First signal and second signal are stored as 1-D array + """ self.first_signal = [2, 1, 2, -1] self.second_signal = [1, 2, 3, 4] def circular_convolution(self) -> list[float]: + """ + This function performs the circular convolution of the first and second signal + using matrix method + + Usage: + >>> convolution = CircularConvolution() + >>> convolution.circular_convolution() + [10.0, 10.0, 6.0, 14.0] + + >>> convolution.first_signal = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6] + >>> convolution.second_signal = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5] + >>> convolution.circular_convolution() + [5.2, 6.0, 6.48, 6.64, 6.48, 6.0, 5.2, 4.08] + + >>> convolution.first_signal = [-1, 1, 2, -2] + >>> convolution.second_signal = [0.5, 1, -1, 2, 0.75] + >>> convolution.circular_convolution() + [6.25, -3.0, 1.5, -2.0, -2.75] + + >>> convolution.first_signal = [1, -1, 2, 3, -1] + >>> convolution.second_signal = [1, 2, 3] + >>> convolution.circular_convolution() + [8.0, -2.0, 3.0, 4.0, 11.0] + + """ length_first_signal = len(self.first_signal) length_second_signal = len(self.second_signal) @@ -53,4 +95,4 @@ if __name__ == "__main__": - doctest.testmod()+ doctest.testmod()
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 * power_factor def reactive_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 * math.sqrt(1 - power_factor**2) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 + """ if ( not isinstance(power_factor, (int, float)) or power_factor < -1 @@ -12,6 +23,17 @@ def reactive_power(apparent_power: float, power_factor: float) -> float: + """ + Calculate reactive power from apparent power and power factor. + + Examples: + >>> reactive_power(100, 0.9) + 43.58898943540673 + >>> reactive_power(0, 0.8) + 0.0 + >>> reactive_power(100, -0.9) + 43.58898943540673 + """ if ( not isinstance(power_factor, (int, float)) or power_factor < -1 @@ -24,4 +46,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: float, # inductance should be in henrys. time: float, # time should in seconds. ) -> float: if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if inductance <= 0: raise ValueError("Inductance must be positive.") return round( source_voltage / resistance * (1 - exp((-time * resistance) / inductance)), 3 ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 inductor is connected to 'DC' current source nothing happens it just works like a +wire because it's real effect cannot be seen while 'DC' is connected, its not even +going to store energy. Inductor stores energy only when it is working on 'AC' current. + +Connecting a inductor in series with a resistor(when R = 0) to a 'AC' potential source, +from zero to a finite value causes a sudden voltage to induced in inductor which +opposes the current. which results in initially slowly current rise. However it would +cease if there is no further changes in current. With resistance zero current will never +stop rising. + +'Resistance(ohms) / Inductance(henrys)' is known as RL-timeconstant. It also represents +as τ (tau). While the charging of a inductor with a resistor results in +a exponential function. + +when inductor is connected across 'AC' potential source. It starts to store the energy +in its 'magnetic field'.with the help 'RL-time-constant' we can find current at any time +in inductor while it is charging. +""" from math import exp # value of exp = 2.718281828459… @@ -11,6 +35,50 @@ inductance: float, # inductance should be in henrys. time: float, # time should in seconds. ) -> float: + """ + Find inductor current at any nth second after initiating its charging. + + Examples + -------- + >>> charging_inductor(source_voltage=5.8,resistance=1.5,inductance=2.3,time=2) + 2.817 + + >>> charging_inductor(source_voltage=8,resistance=5,inductance=3,time=2) + 1.543 + + >>> charging_inductor(source_voltage=8,resistance=5*pow(10,2),inductance=3,time=2) + 0.016 + + >>> charging_inductor(source_voltage=-8,resistance=100,inductance=15,time=12) + Traceback (most recent call last): + ... + ValueError: Source voltage must be positive. + + >>> charging_inductor(source_voltage=80,resistance=-15,inductance=100,time=5) + Traceback (most recent call last): + ... + ValueError: Resistance must be positive. + + >>> charging_inductor(source_voltage=12,resistance=200,inductance=-20,time=5) + Traceback (most recent call last): + ... + ValueError: Inductance must be positive. + + >>> charging_inductor(source_voltage=0,resistance=200,inductance=20,time=5) + Traceback (most recent call last): + ... + ValueError: Source voltage must be positive. + + >>> charging_inductor(source_voltage=10,resistance=0,inductance=20,time=5) + Traceback (most recent call last): + ... + ValueError: Resistance must be positive. + + >>> charging_inductor(source_voltage=15, resistance=25, inductance=0, time=5) + Traceback (most recent call last): + ... + ValueError: Inductance must be positive. + """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") @@ -26,4 +94,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: ------------------------------------- | Freq = 1.44 /[( R1+ 2 x R2) x C1] | ... in Hz ------------------------------------- where Freq is the frequency, R1 is the first resistance in ohms, R2 is the second resistance in ohms, C1 is the capacitance in Microfarads. ------------------------------------------------ | Duty Cycle = (R1 + R2) / (R1 + 2 x R2) x 100 | ... in % ------------------------------------------------ where R1 is the first resistance in ohms, R2 is the second resistance in ohms. """ def astable_frequency( resistance_1: float, resistance_2: float, capacitance: float ) -> float: if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0: raise ValueError("All values must be positive") return (1.44 / ((resistance_1 + 2 * resistance_2) * capacitance)) * 10**6 def astable_duty_cycle(resistance_1: float, resistance_2: float) -> float: if resistance_1 <= 0 or resistance_2 <= 0: raise ValueError("All values must be positive") return (resistance_1 + resistance_2) / (resistance_1 + 2 * resistance_2) * 100 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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, capacitance=976) + 1.7905459175553078 + >>> astable_frequency(resistance_1=2, resistance_2=-1, capacitance=2) + Traceback (most recent call last): + ... + ValueError: All values must be positive + >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=0) + Traceback (most recent call last): + ... + ValueError: All values must be positive + """ if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0: raise ValueError("All values must be positive") @@ -33,6 +48,21 @@ def astable_duty_cycle(resistance_1: float, resistance_2: float) -> float: + """ + Usage examples: + >>> astable_duty_cycle(resistance_1=45, resistance_2=45) + 66.66666666666666 + >>> astable_duty_cycle(resistance_1=356, resistance_2=234) + 71.60194174757282 + >>> astable_duty_cycle(resistance_1=2, resistance_2=-1) + Traceback (most recent call last): + ... + ValueError: All values must be positive + >>> astable_duty_cycle(resistance_1=0, resistance_2=0) + Traceback (most recent call last): + ... + ValueError: All values must be positive + """ if resistance_1 <= 0 or resistance_2 <= 0: raise ValueError("All values must be positive") @@ -42,4 +72,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 resistance == 0: return {"resistance": sqrt(pow(impedance, 2) - pow(reactance, 2))} elif reactance == 0: return {"reactance": sqrt(pow(impedance, 2) - pow(resistance, 2))} elif impedance == 0: return {"impedance": sqrt(pow(resistance, 2) + pow(reactance, 2))} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 annotations @@ -7,6 +12,22 @@ def electrical_impedance( resistance: float, reactance: float, impedance: float ) -> dict[str, float]: + """ + Apply Electrical Impedance formula, on any two given electrical values, + which can be resistance, reactance, and impedance, and then in a Python dict + return name/value pair of the zero value. + + >>> electrical_impedance(3,4,0) + {'impedance': 5.0} + >>> electrical_impedance(0,4,5) + {'resistance': 3.0} + >>> electrical_impedance(3,0,5) + {'reactance': 4.0} + >>> electrical_impedance(3,4,5) + Traceback (most recent call last): + ... + ValueError: One and only one argument must be 0 + """ if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance == 0: @@ -22,4 +43,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def get_black_and_white_rgb(distance: float) -> tuple: if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def get_color_coded_rgb(distance: float) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1)) def get_image( image_width: int = 800, image_height: int = 600, figure_center_x: float = -0.6, figure_center_y: float = 0, figure_width: float = 3.2, max_step: int = 50, use_distance_color_coding: bool = True, ) -> Image.Image: img = Image.new("RGB", (image_width, image_height)) pixels = img.load() # loop through the image-coordinates for image_x in range(image_width): for image_y in range(image_height): # determine the figure-coordinates based on the image-coordinates figure_height = figure_width / image_width * image_height figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height distance = get_distance(figure_x, figure_y, max_step) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: pixels[image_x, image_y] = get_color_coded_rgb(distance) else: pixels[image_x, image_y] = get_black_and_white_rgb(distance) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure img = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
--- +++ @@ -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 for all complex number with an absolute value - # greater than 4 - if a * a + b * b > 4: - break - return step / (max_step - 1) - - -def get_black_and_white_rgb(distance: float) -> tuple: - if distance == 1: - return (0, 0, 0) - else: - return (255, 255, 255) - - -def get_color_coded_rgb(distance: float) -> tuple: - if distance == 1: - return (0, 0, 0) - else: - return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1)) - - -def get_image( - image_width: int = 800, - image_height: int = 600, - figure_center_x: float = -0.6, - figure_center_y: float = 0, - figure_width: float = 3.2, - max_step: int = 50, - use_distance_color_coding: bool = True, -) -> Image.Image: - img = Image.new("RGB", (image_width, image_height)) - pixels = img.load() - - # loop through the image-coordinates - for image_x in range(image_width): - for image_y in range(image_height): - # determine the figure-coordinates based on the image-coordinates - figure_height = figure_width / image_width * image_height - figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width - figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height - - distance = get_distance(figure_x, figure_y, max_step) - - # color the corresponding pixel based on the selected coloring-function - if use_distance_color_coding: - pixels[image_x, image_y] = get_color_coded_rgb(distance) - else: - pixels[image_x, image_y] = get_black_and_white_rgb(distance) - - return img - - -if __name__ == "__main__": - import doctest - - doctest.testmod() - - # colored version, full figure - img = get_image() - - # uncomment for colored version, different section, zoomed in - # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, - # figure_width = 0.8) - - # uncomment for black and white version, full figure - # img = get_image(use_distance_color_coding = False) - - # uncomment to save the image - # img.save("mandelbrot.png") - - img.show()+""" +The Mandelbrot set is the set of complex numbers "c" for which the series +"z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a +complex number "c" is a member of the Mandelbrot set if, when starting with +"z_0 = 0" and applying the iteration repeatedly, the absolute value of +"z_n" remains bounded for all "n > 0". Complex numbers can be written as +"a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i" +is the imaginary component, usually drawn on the y-axis. Most visualizations +of the Mandelbrot set use a color-coding to indicate after how many steps in +the series the numbers outside the set diverge. Images of the Mandelbrot set +exhibit an elaborate and infinitely complicated boundary that reveals +progressively ever-finer recursive detail at increasing magnifications, making +the boundary of the Mandelbrot set a fractal curve. +(description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set ) +(see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set ) +""" + +import colorsys + +from PIL import Image + + +def get_distance(x: float, y: float, max_step: int) -> float: + """ + Return the relative distance (= step/max_step) after which the complex number + constituted by this x-y-pair diverges. Members of the Mandelbrot set do not + diverge so their distance is 1. + + >>> get_distance(0, 0, 50) + 1.0 + >>> get_distance(0.5, 0.5, 50) + 0.061224489795918366 + >>> get_distance(2, 0, 50) + 0.0 + """ + 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 value + # greater than 4 + if a * a + b * b > 4: + break + return step / (max_step - 1) + + +def get_black_and_white_rgb(distance: float) -> tuple: + """ + Black&white color-coding that ignores the relative distance. The Mandelbrot + set is black, everything else is white. + + >>> get_black_and_white_rgb(0) + (255, 255, 255) + >>> get_black_and_white_rgb(0.5) + (255, 255, 255) + >>> get_black_and_white_rgb(1) + (0, 0, 0) + """ + if distance == 1: + return (0, 0, 0) + else: + return (255, 255, 255) + + +def get_color_coded_rgb(distance: float) -> tuple: + """ + Color-coding taking the relative distance into account. The Mandelbrot set + is black. + + >>> get_color_coded_rgb(0) + (255, 0, 0) + >>> get_color_coded_rgb(0.5) + (0, 255, 255) + >>> get_color_coded_rgb(1) + (0, 0, 0) + """ + if distance == 1: + return (0, 0, 0) + else: + return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1)) + + +def get_image( + image_width: int = 800, + image_height: int = 600, + figure_center_x: float = -0.6, + figure_center_y: float = 0, + figure_width: float = 3.2, + max_step: int = 50, + use_distance_color_coding: bool = True, +) -> Image.Image: + """ + Function to generate the image of the Mandelbrot set. Two types of coordinates + are used: image-coordinates that refer to the pixels and figure-coordinates + that refer to the complex numbers inside and outside the Mandelbrot set. The + figure-coordinates in the arguments of this function determine which section + of the Mandelbrot set is viewed. The main area of the Mandelbrot set is + roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates. + + Commenting out tests that slow down pytest... + # 13.35s call fractals/mandelbrot.py::mandelbrot.get_image + # >>> get_image().load()[0,0] + (255, 0, 0) + # >>> get_image(use_distance_color_coding = False).load()[0,0] + (255, 255, 255) + """ + img = Image.new("RGB", (image_width, image_height)) + pixels = img.load() + + # loop through the image-coordinates + for image_x in range(image_width): + for image_y in range(image_height): + # determine the figure-coordinates based on the image-coordinates + figure_height = figure_width / image_width * image_height + figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width + figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height + + distance = get_distance(figure_x, figure_y, max_step) + + # color the corresponding pixel based on the selected coloring-function + if use_distance_color_coding: + pixels[image_x, image_y] = get_color_coded_rgb(distance) + else: + pixels[image_x, image_y] = get_black_and_white_rgb(distance) + + return img + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + + # colored version, full figure + img = get_image() + + # uncomment for colored version, different section, zoomed in + # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, + # figure_width = 0.8) + + # uncomment for black and white version, full figure + # img = get_image(use_distance_color_coding = False) + + # uncomment to save the image + # img.save("mandelbrot.png") + + img.show()
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!" raise ValueError(msg) first_sum += 1 / float(resistor) return 1 / first_sum def resistor_series(resistors: list[float]) -> float: sum_r = 0.00 for index, resistor in enumerate(resistors): sum_r += resistor if resistor < 0: msg = f"Resistor at index {index} has a negative value!" raise ValueError(msg) return sum_r if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: Resistor at index 2 has a negative or zero value! + >>> resistor_parallel([3.21389, 2, 0.000]) + Traceback (most recent call last): + ... + ValueError: Resistor at index 2 has a negative or zero value! + """ first_sum = 0.00 for index, resistor in enumerate(resistors): @@ -15,6 +29,18 @@ def resistor_series(resistors: list[float]) -> float: + """ + Req = R1 + R2 + ... + Rn + + Calculate the equivalent resistance for any number of resistors in parallel. + + >>> resistor_series([3.21389, 2, 3]) + 8.21389 + >>> resistor_series([3.21389, 2, -3]) + Traceback (most recent call last): + ... + ValueError: Resistor at index 2 has a negative value! + """ sum_r = 0.00 for index, resistor in enumerate(resistors): sum_r += resistor @@ -27,4 +53,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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(90) turtle.fd(length / 3) turtle.left(90) turtle.end_fill() def draw_fractal_recursive(x: float, y: float, length: float, depth: float): if depth == 0: draw_cross(x, y, length) return draw_fractal_recursive(x, y, length / 3, depth - 1) draw_fractal_recursive(x + length / 3, y, length / 3, depth - 1) draw_fractal_recursive(x - length / 3, y, length / 3, depth - 1) draw_fractal_recursive(x, y + length / 3, length / 3, depth - 1) draw_fractal_recursive(x, y - length / 3, length / 3, depth - 1) def set_color(rgb: str): turtle.color(rgb) def draw_vicsek_fractal(x: float, y: float, length: float, depth: float, color="blue"): turtle.speed(0) turtle.hideturtle() set_color(color) draw_fractal_recursive(x, y, length, depth) turtle.Screen().update() def main(): draw_vicsek_fractal(0, 0, 800, 4) turtle.done() if __name__ == "__main__": main()
--- +++ @@ -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 pattern. +The algorithm involves dividing a square into 9 equal smaller squares, +removing the center square, and then repeating this process on the remaining 8 squares. +This results in a pattern that exhibits self-similarity and has a +square-shaped outline with smaller squares within it. + +Source: https://en.wikipedia.org/wiki/Vicsek_fractal +""" import turtle def draw_cross(x: float, y: float, length: float): + """ + Draw a cross at the specified position and with the specified length. + """ turtle.up() turtle.goto(x - length / 2, y - length / 6) turtle.down() @@ -19,6 +35,10 @@ def draw_fractal_recursive(x: float, y: float, length: float, depth: float): + """ + Recursively draw the Vicsek fractal at the specified position, with the + specified length and depth. + """ if depth == 0: draw_cross(x, y, length) return @@ -35,6 +55,10 @@ def draw_vicsek_fractal(x: float, y: float, length: float, depth: float, color="blue"): + """ + Draw the Vicsek fractal at the specified position, with the specified + length and depth. + """ turtle.speed(0) turtle.hideturtle() set_color(color) @@ -49,4 +73,4 @@ if __name__ == "__main__": - main()+ main()
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 isinstance(years_to_repay, int): raise Exception("Years to repay must be an integer > 0") # Yearly rate is divided by 12 to get monthly rate rate_per_month = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly number_of_payments = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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, rate_per_annum: float, years_to_repay: int ) -> float: + """ + Formula for amortization amount per month: + A = p * r * (1 + r)^n / ((1 + r)^n - 1) + where p is the principal, r is the rate of interest per month + and n is the number of payments + + >>> equated_monthly_installments(25000, 0.12, 3) + 830.3577453212793 + >>> equated_monthly_installments(25000, 0.12, 10) + 358.67737100646826 + >>> equated_monthly_installments(0, 0.12, 3) + Traceback (most recent call last): + ... + Exception: Principal borrowed must be > 0 + >>> equated_monthly_installments(25000, -1, 3) + Traceback (most recent call last): + ... + Exception: Rate of interest must be >= 0 + >>> equated_monthly_installments(25000, 0.12, 0) + Traceback (most recent call last): + ... + Exception: Years to repay must be an integer > 0 + """ if principal <= 0: raise Exception("Principal borrowed must be > 0") if rate_per_annum < 0: @@ -27,4 +58,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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, "Green": 5, "Blue": 6, "Violet": 7, "Grey": 8, "White": 9, } multiplier_color_values: dict[str, float] = { "Black": 10**0, "Brown": 10**1, "Red": 10**2, "Orange": 10**3, "Yellow": 10**4, "Green": 10**5, "Blue": 10**6, "Violet": 10**7, "Grey": 10**8, "White": 10**9, "Gold": 10**-1, "Silver": 10**-2, } tolerance_color_values: dict[str, float] = { "Brown": 1, "Red": 2, "Orange": 0.05, "Yellow": 0.02, "Green": 0.5, "Blue": 0.25, "Violet": 0.1, "Grey": 0.01, "Gold": 5, "Silver": 10, } temperature_coeffecient_color_values: dict[str, int] = { "Black": 250, "Brown": 100, "Red": 50, "Orange": 15, "Yellow": 25, "Green": 20, "Blue": 10, "Violet": 5, "Grey": 1, } band_types: dict[int, dict[str, int]] = { 3: {"significant": 2, "multiplier": 1}, 4: {"significant": 2, "multiplier": 1, "tolerance": 1}, 5: {"significant": 3, "multiplier": 1, "tolerance": 1}, 6: {"significant": 3, "multiplier": 1, "tolerance": 1, "temp_coeffecient": 1}, } def get_significant_digits(colors: list) -> str: digit = "" for color in colors: if color not in significant_figures_color_values: msg = f"{color} is not a valid color for significant figure bands" raise ValueError(msg) digit = digit + str(significant_figures_color_values[color]) return str(digit) def get_multiplier(color: str) -> float: if color not in multiplier_color_values: msg = f"{color} is not a valid color for multiplier band" raise ValueError(msg) return multiplier_color_values[color] def get_tolerance(color: str) -> float: if color not in tolerance_color_values: msg = f"{color} is not a valid color for tolerance band" raise ValueError(msg) return tolerance_color_values[color] def get_temperature_coeffecient(color: str) -> int: if color not in temperature_coeffecient_color_values: msg = f"{color} is not a valid color for temperature coeffecient band" raise ValueError(msg) return temperature_coeffecient_color_values[color] def get_band_type_count(total_number_of_bands: int, type_of_band: str) -> int: if total_number_of_bands not in band_types: msg = f"{total_number_of_bands} is not a valid number of bands" raise ValueError(msg) if type_of_band not in band_types[total_number_of_bands]: msg = f"{type_of_band} is not valid for a {total_number_of_bands} band resistor" raise ValueError(msg) return band_types[total_number_of_bands][type_of_band] def check_validity(number_of_bands: int, colors: list) -> bool: if number_of_bands >= 3 and number_of_bands <= 6: if number_of_bands == len(colors): for color in colors: if color not in valid_colors: msg = f"{color} is not a valid color" raise ValueError(msg) return True else: msg = f"Expecting {number_of_bands} colors, provided {len(colors)} colors" raise ValueError(msg) else: msg = "Invalid number of bands. Resistor bands must be 3 to 6" raise ValueError(msg) def calculate_resistance(number_of_bands: int, color_code_list: list) -> dict: is_valid = check_validity(number_of_bands, color_code_list) if is_valid: number_of_significant_bands = get_band_type_count( number_of_bands, "significant" ) significant_colors = color_code_list[:number_of_significant_bands] significant_digits = int(get_significant_digits(significant_colors)) multiplier_color = color_code_list[number_of_significant_bands] multiplier = get_multiplier(multiplier_color) if number_of_bands == 3: tolerance_color = None else: tolerance_color = color_code_list[number_of_significant_bands + 1] tolerance = ( 20 if tolerance_color is None else get_tolerance(str(tolerance_color)) ) if number_of_bands != 6: temperature_coeffecient_color = None else: temperature_coeffecient_color = color_code_list[ number_of_significant_bands + 2 ] temperature_coeffecient = ( 0 if temperature_coeffecient_color is None else get_temperature_coeffecient(str(temperature_coeffecient_color)) ) resisitance = significant_digits * multiplier if temperature_coeffecient == 0: answer = f"{resisitance}Ω ±{tolerance}% " else: answer = f"{resisitance}Ω ±{tolerance}% {temperature_coeffecient} ppm/K" return {"resistance": answer} else: raise ValueError("Input is invalid") if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 omega: Ω. + + The colored bands on a resistor can tell you everything you need to know about its + value and tolerance, as long as you understand how to read them. The order in which + the colors are arranged is very important, and each value of resistor has its own + unique combination. + + The color coding for resistors is an international standard that is defined in IEC + 60062. + + The number of bands present in a resistor varies from three to six. These represent + significant figures, multiplier, tolerance, reliability, and temperature coefficient + Each color used for a type of band has a value assigned to it. It is read from left + to right. + All resistors will have significant figures and multiplier bands. In a three band + resistor first two bands from the left represent significant figures and the third + represents the multiplier band. + + Significant figures - The number of significant figures band in a resistor can vary + from two to three. + Colors and values associated with significant figure bands - + (Black = 0, Brown = 1, Red = 2, Orange = 3, Yellow = 4, Green = 5, Blue = 6, + Violet = 7, Grey = 8, White = 9) + + Multiplier - There will be one multiplier band in a resistor. It is multiplied with + the significant figures obtained from previous bands. + Colors and values associated with multiplier band - + (Black = 100, Brown = 10^1, Red = 10^2, Orange = 10^3, Yellow = 10^4, Green = 10^5, + Blue = 10^6, Violet = 10^7, Grey = 10^8, White = 10^9, Gold = 10^-1, Silver = 10^-2) + Note that multiplier bands use Gold and Silver which are not used for significant + figure bands. + + Tolerance - The tolerance band is not always present. It can be seen in four band + resistors and above. This is a percentage by which the resistor value can vary. + Colors and values associated with tolerance band - + (Brown = 1%, Red = 2%, Orange = 0.05%, Yellow = 0.02%, Green = 0.5%,Blue = 0.25%, + Violet = 0.1%, Grey = 0.01%, Gold = 5%, Silver = 10%) + If no color is mentioned then by default tolerance is 20% + Note that tolerance band does not use Black and White colors. + + Temperature Coeffecient - Indicates the change in resistance of the component as + a function of ambient temperature in terms of ppm/K. + It is present in six band resistors. + Colors and values associated with Temperature coeffecient - + (Black = 250 ppm/K, Brown = 100 ppm/K, Red = 50 ppm/K, Orange = 15 ppm/K, + Yellow = 25 ppm/K, Green = 20 ppm/K, Blue = 10 ppm/K, Violet = 5 ppm/K, + Grey = 1 ppm/K) + Note that temperature coeffecient band does not use White, Gold, Silver colors. + +Sources : + https://www.calculator.net/resistor-calculator.html + https://learn.parallax.com/support/reference/resistor-color-codes + https://byjus.com/physics/resistor-colour-codes/ +""" valid_colors: list = [ "Black", @@ -76,6 +136,19 @@ def get_significant_digits(colors: list) -> str: + """ + Function returns the digit associated with the color. Function takes a + list containing colors as input and returns digits as string + + >>> get_significant_digits(['Black','Blue']) + '06' + + >>> get_significant_digits(['Aqua','Blue']) + Traceback (most recent call last): + ... + ValueError: Aqua is not a valid color for significant figure bands + + """ digit = "" for color in colors: if color not in significant_figures_color_values: @@ -86,6 +159,19 @@ def get_multiplier(color: str) -> float: + """ + Function returns the multiplier value associated with the color. + Function takes color as input and returns multiplier value + + >>> get_multiplier('Gold') + 0.1 + + >>> get_multiplier('Ivory') + Traceback (most recent call last): + ... + ValueError: Ivory is not a valid color for multiplier band + + """ if color not in multiplier_color_values: msg = f"{color} is not a valid color for multiplier band" raise ValueError(msg) @@ -93,6 +179,19 @@ def get_tolerance(color: str) -> float: + """ + Function returns the tolerance value associated with the color. + Function takes color as input and returns tolerance value. + + >>> get_tolerance('Green') + 0.5 + + >>> get_tolerance('Indigo') + Traceback (most recent call last): + ... + ValueError: Indigo is not a valid color for tolerance band + + """ if color not in tolerance_color_values: msg = f"{color} is not a valid color for tolerance band" raise ValueError(msg) @@ -100,6 +199,19 @@ def get_temperature_coeffecient(color: str) -> int: + """ + Function returns the temperature coeffecient value associated with the color. + Function takes color as input and returns temperature coeffecient value. + + >>> get_temperature_coeffecient('Yellow') + 25 + + >>> get_temperature_coeffecient('Cyan') + Traceback (most recent call last): + ... + ValueError: Cyan is not a valid color for temperature coeffecient band + + """ if color not in temperature_coeffecient_color_values: msg = f"{color} is not a valid color for temperature coeffecient band" raise ValueError(msg) @@ -107,6 +219,35 @@ def get_band_type_count(total_number_of_bands: int, type_of_band: str) -> int: + """ + Function returns the number of bands of a given type in a resistor with n bands + Function takes total_number_of_bands and type_of_band as input and returns + number of bands belonging to that type in the given resistor + + >>> get_band_type_count(3,'significant') + 2 + + >>> get_band_type_count(2,'significant') + Traceback (most recent call last): + ... + ValueError: 2 is not a valid number of bands + + >>> get_band_type_count(3,'sign') + Traceback (most recent call last): + ... + ValueError: sign is not valid for a 3 band resistor + + >>> get_band_type_count(3,'tolerance') + Traceback (most recent call last): + ... + ValueError: tolerance is not valid for a 3 band resistor + + >>> get_band_type_count(5,'temp_coeffecient') + Traceback (most recent call last): + ... + ValueError: temp_coeffecient is not valid for a 5 band resistor + + """ if total_number_of_bands not in band_types: msg = f"{total_number_of_bands} is not a valid number of bands" raise ValueError(msg) @@ -117,6 +258,25 @@ def check_validity(number_of_bands: int, colors: list) -> bool: + """ + Function checks if the input provided is valid or not. + Function takes number_of_bands and colors as input and returns + True if it is valid + + >>> check_validity(3, ["Black","Blue","Orange"]) + True + + >>> check_validity(4, ["Black","Blue","Orange"]) + Traceback (most recent call last): + ... + ValueError: Expecting 4 colors, provided 3 colors + + >>> check_validity(3, ["Cyan","Red","Yellow"]) + Traceback (most recent call last): + ... + ValueError: Cyan is not a valid color + + """ if number_of_bands >= 3 and number_of_bands <= 6: if number_of_bands == len(colors): for color in colors: @@ -133,6 +293,44 @@ def calculate_resistance(number_of_bands: int, color_code_list: list) -> dict: + """ + Function calculates the total resistance of the resistor using the color codes. + Function takes number_of_bands, color_code_list as input and returns + resistance + + >>> calculate_resistance(3, ["Black","Blue","Orange"]) + {'resistance': '6000Ω ±20% '} + + >>> calculate_resistance(4, ["Orange","Green","Blue","Gold"]) + {'resistance': '35000000Ω ±5% '} + + >>> calculate_resistance(5, ["Violet","Brown","Grey","Silver","Green"]) + {'resistance': '7.18Ω ±0.5% '} + + >>> calculate_resistance(6, ["Red","Green","Blue","Yellow","Orange","Grey"]) + {'resistance': '2560000Ω ±0.05% 1 ppm/K'} + + >>> calculate_resistance(0, ["Violet","Brown","Grey","Silver","Green"]) + Traceback (most recent call last): + ... + ValueError: Invalid number of bands. Resistor bands must be 3 to 6 + + >>> calculate_resistance(4, ["Violet","Brown","Grey","Silver","Green"]) + Traceback (most recent call last): + ... + ValueError: Expecting 4 colors, provided 5 colors + + >>> calculate_resistance(4, ["Violet","Silver","Brown","Grey"]) + Traceback (most recent call last): + ... + ValueError: Silver is not a valid color for significant figure bands + + >>> calculate_resistance(4, ["Violet","Blue","Lime","Grey"]) + Traceback (most recent call last): + ... + ValueError: Lime is not a valid color + + """ is_valid = check_validity(number_of_bands, color_code_list) if is_valid: number_of_significant_bands = get_band_type_count( @@ -173,4 +371,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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) for i, cash_flow in enumerate(cash_flows) ) return round(present_value, ndigits=2) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 year + +Note: This algorithm assumes that cash flows are paid at the end of the specified year +""" def present_value(discount_rate: float, cash_flows: list[float]) -> float: + """ + >>> present_value(0.13, [10, 20.70, -293, 297]) + 4.69 + >>> present_value(0.07, [-109129.39, 30923.23, 15098.93, 29734,39]) + -42739.63 + >>> present_value(0.07, [109129.39, 30923.23, 15098.93, 29734,39]) + 175519.15 + >>> present_value(-1, [109129.39, 30923.23, 15098.93, 29734,39]) + Traceback (most recent call last): + ... + ValueError: Discount rate cannot be negative + >>> present_value(0.03, []) + Traceback (most recent call last): + ... + ValueError: Cash flows list cannot be empty + """ if discount_rate < 0: raise ValueError("Discount rate cannot be negative") if not cash_flows: @@ -14,4 +39,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 at timestamp t moving_average = 0.0 for i, stock_price in enumerate(stock_prices): if i <= window_size: # Assigning simple moving average till the window_size for the first time # is reached moving_average = (moving_average + stock_price) * 0.5 if i else stock_price else: # Calculating exponential moving average based on current timestamp data # point and previous exponential average value moving_average = (alpha * stock_price) + ((1 - alpha) * moving_average) yield moving_average if __name__ == "__main__": import doctest doctest.testmod() stock_prices = [2.0, 5, 3, 8.2, 6, 9, 10] window_size = 3 result = tuple(exponential_moving_average(iter(stock_prices), window_size)) print(f"{stock_prices = }") print(f"{window_size = }") print(f"{result = }")
--- +++ @@ -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 finance to analyze changes stock prices. +EMA is used in conjunction with Simple moving average (SMA), EMA reacts to the +changes in the value quicker than SMA, which is one of the advantages of using EMA. +""" from collections.abc import Iterator @@ -5,6 +15,29 @@ def exponential_moving_average( stock_prices: Iterator[float], window_size: int ) -> Iterator[float]: + """ + Yields exponential moving averages of the given stock prices. + >>> tuple(exponential_moving_average(iter([2, 5, 3, 8.2, 6, 9, 10]), 3)) + (2, 3.5, 3.25, 5.725, 5.8625, 7.43125, 8.715625) + + :param stock_prices: A stream of stock prices + :param window_size: The number of stock prices that will trigger a new calculation + of the exponential average (window_size > 0) + :return: Yields a sequence of exponential moving averages + + Formula: + + st = alpha * xt + (1 - alpha) * st_prev + + Where, + st : Exponential moving average at timestamp t + xt : stock price in from the stock prices at timestamp t + st_prev : Exponential moving average at timestamp t-1 + alpha : 2/(1 + window_size) - smoothing factor + + Exponential moving average (EMA) is a rule of thumb technique for + smoothing time series data using an exponential window function. + """ if window_size <= 0: raise ValueError("window_size must be > 0") @@ -37,4 +70,4 @@ result = tuple(exponential_moving_average(iter(stock_prices), window_size)) print(f"{stock_prices = }") print(f"{window_size = }") - print(f"{result = }")+ print(f"{result = }")
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 than 1") if not isinstance(purchase_value, (float, int)): raise TypeError("Purchase value must be numeric") if not isinstance(residual_value, (float, int)): raise TypeError("Residual value must be numeric") if purchase_value < 0.0: raise ValueError("Purchase value cannot be less than zero") if purchase_value < residual_value: raise ValueError("Purchase value cannot be less than residual value") # Calculate annual depreciation expense depreciable_cost = purchase_value - residual_value annual_depreciation_expense = depreciable_cost / useful_years # List of annual depreciation expenses list_of_depreciation_expenses = [] accumulated_depreciation_expense = 0.0 for period in range(useful_years): if period != useful_years - 1: accumulated_depreciation_expense += annual_depreciation_expense list_of_depreciation_expenses.append(annual_depreciation_expense) else: depreciation_expense_in_end_year = ( depreciable_cost - accumulated_depreciation_expense ) list_of_depreciation_expenses.append(depreciation_expense_in_end_year) return list_of_depreciation_expenses if __name__ == "__main__": user_input_useful_years = int(input("Please Enter Useful Years:\n > ")) user_input_purchase_value = float(input("Please Enter Purchase Value:\n > ")) user_input_residual_value = float(input("Please Enter Residual Value:\n > ")) print( straight_line_depreciation( user_input_useful_years, user_input_purchase_value, user_input_residual_value, ) )
--- +++ @@ -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 recognized as expenses +over the years during which the asset is used. + +The following methods are widely used +for depreciation calculation in accounting: +- Straight-line method +- Diminishing balance method +- Units-of-production method + +The straight-line method is the simplest and most widely used. +This method calculates depreciation by spreading the cost evenly +over the asset's useful life. + +The following formula shows how to calculate the yearly depreciation expense: + +- annual depreciation expense = + (purchase cost of asset - residual value) / useful life of asset(years) + +Further information on: +https://en.wikipedia.org/wiki/Depreciation + +The function, straight_line_depreciation, returns a list of +the depreciation expenses over the given period. +""" def straight_line_depreciation( @@ -5,6 +34,23 @@ purchase_value: float, residual_value: float = 0.0, ) -> list[float]: + """ + Calculate the depreciation expenses over the given period + :param useful_years: Number of years the asset will be used + :param purchase_value: Purchase expenditure for the asset + :param residual_value: Residual value of the asset at the end of its useful life + :return: A list of annual depreciation expenses over the asset's useful life + >>> straight_line_depreciation(10, 1100.0, 100.0) + [100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0] + >>> straight_line_depreciation(6, 1250.0, 50.0) + [200.0, 200.0, 200.0, 200.0, 200.0, 200.0] + >>> straight_line_depreciation(4, 1001.0) + [250.25, 250.25, 250.25, 250.25] + >>> straight_line_depreciation(11, 380.0, 50.0) + [30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0] + >>> straight_line_depreciation(1, 4985, 100) + [4885.0] + """ if not isinstance(useful_years, int): raise TypeError("Useful years must be an integer") @@ -54,4 +100,4 @@ user_input_purchase_value, user_input_residual_value, ) - )+ )
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: sma.append(None) # SMA not available for early data points else: window = data[i - window_size + 1 : i + 1] sma_value = sum(window) / window_size sma.append(sma_value) return sma if __name__ == "__main__": import doctest doctest.testmod() # Example data (replace with your own time series data) data = [10, 12, 15, 13, 14, 16, 18, 17, 19, 21] # Specify the window size for the SMA window_size = 3 # Calculate the Simple Moving Average sma_values = simple_moving_average(data, window_size) # Print the SMA values print("Simple Moving Average (SMA) Values:") for i, value in enumerate(sma_values): if value is not None: print(f"Day {i + 1}: {value:.2f}") else: print(f"Day {i + 1}: Not enough data for SMA")
--- +++ @@ -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://en.wikipedia.org/wiki/Moving_average +""" from collections.abc import Sequence @@ -5,6 +13,24 @@ def simple_moving_average( data: Sequence[float], window_size: int ) -> list[float | None]: + """ + Calculate the simple moving average (SMA) for some given time series data. + + :param data: A list of numerical data points. + :param window_size: An integer representing the size of the SMA window. + :return: A list of SMA values with the same length as the input data. + + Examples: + >>> sma = simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 3) + >>> [round(value, 2) if value is not None else None for value in sma] + [None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0] + >>> simple_moving_average([10, 12, 15], 5) + [None, None, None] + >>> simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 0) + Traceback (most recent call last): + ... + ValueError: Window size must be a positive integer + """ if window_size < 1: raise ValueError("Window size must be a positive integer") @@ -40,4 +66,4 @@ if value is not None: print(f"Day {i + 1}: {value:.2f}") else: - print(f"Day {i + 1}: Not enough data for SMA")+ print(f"Day {i + 1}: Not enough data for SMA")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/simple_moving_average.py