instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Improve my code by adding docstrings
# https://www.investopedia.com from __future__ import annotations def simple_interest( principal: float, daily_interest_rate: float, days_between_payments: float ) -> float: if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0") if daily_interest_rate < 0: ra...
--- +++ @@ -6,6 +6,30 @@ def simple_interest( principal: float, daily_interest_rate: float, days_between_payments: float ) -> float: + """ + >>> simple_interest(18000.0, 0.06, 3) + 3240.0 + >>> simple_interest(0.5, 0.06, 3) + 0.09 + >>> simple_interest(18000.0, 0.01, 10) + 1800.0 + >>> sim...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/interest.py
Add docstrings including usage examples
from __future__ import annotations import matplotlib.pyplot as plt import numpy as np # initial triangle of Koch snowflake VECTOR_1 = np.array([0, 0]) VECTOR_2 = np.array([0.5, 0.8660254]) VECTOR_3 = np.array([1, 0]) INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] # uncomment for simple Koch curve instea...
--- +++ @@ -1,3 +1,24 @@+""" +Description + The Koch snowflake is a fractal curve and one of the earliest fractals to + have been described. The Koch snowflake can be built up iteratively, in a + sequence of stages. The first stage is an equilateral triangle, and each + successive stage is formed by adding ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/fractals/koch_snowflake.py
Fully document this Python code with docstrings
def price_plus_tax(price: float, tax_rate: float) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(f"{price_plus_tax(100, 0.25) = }") print(f"{price_plus_tax(125.50, 0.05) = }")
--- +++ @@ -1,9 +1,18 @@+""" +Calculate price plus tax of a good or service given its price and a tax rate. +""" def price_plus_tax(price: float, tax_rate: float) -> float: + """ + >>> price_plus_tax(100, 0.25) + 125.0 + >>> price_plus_tax(125.50, 0.05) + 131.775 + """ return price * (1 + ta...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/financial/price_plus_tax.py
Add documentation for all methods
from __future__ import annotations import math from dataclasses import dataclass, field from types import NoneType from typing import Self # Building block classes @dataclass class Angle: degrees: float = 90 def __post_init__(self) -> None: if not isinstance(self.degrees, (int, float)) or not 0 <=...
--- +++ @@ -10,6 +10,22 @@ @dataclass class Angle: + """ + An Angle in degrees (unit of measurement) + + >>> Angle() + Angle(degrees=90) + >>> Angle(45.5) + Angle(degrees=45.5) + >>> Angle(-1) + Traceback (most recent call last): + ... + TypeError: degrees must be a numeric value be...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/geometry/geometry.py
Add docstrings to improve code quality
from dataclasses import dataclass @dataclass class Node: value: int = 0 neighbors: list["Node"] | None = None def __post_init__(self) -> None: self.neighbors = self.neighbors or [] def __hash__(self) -> int: return id(self) def clone_graph(node: Node | None) -> Node | None: if...
--- +++ @@ -1,3 +1,14 @@+""" +LeetCode 133. Clone Graph +https://leetcode.com/problems/clone-graph/ + +Given a reference of a node in a connected undirected graph. + +Return a deep copy (clone) of the graph. + +Each node in the graph contains a value (int) and a list (List[Node]) of its +neighbors. +""" from datacla...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/deep_clone_graph.py
Help me comply with documentation standards
import warnings from collections.abc import Callable from typing import Any import matplotlib.pyplot as plt import numpy as np c_cauliflower = 0.25 + 0.0j c_polynomial_1 = -0.4 + 0.6j c_polynomial_2 = -0.1 + 0.651j c_exponential = -2.0 nb_iterations = 56 window_size = 2.0 nb_pixels = 666 def eval_exponential(c_par...
--- +++ @@ -1,3 +1,25 @@+"""Author Alexandre De Zotti + +Draws Julia sets of quadratic polynomials and exponential maps. + More specifically, this iterates the function a fixed number of times + then plots whether the absolute value of the last iterate is greater than + a fixed threshold (named "escape radius"). For th...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/fractals/julia_sets.py
Generate NumPy-style docstrings
from collections import deque def expand_search( graph: dict[int, list[int]], queue: deque[int], parents: dict[int, int | None], opposite_direction_parents: dict[int, int | None], ) -> int | None: if not queue: return None current = queue.popleft() for neighbor in graph[current]:...
--- +++ @@ -1,3 +1,15 @@+""" +Bidirectional Search Algorithm. + +This algorithm searches from both the source and target nodes simultaneously, +meeting somewhere in the middle. This approach can significantly reduce the +search space compared to a traditional one-directional search. + +Time Complexity: O(b^(d/2)) where...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/bidirectional_search.py
Create documentation for each function signature
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. N_POPULATION = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPU...
--- +++ @@ -1,3 +1,9 @@+""" +Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works +(Evaluation, Selection, Crossover and Mutation) +https://en.wikipedia.org/wiki/Genetic_algorithm +Author: D4rkia +""" from __future__ import annotations @@ -16,11 +22,23 @@ def evaluate(item: str,...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/genetic_algorithm/basic_string.py
Document my Python code with docstrings
from __future__ import annotations from dataclasses import dataclass import matplotlib.pyplot as plt import numpy as np @dataclass class FuzzySet: name: str left_boundary: float peak: float right_boundary: float def __str__(self) -> str: return ( f"{self.name}: [{self.left...
--- +++ @@ -1,3 +1,8 @@+""" +By @Shreya123714 + +https://en.wikipedia.org/wiki/Fuzzy_set +""" from __future__ import annotations @@ -9,6 +14,51 @@ @dataclass class FuzzySet: + """ + A class for representing and manipulating triangular fuzzy sets. + Attributes: + name: The name or label of the fu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/fuzzy_logic/fuzzy_operations.py
Help me comply with documentation standards
from __future__ import annotations class Point: def __init__(self, x_coordinate: float, y_coordinate: float) -> None: self.x = x_coordinate self.y = y_coordinate def __eq__(self, other: object) -> bool: if not isinstance(other, Point): return NotImplemented retur...
--- +++ @@ -1,8 +1,29 @@+""" +Jarvis March (Gift Wrapping) algorithm for finding the convex hull of a set of points. + +The convex hull is the smallest convex polygon that contains all the points. + +Time Complexity: O(n*h) where n is the number of points and h is the number of +hull points. +Space Complexity: O(h) whe...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/geometry/jarvis_march.py
Write docstrings describing each step
from __future__ import annotations from collections.abc import Sequence from dataclasses import dataclass from typing import TypeVar T = TypeVar("T", bound="Point") @dataclass class Point: x: float y: float def __init__(self, x_coordinate: float, y_coordinate: float) -> None: self.x = float(x...
--- +++ @@ -1,3 +1,19 @@+""" +Graham Scan algorithm for finding the convex hull of a set of points. + +The Graham scan is a method of computing the convex hull of a finite set of points +in the plane with time complexity O(n log n). It is named after Ronald Graham, who +published the original algorithm in 1972. + +The ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/geometry/graham_scan.py
Add docstrings to improve collaboration
from __future__ import annotations import math __version__ = "2020.9.26" __author__ = "xcodz-dot, cclaus, dhruvmanila" def convert_to_2d( x: float, y: float, z: float, scale: float, distance: float ) -> tuple[float, float]: if not all(isinstance(val, (float, int)) for val in locals().values()): msg...
--- +++ @@ -1,3 +1,6 @@+""" +render 3d points for 2d surfaces. +""" from __future__ import annotations @@ -10,6 +13,20 @@ def convert_to_2d( x: float, y: float, z: float, scale: float, distance: float ) -> tuple[float, float]: + """ + Converts 3d point to a 2d drawable point + + >>> convert_to_2d(1....
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphics/vector3_for_2d_rendering.py
Add docstrings explaining edge cases
import copy import random cities = { 0: [0, 0], 1: [0, 5], 2: [3, 8], 3: [8, 10], 4: [12, 8], 5: [12, 4], 6: [8, 0], 7: [6, 2], } def main( cities: dict[int, list[int]], ants_num: int, iterations_num: int, pheromone_evaporation: float, alpha: float, beta: floa...
--- +++ @@ -1,3 +1,15 @@+""" +Use an ant colony optimization algorithm to solve the travelling salesman problem (TSP) +which asks the following question: +"Given a list of cities and the distances between each pair of cities, what is the + shortest possible route that visits each city exactly once and returns to the or...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/ant_colony_optimization_algorithms.py
Turn comments into proper docstrings
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range...
--- +++ @@ -77,6 +77,14 @@ def dfs(g, s): + """ + >>> dfs({1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}, 1) + 1 + 2 + 4 + 5 + 3 + """ vis, _s = {s}, [s] print(s) while _s: @@ -104,6 +112,17 @@ def bfs(g, s): + """ + >>> bfs({1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [], 5: [...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/basic_graphs.py
Add docstrings that explain inputs and outputs
#!/usr/bin/python from __future__ import annotations from queue import Queue class Graph: def __init__(self) -> None: self.vertices: dict[int, list[int]] = {} def print_graph(self) -> None: for i in self.vertices: print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]]))...
--- +++ @@ -1,5 +1,6 @@ #!/usr/bin/python +"""Author: OMKAR PATHAK""" from __future__ import annotations @@ -11,16 +12,44 @@ self.vertices: dict[int, list[int]] = {} def print_graph(self) -> None: + """ + prints adjacency list representation of graaph + >>> g = Graph() + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/breadth_first_search.py
Write docstrings describing functionality
import sys import turtle def get_mid(p1: tuple[float, float], p2: tuple[float, float]) -> tuple[float, float]: return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2 def triangle( vertex1: tuple[float, float], vertex2: tuple[float, float], vertex3: tuple[float, float], depth: int, ) -> None: my_pe...
--- +++ @@ -1,9 +1,47 @@+""" +Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95 + +Simple example of fractal generation using recursion. + +What is the Sierpiński Triangle? + The Sierpiński triangle (sometimes spelled Sierpinski), also called the +Sierpiński gasket or Sierpiński sieve, is a fract...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/fractals/sierpinski_triangle.py
Help me write clear docstrings
import numpy as np def validate_adjacency_list(graph: list[list[int | None]]) -> None: if not isinstance(graph, list): raise ValueError("Graph should be a list of lists.") for node_index, neighbors in enumerate(graph): if not isinstance(neighbors, list): no_neighbors_message: str...
--- +++ @@ -1,8 +1,51 @@+""" +Lanczos Method for Finding Eigenvalues and Eigenvectors of a Graph. + +This module demonstrates the Lanczos method to approximate the largest eigenvalues +and corresponding eigenvectors of a symmetric matrix represented as a graph's +adjacency list. The method efficiently handles large, sp...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/lanczos_eigenvectors.py
Add well-formatted docstrings
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean HEURISTIC = 0 grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0...
--- +++ @@ -1,3 +1,6 @@+""" +https://en.wikipedia.org/wiki/Bidirectional_search +""" from __future__ import annotations @@ -23,6 +26,20 @@ class Node: + """ + >>> k = Node(0, 0, 4, 3, 0, None) + >>> k.calculate_heuristic() + 5.0 + >>> n = Node(1, 4, 3, 4, 2, None) + >>> n.calculate_heuristic(...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/bidirectional_a_star.py
Generate docstrings for this script
#!/usr/bin/env python3 from __future__ import annotations import random import unittest from pprint import pformat from typing import TypeVar import pytest T = TypeVar("T") class GraphAdjacencyList[T]: def __init__( self, vertices: list[T], edges: list[list[T]], directed: bool = True ) -> None: ...
--- +++ @@ -1,4 +1,20 @@ #!/usr/bin/env python3 +""" +Author: Vikram Nithyanandam + +Description: +The following implementation is a robust unweighted Graph data structure +implemented using an adjacency list. This vertices and edges of this graph can be +effectively initialized and modified while storing your chosen g...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/graph_adjacency_list.py
Add documentation for all methods
from __future__ import annotations import time Path = list[tuple[int, int]] grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0...
--- +++ @@ -1,3 +1,6 @@+""" +https://en.wikipedia.org/wiki/Bidirectional_search +""" from __future__ import annotations @@ -31,6 +34,23 @@ class BreadthFirstSearch: + """ + # Comment out slow pytests... + # 9.15s call graphs/bidirectional_breadth_first_search.py:: \ + # graphs.bi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/bidirectional_breadth_first_search.py
Fill in missing docstrings in my code
# Title: Dijkstra's Algorithm for finding single source shortest path from scratch # Author: Shubham Malik # References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm import math import sys # For storing the vertex set to retrieve node with the lowest distance class PriorityQueue: # Based on Min Heap ...
--- +++ @@ -11,14 +11,67 @@ class PriorityQueue: # Based on Min Heap def __init__(self): + """ + Priority queue class constructor method. + + Examples: + >>> priority_queue_test = PriorityQueue() + >>> priority_queue_test.cur_size + 0 + >>> priority_queue_test....
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/dijkstra_algorithm.py
Create docstrings for each class method
from __future__ import annotations Path = list[tuple[int, int]] # 0's are free path whereas 1's are obstacles TEST_GRIDS = [ [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], ...
--- +++ @@ -1,3 +1,6 @@+""" +https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS +""" from __future__ import annotations @@ -35,6 +38,20 @@ class Node: + """ + >>> k = Node(0, 0, 4, 5, 0, None) + >>> k.calculate_heuristic() + 9 + >>> n = Node(1, 4, 3, 4, 2, None) + >>> n.calculate_heur...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/greedy_best_first.py
Turn comments into proper docstrings
# https://en.wikipedia.org/wiki/B%C3%A9zier_curve # https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm from __future__ import annotations from scipy.special import comb class BezierCurve: def __init__(self, list_of_points: list[tuple[float, float]]): self.list_of_points = list...
--- +++ @@ -6,14 +6,35 @@ class BezierCurve: + """ + Bezier curve is a weighted sum of a set of control points. + Generate Bezier curves from a given set of control points. + This implementation works only for 2d coordinates in the xy plane. + """ def __init__(self, list_of_points: list[tuple[...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphics/bezier_curve.py
Write proper docstrings for these functions
import heapq def greedy_min_vertex_cover(graph: dict) -> set[int]: # queue used to store nodes and their rank queue: list[list] = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works...
--- +++ @@ -1,8 +1,24 @@+""" +* Author: Manuel Di Lullo (https://github.com/manueldilullo) +* Description: Approximization algorithm for minimum vertex cover problem. + Greedy Approach. Uses graphs represented with an adjacency list +URL: https://mathworld.wolfram.com/MinimumVertexCover.html +URL: https:/...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/greedy_min_vertex_cover.py
Add verbose docstrings with examples
#!/usr/bin/env python3 # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import TypeVar T = TypeVar("T") class GraphAdjacencyList[T]: def __init__(self, directed: bool = True) -> None: ...
--- +++ @@ -12,8 +12,71 @@ class GraphAdjacencyList[T]: + """ + Adjacency List type Graph Data Structure that accounts for directed and undirected + Graphs. Initialize graph object indicating whether it's directed or undirected. + + Directed graph example: + >>> d_graph = GraphAdjacencyList() + >...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/graph_list.py
Generate docstrings for exported functions
def matching_min_vertex_cover(graph: dict) -> set: # chosen_vertices = set of chosen vertices chosen_vertices = set() # edges = list of graph's edges edges = get_edges(graph) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to...
--- +++ @@ -1,6 +1,23 @@+""" +* Author: Manuel Di Lullo (https://github.com/manueldilullo) +* Description: Approximization algorithm for minimum vertex cover problem. + Matching Approach. Uses graphs represented with an adjacency list + +URL: https://mathworld.wolfram.com/MinimumVertexCover.html +URL: htt...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/matching_min_vertex_cover.py
Add inline docstrings for readability
from __future__ import annotations import random # Adjacency list representation of this graph: # https://en.wikipedia.org/wiki/File:Single_run_of_Karger%E2%80%99s_Mincut_algorithm.svg TEST_GRAPH = { "1": ["2", "3", "4", "5"], "2": ["1", "3", "4", "5"], "3": ["1", "2", "4", "5", "10"], "4": ["1", "2"...
--- +++ @@ -1,3 +1,6 @@+""" +An implementation of Karger's Algorithm for partitioning a graph. +""" from __future__ import annotations @@ -20,6 +23,24 @@ def partition_graph(graph: dict[str, list[str]]) -> set[tuple[str, str]]: + """ + Partitions a graph using Karger's Algorithm. Implemented from + ps...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/karger.py
Add structured docstrings to improve clarity
from __future__ import annotations from typing import Any class Graph: def __init__(self, num_of_nodes: int) -> None: self.m_num_of_nodes = num_of_nodes self.m_edges: list[list[int]] = [] self.m_component: dict[int, int] = {} def add_edge(self, u_node: int, v_node: int, weight: int...
--- +++ @@ -1,3 +1,29 @@+"""Borůvka's algorithm. + +Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm. +Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a +connected graph, or a minimum spanning forest if a graph that is not connected. + +The time comple...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/boruvka.py
Add detailed docstrings explaining each function
from collections import defaultdict, deque def is_bipartite_dfs(graph: dict[int, list[int]]) -> bool: def depth_first_search(node: int, color: int) -> bool: if visited[node] == -1: visited[node] = color if node not in graph: return True for neighbor in ...
--- +++ @@ -2,8 +2,69 @@ def is_bipartite_dfs(graph: dict[int, list[int]]) -> bool: + """ + Check if a graph is bipartite using depth-first search (DFS). + + Args: + `graph`: Adjacency list representing the graph. + + Returns: + ``True`` if bipartite, ``False`` otherwise. + + Checks if ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/check_bipatrite.py
Add docstrings to improve readability
def min_path_sum(grid: list) -> int: if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information") for cell_n in range(1, len(grid[0])): grid[0][cell_n] += grid[0][cell_n - 1] row_above = grid[0] for row_n in range(1, len(grid)): current_...
--- +++ @@ -1,4 +1,33 @@ def min_path_sum(grid: list) -> int: + """ + Find the path from top left to bottom right of array of numbers + with the lowest possible sum and return the sum along this path. + >>> min_path_sum([ + ... [1, 3, 1], + ... [1, 5, 1], + ... [4, 2, 1], + ... ]) + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/minimum_path_sum.py
Document this code for team use
# Author: Swayam Singh (https://github.com/practice404) from queue import PriorityQueue from typing import Any import numpy as np def pass_and_relaxation( graph: dict, v: str, visited_forward: set, visited_backward: set, cst_fwd: dict, cst_bwd: dict, queue: PriorityQueue, parent: di...
--- +++ @@ -1,3 +1,12 @@+""" +Bi-directional Dijkstra's algorithm. + +A bi-directional approach is an efficient and +less time consuming optimization for Dijkstra's +searching algorithm + +Reference: shorturl.at/exHM7 +""" # Author: Swayam Singh (https://github.com/practice404) @@ -38,6 +47,18 @@ def bidirectional...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/bi_directional_dijkstra.py
Add well-formatted docstrings
from __future__ import annotations from collections import Counter from random import random class MarkovChainGraphUndirectedUnweighted: def __init__(self): self.connections = {} def add_node(self, node: str) -> None: self.connections[node] = {} def add_transition_probability( ...
--- +++ @@ -5,6 +5,9 @@ class MarkovChainGraphUndirectedUnweighted: + """ + Undirected Unweighted Graph for running Markov Chain Algorithm + """ def __init__(self): self.connections = {} @@ -38,6 +41,27 @@ def get_transitions( start: str, transitions: list[tuple[str, str, float]], step...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/markov_chain.py
Add docstrings with type hints explained
def max_profit(prices: list[int]) -> int: if not prices: return 0 min_price = prices[0] max_profit: int = 0 for price in prices: min_price = min(price, min_price) max_profit = max(price - min_price, max_profit) return max_profit if __name__ == "__main__": import do...
--- +++ @@ -1,6 +1,27 @@+""" +Given a list of stock prices calculate the maximum profit that can be made from a +single buy and sell of one share of stock. We only allowed to complete one buy +transaction and one sell transaction but must buy before we sell. + +Example : prices = [7, 1, 5, 3, 6, 4] +max_profit will re...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/greedy_methods/best_time_to_buy_and_sell_stock.py
Document this script properly
import random def random_graph( vertices_number: int, probability: float, directed: bool = False ) -> dict: graph: dict = {i: [] for i in range(vertices_number)} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(vertices_nu...
--- +++ @@ -1,3 +1,10 @@+""" +* Author: Manuel Di Lullo (https://github.com/manueldilullo) +* Description: Random graphs generator. + Uses graphs represented with an adjacency list. + +URL: https://en.wikipedia.org/wiki/Random_graph +""" import random @@ -5,6 +12,20 @@ def random_graph( vertices...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/random_graph_generator.py
Insert docstrings into my code
def minimum_waiting_time(queries: list[int]) -> int: n = len(queries) if n in (0, 1): return 0 return sum(query * (n - i - 1) for i, query in enumerate(sorted(queries))) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,41 @@+""" +Calculate the minimum waiting time using a greedy algorithm. +reference: https://www.youtube.com/watch?v=Sf3eiO12eJs + +For doctests run following command: +python -m doctest -v minimum_waiting_time.py + +The minimum_waiting_time function uses a greedy algorithm to calculate the minimum +t...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/greedy_methods/minimum_waiting_time.py
Add docstrings that explain purpose and usage
import heapq as hq import math from collections.abc import Iterator class Vertex: def __init__(self, id_): self.id = str(id_) self.key = None self.pi = None self.neighbors = [] self.edges = {} # {vertex:distance} def __lt__(self, other): return self.key < ot...
--- +++ @@ -1,3 +1,9 @@+"""Prim's Algorithm. + +Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm. + +Details: https://en.wikipedia.org/wiki/Prim%27s_algorithm +""" import heapq as hq import math @@ -5,8 +11,16 @@ class Vertex: + """Class Vertex.""" def __init__(self, id_...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/prim.py
Document all public functions with docstrings
class Graph: def __init__(self): self.num_vertices = 0 self.num_edges = 0 self.adjacency = {} def add_vertex(self, vertex): if vertex not in self.adjacency: self.adjacency[vertex] = {} self.num_vertices += 1 def add_edge(self, head, tail, weight): ...
--- +++ @@ -1,150 +1,196 @@-class Graph: - - def __init__(self): - self.num_vertices = 0 - self.num_edges = 0 - self.adjacency = {} - - def add_vertex(self, vertex): - if vertex not in self.adjacency: - self.adjacency[vertex] = {} - self.num_vertices += 1 - - d...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/minimum_spanning_tree_boruvka.py
Add docstrings that explain inputs and outputs
from __future__ import annotations from collections import deque from queue import Queue from timeit import timeit G = { "A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"], "E": ["B", "F"], "F": ["C", "E"], } def breadth_first_search(graph: dict, start: str) -> list[str]: ...
--- +++ @@ -1,3 +1,17 @@+""" +https://en.wikipedia.org/wiki/Breadth-first_search +pseudo-code: +breadth_first_search(graph G, start vertex s): +// all nodes initially unexplored +mark s as explored +let Q = queue data structure, initialized with s +while Q is non-empty: + remove the first node of Q, call it v + f...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/breadth_first_search_2.py
Generate docstrings for each module
test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]} test_graph_2 = {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []} def dfs(graph: dict, vert: int, visited: list) -> list: visited[vert] = True connected_verts = [] for neighbour in graph[vert]: if no...
--- +++ @@ -1,3 +1,9 @@+""" +https://en.wikipedia.org/wiki/Component_(graph_theory) + +Finding connected components in graph + +""" test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]} @@ -5,6 +11,14 @@ def dfs(graph: dict, vert: int, visited: list) -> list: + """ + Use ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/connected_components.py
Add documentation for all methods
test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} test_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def topology_sort( graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: visited[vert] = True order = [] for neighbour in graph[vert]: if no...
--- +++ @@ -1,3 +1,9 @@+""" +https://en.wikipedia.org/wiki/Strongly_connected_component + +Finding strongly connected components in directed graph + +""" test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} @@ -7,6 +13,14 @@ def topology_sort( graph: dict[int, list[int]], vert: int, visited: list[bool] ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/strongly_connected_components.py
Document helper functions with docstrings
from collections import deque def tarjan(g: list[list[int]]) -> list[list[int]]: n = len(g) stack: deque[int] = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v: int, index: int, components: list[list[int]]) -> int: ...
--- +++ @@ -2,6 +2,39 @@ def tarjan(g: list[list[int]]) -> list[list[int]]: + """ + Tarjan's algo for finding strongly connected components in a directed graph + + Uses two main attributes of each node to track reachability, the index of that node + within a component(index), and the lowest index reacha...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/tarjans_scc.py
Generate docstrings for each module
def check_cycle(graph: dict) -> bool: # Keep track of visited nodes visited: set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack rec_stk: set[int] = set() return any( node not in visited and depth_first_search(graph, node, visited, rec_stk) ...
--- +++ @@ -1,6 +1,16 @@+""" +Program to check if a cycle is present in a given graph +""" def check_cycle(graph: dict) -> bool: + """ + Returns True if graph is cyclic else False + >>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}) + False + >>> check_cycle(graph={0:[1, 2], 1:[2]...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/check_cycle.py
Improve documentation using docstrings
def find_minimum_change(denominations: list[int], value: str) -> list[int]: total_value = int(value) # Initialize Result answer = [] # Traverse through all denomination for denomination in reversed(denominations): # Find denominations while int(total_value) >= int(denomination): ...
--- +++ @@ -1,6 +1,60 @@+""" +Test cases: +Do you want to enter your denominations ? (Y/N) :N +Enter the change you want to make in Indian Currency: 987 +Following is minimal change for 987 : +500 100 100 100 100 50 20 10 5 2 + +Do you want to enter your denominations ? (Y/N) :Y +Enter number of denomination:10 +1 +5 ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/greedy_methods/minimum_coin_change.py
Add docstrings to make code maintainable
from dataclasses import dataclass @dataclass class GasStation: gas_quantity: int cost: int def get_gas_stations( gas_quantities: list[int], costs: list[int] ) -> tuple[GasStation, ...]: return tuple( GasStation(quantity, cost) for quantity, cost in zip(gas_quantities, costs) ) def can...
--- +++ @@ -1,3 +1,28 @@+""" +Task: +There are n gas stations along a circular route, where the amount of gas +at the ith station is gas_quantities[i]. + +You have a car with an unlimited gas tank and it costs costs[i] of gas +to travel from the ith station to its next (i + 1)th station. +You begin the journey with an ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/greedy_methods/gas_station.py
Generate docstrings for exported functions
def optimal_merge_pattern(files: list) -> float: optimal_merge_cost = 0 while len(files) > 1: temp = 0 # Consider two files with minimum cost to be merged for _ in range(2): min_index = files.index(min(files)) temp += files[min_index] files.pop(min_i...
--- +++ @@ -1,6 +1,42 @@+""" +This is a pure Python implementation of the greedy-merge-sort algorithm +reference: https://www.geeksforgeeks.org/optimal-file-merge-patterns/ + +For doctests run following command: +python3 -m doctest -v greedy_merge_sort.py + +Objective +Merge a set of sorted files of different length in...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/greedy_methods/optimal_merge_pattern.py
Write docstrings describing each step
from heapq import heappop, heappush from sys import maxsize def smallest_range(nums: list[list[int]]) -> list[int]: min_heap: list[tuple[int, int, int]] = [] current_max = -maxsize - 1 for i, items in enumerate(nums): heappush(min_heap, (items[0], i, 0)) current_max = max(current_max, i...
--- +++ @@ -1,9 +1,43 @@+""" +smallest_range function takes a list of sorted integer lists and finds the smallest +range that includes at least one number from each list, using a min heap for efficiency. +""" from heapq import heappop, heappush from sys import maxsize def smallest_range(nums: list[list[int]]) ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/greedy_methods/smallest_range.py
Add verbose docstrings with examples
def djb2(s: str) -> int: hash_value = 5381 for x in s: hash_value = ((hash_value << 5) + hash_value) + ord(x) return hash_value & 0xFFFFFFFF
--- +++ @@ -1,7 +1,35 @@+""" +This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c +Another version of this algorithm (now favored by Bernstein) uses xor: + hash(i) = hash(i - 1) * 33 ^ str[i]; + + First Magic constant 33: + It has never been adequately explained. + It's m...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/djb2.py
Fully document this Python code with docstrings
MOD_ADLER = 65521 def adler32(plain_text: str) -> int: a = 1 b = 0 for plain_chr in plain_text: a = (a + ord(plain_chr)) % MOD_ADLER b = (b + a) % MOD_ADLER return (b << 16) | a
--- +++ @@ -1,11 +1,30 @@+""" +Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. +Compared to a cyclic redundancy check of the same length, it trades reliability for +speed (preferring the latter). +Adler-32 is more reliable than Fletcher-16, and slightly less reliable than +Fletcher-32.[2] + +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/adler32.py
Write Python docstrings for this snippet
def fletcher16(text: str) -> int: data = bytes(text, "ascii") sum1 = 0 sum2 = 0 for character in data: sum1 = (sum1 + character) % 255 sum2 = (sum1 + sum2) % 255 return (sum2 << 8) | sum1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,16 +1,36 @@- - -def fletcher16(text: str) -> int: - data = bytes(text, "ascii") - sum1 = 0 - sum2 = 0 - for character in data: - sum1 = (sum1 + character) % 255 - sum2 = (sum1 + sum2) % 255 - return (sum2 << 8) | sum1 - - -if __name__ == "__main__": - import doctest - - ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/fletcher16.py
Add detailed documentation for each class
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrog...
--- +++ @@ -3,6 +3,46 @@ # Coding date: apr 2019 # Black: True +""" +* This code implement the Hamming code: + https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, +Hamming codes are a family of linear error-correcting codes. Hamming +codes can detect up to two-bit errors or correct one-bit errors ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/hamming_code.py
Write docstrings including parameters and return values
from collections.abc import Generator from math import sin def to_little_endian(string_32: bytes) -> bytes: if len(string_32) != 32: raise ValueError("Input must be of length 32") little_endian = b"" for i in [3, 2, 1, 0]: little_endian += string_32[8 * i : 8 * i + 8] return little_e...
--- +++ @@ -1,9 +1,39 @@+""" +The MD5 algorithm is a hash function that's commonly used as a checksum to +detect data corruption. The algorithm works by processing a given message in +blocks of 512 bits, padding the message as needed. It uses the blocks to operate +a 128-bit state and performs a total of 64 such operat...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/md5.py
Generate NumPy-style docstrings
import argparse import hashlib # hashlib is only used inside the Test class import struct class SHA1Hash: def __init__(self, data): self.data = data self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] @staticmethod def rotate(n, b): return ((n << b) | (n >> (3...
--- +++ @@ -1,3 +1,30 @@+""" +Implementation of the SHA1 hash function and gives utilities to find hash of string or +hash of text from a file. Also contains a Test class to verify that the generated hash +matches what is returned by the hashlib library + +Usage: python sha1.py --string "Hello World!!" + python s...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/sha1.py
Write docstrings including parameters and return values
def sdbm(plain_text: str) -> int: hash_value = 0 for plain_chr in plain_text: hash_value = ( ord(plain_chr) + (hash_value << 6) + (hash_value << 16) - hash_value ) return hash_value
--- +++ @@ -1,9 +1,39 @@+""" +This algorithm was created for sdbm (a public-domain reimplementation of ndbm) +database library. +It was found to do well in scrambling bits, causing better distribution of the keys +and fewer splits. +It also happens to be a good general hashing function with good distribution. +The actu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/sdbm.py
Include argument descriptions in docstrings
# To get an insight into Greedy Algorithm through the Knapsack problem def calc_profit(profit: list, weight: list, max_weight: int) -> int: if len(profit) != len(weight): raise ValueError("The length of profit and weight must be same.") if max_weight <= 0: raise ValueError("max_weight must g...
--- +++ @@ -1,9 +1,35 @@ # To get an insight into Greedy Algorithm through the Knapsack problem +""" +A shopkeeper has bags of wheat that each have different weights and different profits. +eg. +profit 5 8 7 1 12 3 4 +weight 2 7 1 6 4 2 5 +max_weight 100 + +Constraints: +max_weight > 0 +profit[i] >= 0 +weight[i] >...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/knapsack/greedy_knapsack.py
Write docstrings describing each step
# Author: M. Yathurshan # Black Formatter: True import argparse import struct import unittest class SHA256: def __init__(self, data: bytes) -> None: self.data = data # Initialize hash values self.hashes = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, ...
--- +++ @@ -1,216 +1,248 @@-# Author: M. Yathurshan -# Black Formatter: True - - -import argparse -import struct -import unittest - - -class SHA256: - - def __init__(self, data: bytes) -> None: - self.data = data - - # Initialize hash values - self.hashes = [ - 0x6A09E667, - ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/hashes/sha256.py
Create docstrings for each class method
# To get an insight into naive recursive way to solve the Knapsack problem def knapsack( weights: list, values: list, number_of_items: int, max_weight: int, index: int ) -> int: if index == number_of_items: return 0 ans1 = 0 ans2 = 0 ans1 = knapsack(weights, values, number_of_items, max_...
--- +++ @@ -1,11 +1,38 @@ # To get an insight into naive recursive way to solve the Knapsack problem +""" +A shopkeeper has bags of wheat that each have different weights and different profits. +eg. +no_of_items 4 +profit 5 4 8 6 +weight 1 2 4 5 +max_weight 5 +Constraints: +max_weight > 0 +profit[i] >= 0 +weight[i]...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/knapsack/recursive_approach_knapsack.py
Add missing documentation to my Python functions
import numpy as np from numpy import float64 from numpy.typing import NDArray def retroactive_resolution( coefficients: NDArray[float64], vector: NDArray[float64] ) -> NDArray[float64]: rows, _columns = np.shape(coefficients) x: NDArray[float64] = np.zeros((rows, 1), dtype=float) for row in reverse...
--- +++ @@ -1,3 +1,7 @@+""" +| Gaussian elimination method for solving a system of linear equations. +| Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination +""" import numpy as np from numpy import float64 @@ -7,6 +11,27 @@ def retroactive_resolution( coefficients: NDArray[float64], vecto...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/gaussian_elimination.py
Generate consistent documentation across files
from __future__ import annotations from functools import lru_cache def knapsack( capacity: int, weights: list[int], values: list[int], counter: int, allow_repetition=False, ) -> int: @lru_cache def knapsack_recur(capacity: int, counter: int) -> int: # Base Case if counte...
--- +++ @@ -1,3 +1,6 @@+"""A recursive implementation of 0-N Knapsack Problem +https://en.wikipedia.org/wiki/Knapsack_problem +""" from __future__ import annotations @@ -11,6 +14,28 @@ counter: int, allow_repetition=False, ) -> int: + """ + Returns the maximum value that can be put in a knapsack of...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/knapsack/knapsack.py
Create documentation strings for testing functions
from __future__ import annotations import numpy as np from numpy import float64 from numpy.typing import NDArray # Method to find solution of system of linear equations def jacobi_iteration_method( coefficient_matrix: NDArray[float64], constant_matrix: NDArray[float64], init_val: list[float], iterat...
--- +++ @@ -1,3 +1,6 @@+""" +Jacobi Iteration Method - https://en.wikipedia.org/wiki/Jacobi_method +""" from __future__ import annotations @@ -13,6 +16,69 @@ init_val: list[float], iterations: int, ) -> list[float]: + """ + Jacobi Iteration Method: + An iterative algorithm to determine the solut...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/jacobi_iteration_method.py
Add docstrings explaining edge cases
from __future__ import annotations import numpy as np def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray]: # Ensure that table is a square array rows, columns = np.shape(table) if rows != columns: msg = ( "'table' has to be of square shaped array but got...
--- +++ @@ -1,3 +1,21 @@+""" +Lower-upper (LU) decomposition factors a matrix as a product of a lower +triangular matrix and an upper triangular matrix. A square matrix has an LU +decomposition under the following conditions: + + - If the matrix is invertible, then it has an LU decomposition if and only + if al...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/lu_decomposition.py
Add docstrings to make code maintainable
#!/usr/bin/python class Graph: def __init__(self): self.vertex = {} # for printing the Graph vertices def print_graph(self) -> None: print(self.vertex) for i in self.vertex: print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]])) # for adding the edge bet...
--- +++ @@ -1,5 +1,6 @@ #!/usr/bin/python +"""Author: OMKAR PATHAK""" class Graph: @@ -8,12 +9,44 @@ # for printing the Graph vertices def print_graph(self) -> None: + """ + Print the graph vertices. + + Example: + >>> g = Graph() + >>> g.add_edge(0, 1) + >>> ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/depth_first_search_2.py
Generate docstrings for script automation
import heapq def dijkstra(graph, start, end): heap = [(0, start)] # cost from start node,end node visited = set() while heap: (cost, u) = heapq.heappop(heap) if u in visited: continue visited.add(u) if u == end: return cost for v, c in gra...
--- +++ @@ -1,8 +1,49 @@+""" +pseudo-code + +DIJKSTRA(graph G, start vertex s, destination vertex d): + +//all nodes initially unexplored + +1 - let H = min heap data structure, initialized with 0 and s [here 0 indicates + the distance from start vertex s] +2 - while H is non-empty: +3 - remove the first node ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/dijkstra.py
Generate docstrings for script automation
from __future__ import annotations def depth_first_search(graph: dict, start: str) -> set[str]: explored, stack = set(start), [start] while stack: v = stack.pop() explored.add(v) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elem...
--- +++ @@ -1,8 +1,22 @@+"""Non recursive implementation of a DFS algorithm.""" from __future__ import annotations def depth_first_search(graph: dict, start: str) -> set[str]: + """Depth First Search on Graph + :param graph: directed graph in dictionary format + :param start: starting vertex as a strin...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/depth_first_search.py
Turn comments into proper docstrings
from typing import Any import numpy as np def _is_matrix_spd(matrix: np.ndarray) -> bool: # Ensure matrix is square. assert np.shape(matrix)[0] == np.shape(matrix)[1] # If matrix not symmetric, exit right away. if np.allclose(matrix, matrix.T) is False: return False # Get eigenvalues a...
--- +++ @@ -1,3 +1,8 @@+""" +Resources: +- https://en.wikipedia.org/wiki/Conjugate_gradient_method +- https://en.wikipedia.org/wiki/Definite_symmetric_matrix +""" from typing import Any @@ -5,6 +10,26 @@ def _is_matrix_spd(matrix: np.ndarray) -> bool: + """ + Returns True if input matrix is symmetric pos...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/src/conjugate_gradient.py
Create docstrings for each class method
# pylint: disable=invalid-name from collections import defaultdict def dfs(start: int) -> int: # pylint: disable=redefined-outer-name ret = 1 visited[start] = True for v in tree[start]: if v not in visited: ret += dfs(v) if ret % 2 == 0: cuts.append(start) return r...
--- +++ @@ -1,9 +1,24 @@+""" +You are given a tree(a simple connected graph with no cycles). The tree has N +nodes numbered from 1 to N and is rooted at node 1. + +Find the maximum number of edges you can remove from the tree to get a forest +such that each connected component of the forest contains an even number of +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/even_tree.py
Add structured docstrings to improve clarity
from __future__ import annotations class Graph: def __init__(self, vertices: int) -> None: self.vertices = vertices self.graph = [[0] * vertices for _ in range(vertices)] def print_solution(self, distances_from_source: list[int]) -> None: print("Vertex \t Distance from Source") ...
--- +++ @@ -3,10 +3,23 @@ class Graph: def __init__(self, vertices: int) -> None: + """ + >>> graph = Graph(2) + >>> graph.vertices + 2 + >>> len(graph.graph) + 2 + >>> len(graph.graph[0]) + 2 + """ self.vertices = vertices self.gra...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/dijkstra_alternate.py
Create structured documentation for my script
# fmt: off edge_array = [ ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3', 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3'], ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'cd-e2', 'de-e1', 'df-e8', 'ef-e3', 'eg-e2', 'fg-e6'],...
--- +++ @@ -1,172 +1,233 @@- -# fmt: off -edge_array = [ - ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', 'cd-e2', 'ce-e4', - 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3', 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3'], - ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'cd-e2', 'de-e1', 'df-e8',...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/frequent_pattern_graph_miner.py
Document classes and their methods
from heapq import heappop, heappush import numpy as np def dijkstra( grid: np.ndarray, source: tuple[int, int], destination: tuple[int, int], allow_diagonal: bool, ) -> tuple[float | int, list[tuple[int, int]]]: rows, cols = grid.shape dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] if allow_d...
--- +++ @@ -1,3 +1,10 @@+""" +This script implements the Dijkstra algorithm on a binary grid. +The grid consists of 0s and 1s, where 1 represents +a walkable node and 0 represents an obstacle. +The algorithm finds the shortest path from a start node to a destination node. +Diagonal movement can be allowed or disallowed...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/dijkstra_binary_grid.py
Write reusable docstrings
def __get_demo_graph(index): return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], ...
--- +++ @@ -1,3 +1,13 @@+""" +An edge is a bridge if, after removing it count of connected components in graph will +be increased by one. Bridges represent vulnerabilities in a connected network and are +useful for designing reliable networks. For example, in a wired computer network, an +articulation point indicates t...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/finding_bridges.py
Document all public functions with docstrings
from __future__ import annotations from sys import maxsize from typing import TypeVar T = TypeVar("T") def get_parent_position(position: int) -> int: return (position - 1) // 2 def get_child_left_position(position: int) -> int: return (2 * position) + 1 def get_child_right_position(position: int) -> in...
--- +++ @@ -1,3 +1,11 @@+""" +Prim's (also known as Jarník's) algorithm is a greedy algorithm that finds a minimum +spanning tree for a weighted undirected graph. This means it finds a subset of the +edges that forms a tree that includes every vertex, where the total weight of all the +edges in the tree is minimized. T...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/minimum_spanning_tree_prims2.py
Write clean docstrings for readability
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class Vector: def __init__(self, components: Collection[float] | None = None) -> None: if components is None: components = [] self.__components = list(comp...
--- +++ @@ -1,3 +1,23 @@+""" +Created on Mon Feb 26 14:29:11 2018 + +@author: Christian Bender +@license: MIT-license + +This module contains some useful classes and functions for dealing +with linear algebra in python. + +Overview: + +- class Vector +- function zero_vector(dimension) +- function unit_basis_vector(dime...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/src/lib.py
Write docstrings for utility functions
# floyd_warshall.py def _print_dist(dist, v): print("\nThe shortest path matrix using Floyd Warshall algorithm\n") for i in range(v): for j in range(v): if dist[i][j] != float("inf"): print(int(dist[i][j]), end="\t") else: print("INF", end="\t") ...
--- +++ @@ -1,4 +1,8 @@ # floyd_warshall.py +""" +The problem is to find the shortest distance between all pairs of vertices in a +weighted directed graph that can have negative edge weights. +""" def _print_dist(dist, v): @@ -13,6 +17,21 @@ def floyd_warshall(graph, v): + """ + :param graph: 2D array ca...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/graphs_floyd_warshall.py
Help me comply with documentation standards
import numpy as np from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor class GradientBoostingClassifier: def __init__(self, n_estimators: int = 100, learning_rate: float = 0.1) -> None...
--- +++ @@ -7,11 +7,43 @@ class GradientBoostingClassifier: def __init__(self, n_estimators: int = 100, learning_rate: float = 0.1) -> None: + """ + Initialize a GradientBoostingClassifier. + + Parameters: + - n_estimators (int): The number of weak learners to train. + - learni...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/gradient_boosting_classifier.py
Document this script properly
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used ...
--- +++ @@ -8,6 +8,12 @@ # importing all the required libraries +""" +Implementing logistic regression for classification problem +Helpful resources: +Coursera ML course +https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac +""" import numpy as np from matplotlib import pyplot...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/logistic_regression.py
Auto-generate documentation strings for this file
import numpy as np def power_iteration( input_matrix: np.ndarray, vector: np.ndarray, error_tol: float = 1e-12, max_iterations: int = 100, ) -> tuple[float, np.ndarray]: # Ensure matrix is square. assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1] # Ensure proper dimensionality...
--- +++ @@ -7,6 +7,35 @@ error_tol: float = 1e-12, max_iterations: int = 100, ) -> tuple[float, np.ndarray]: + """ + Power Iteration. + Find the largest eigenvalue and corresponding eigenvector + of matrix input_matrix given a random vector in the same space. + Will work so long as vector has c...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/src/power_iteration.py
Fully document this Python code with docstrings
from typing import Any import numpy as np def is_hermitian(matrix: np.ndarray) -> bool: return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any: v_star = v.conjugate().T v_star_dot = v_star.dot(a) assert isinstance(v_star_dot, np.ndarray) ...
--- +++ @@ -1,3 +1,6 @@+""" +https://en.wikipedia.org/wiki/Rayleigh_quotient +""" from typing import Any @@ -5,10 +8,43 @@ def is_hermitian(matrix: np.ndarray) -> bool: + """ + Checks if a matrix is Hermitian. + >>> import numpy as np + >>> A = np.array([ + ... [2, 2+1j, 4], + ... [2-1j, ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/src/rayleigh_quotient.py
Add missing documentation to my Python functions
from math import cos, sin def scaling(scaling_factor: float) -> list[list[float]]: scaling_factor = float(scaling_factor) return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)] def rotation(angle: float) -> list[list[float]]: c, s = cos(angle), sin(angle) return [[c, -s], [s, c...
--- +++ @@ -1,24 +1,58 @@+""" +2D Transformations are regularly used in Linear Algebra. + +I have added the codes for reflection, projection, scaling and rotation 2D matrices. + +.. code-block:: python + + scaling(5) = [[5.0, 0.0], [0.0, 5.0]] + rotation(45) = [[0.5253219888177297, -0.8509035245341184], + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_algebra/src/transformations_2d.py
Insert docstrings into my code
import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots ca...
--- +++ @@ -17,6 +17,16 @@ # Mean Absolute Error def mae(predict, actual): + """ + Examples(rounded for precision): + >>> actual = [1,2,3];predict = [1,4,3] + >>> float(np.around(mae(predict,actual),decimals = 2)) + 0.67 + + >>> actual = [1,1,1];predict = [1,1,1] + >>> float(mae(predict,actual))...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/scoring_functions.py
Write beginner-friendly docstrings
import logging import numpy as np import scipy.fftpack as fft from scipy.signal import get_window logging.basicConfig(filename=f"{__file__}.log", level=logging.INFO) def mfcc( audio: np.ndarray, sample_rate: int, ftt_size: int = 1024, hop_length: int = 20, mel_filter_num: int = 10, dct_filt...
--- +++ @@ -1,3 +1,61 @@+""" +Mel Frequency Cepstral Coefficients (MFCC) Calculation + +MFCC is an algorithm widely used in audio and speech processing to represent the +short-term power spectrum of a sound signal in a more compact and +discriminative way. It is particularly popular in speech and audio processing +task...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/mfcc.py
Add docstrings for better understanding
# https://en.wikipedia.org/wiki/Set_cover_problem from dataclasses import dataclass from operator import attrgetter @dataclass class Item: weight: int value: int @property def ratio(self) -> float: return self.value / self.weight def fractional_cover(items: list[Item], capacity: int) -> fl...
--- +++ @@ -11,10 +11,70 @@ @property def ratio(self) -> float: + """ + Return the value-to-weight ratio for the item. + + Returns: + float: The value-to-weight ratio for the item. + + Examples: + >>> Item(10, 65).ratio + 6.5 + + >>> Item(20, 100).r...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/greedy_methods/fractional_cover_problem.py
Add docstrings to improve collaboration
import doctest import numpy as np from sklearn.datasets import load_iris from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler def collect_dataset() -> tuple[np.ndarray, np.ndarray]: data = load_iris() return np.array(data.data), np.array(data.target) def apply_pca(data_x:...
--- +++ @@ -1,3 +1,13 @@+""" +Principal Component Analysis (PCA) is a dimensionality reduction technique +used in machine learning. It transforms high-dimensional data into a lower-dimensional +representation while retaining as much variance as possible. + +This implementation follows best practices, including: +- Stan...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/principle_component_analysis.py
Can you add docstrings to this Python file?
import numpy as np class DecisionTree: def __init__(self, depth=5, min_leaf_size=5): self.depth = depth self.decision_boundary = 0 self.left = None self.right = None self.min_leaf_size = min_leaf_size self.prediction = None def mean_squared_error(self, labels,...
--- +++ @@ -1,3 +1,8 @@+""" +Implementation of a basic regression decision tree. +Input data set: The input data set must be 1-dimensional with continuous labels. +Output: The decision tree maps a real number input to a real number output. +""" import numpy as np @@ -12,12 +17,69 @@ self.prediction = None ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/decision_tree.py
Generate NumPy-style docstrings
from __future__ import annotations from collections import defaultdict from enum import Enum from types import TracebackType from typing import Any import numpy as np from typing_extensions import Self # noqa: UP035 class OpType(Enum): ADD = 0 SUB = 1 MUL = 2 DIV = 3 MATMUL = 4 POWER = 5 ...
--- +++ @@ -1,3 +1,11 @@+""" +Demonstration of the Automatic Differentiation (Reverse mode). + +Reference: https://en.wikipedia.org/wiki/Automatic_differentiation + +Author: Poojan Smart +Email: smrtpoojan@gmail.com +""" from __future__ import annotations @@ -11,6 +19,9 @@ class OpType(Enum): + """ + Cla...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/automatic_differentiation.py
Add docstrings to make code maintainable
from typing import Any import numpy as np class Tableau: # Max iteration number to prevent cycling maxiter = 100 def __init__( self, tableau: np.ndarray, n_vars: int, n_artificial_vars: int ) -> None: if tableau.dtype != "float64": raise TypeError("Tableau must have typ...
--- +++ @@ -1,3 +1,17 @@+""" +Python implementation of the simplex algorithm for solving linear programs in +tabular form with +- `>=`, `<=`, and `=` constraints and +- each variable `x1, x2, ...>= 0`. + +See https://gist.github.com/imengus/f9619a568f7da5bc74eaf20169a24d98 for how to +convert linear programs to simplex...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/linear_programming/simplex.py
Add docstrings that explain logic
import numpy as np class Cell: def __init__(self): self.position = (0, 0) self.parent = None self.g = 0 self.h = 0 self.f = 0 """ Overrides equals method because otherwise cell assign will give wrong results. """ def __eq__(self, cell): retur...
--- +++ @@ -1,8 +1,28 @@+""" +The A* algorithm combines features of uniform-cost search and pure heuristic search to +efficiently compute optimal solutions. + +The A* algorithm is a best-first search algorithm in which the cost associated with a +node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the i...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/astar.py
Generate docstrings for this script
#!/usr/bin/env python3 from __future__ import annotations import random import unittest from pprint import pformat from typing import TypeVar import pytest T = TypeVar("T") class GraphAdjacencyMatrix[T]: def __init__( self, vertices: list[T], edges: list[list[T]], directed: bool = True ) -> None: ...
--- +++ @@ -1,4 +1,20 @@ #!/usr/bin/env python3 +""" +Author: Vikram Nithyanandam + +Description: +The following implementation is a robust unweighted Graph data structure +implemented using an adjacency matrix. This vertices and edges of this graph can be +effectively initialized and modified while storing your chosen...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/graphs/graph_adjacency_matrix.py
Write beginner-friendly docstrings
import doctest import numpy as np from numpy import ndarray from sklearn.datasets import load_iris def collect_dataset() -> tuple[ndarray, ndarray]: iris_dataset = load_iris() return np.array(iris_dataset.data), np.array(iris_dataset.target) def compute_pairwise_affinities(data_matrix: ndarray, sigma: flo...
--- +++ @@ -1,3 +1,9 @@+""" +t-distributed stochastic neighbor embedding (t-SNE) + +For more details, see: +https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding +""" import doctest @@ -7,11 +13,38 @@ def collect_dataset() -> tuple[ndarray, ndarray]: + """ + Load the Iris dataset and ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/t_stochastic_neighbour_embedding.py
Document functions with detailed explanations
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def norm_squared(vector: ndarray) -> float: return np.dot(vector, vector) class SVC: def __init__( self, *, regularization: float = np.inf, kernel: str = "linear", ...
--- +++ @@ -4,10 +4,52 @@ def norm_squared(vector: ndarray) -> float: + """ + Return the squared second norm of vector + norm_squared(v) = sum(x * x for x in v) + + Args: + vector (ndarray): input vector + + Returns: + float: squared second norm of vector + + >>> int(norm_squared([1,...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/support_vector_machines.py
Add detailed docstrings explaining each function
from collections import Counter from itertools import combinations def load_data() -> list[list[str]]: return [["milk"], ["milk", "butter"], ["milk", "bread"], ["milk", "bread", "chips"]] def prune(itemset: list, candidates: list, length: int) -> list: itemset_counter = Counter(tuple(item) for item in item...
--- +++ @@ -1,13 +1,50 @@+""" +Apriori Algorithm is a Association rule mining technique, also known as market basket +analysis, aims to discover interesting relationships or associations among a set of +items in a transactional or relational database. + +For example, Apriori Algorithm states: "If a customer buys item A...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/apriori_algorithm.py
Add docstrings for utility scripts
# Copyright (c) 2023 Diego Gasco (diego.gasco99@gmail.com), Diegomangasco on GitHub import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def column_reshape(input_array: np.ndarray) -> np.ndarray: return input_array.reshap...
--- +++ @@ -1,5 +1,12 @@ # Copyright (c) 2023 Diego Gasco (diego.gasco99@gmail.com), Diegomangasco on GitHub +""" +Requirements: + - numpy version 1.21 + - scipy version 1.3.3 +Notes: + - Each column of the features matrix corresponds to a class item +""" import logging @@ -11,6 +18,13 @@ def column_resh...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/dimensionality_reduction.py
Add missing documentation to my Python functions
from statistics import mean, stdev def normalization(data: list, ndigits: int = 3) -> list: # variables for calculation x_min = min(data) x_max = max(data) # normalize data return [round((x - x_min) / (x_max - x_min), ndigits) for x in data] def standardization(data: list, ndigits: int = 3) -> ...
--- +++ @@ -1,8 +1,46 @@+""" +Normalization. + +Wikipedia: https://en.wikipedia.org/wiki/Normalization +Normalization is the process of converting numerical data to a standard range of values. +This range is typically between [0, 1] or [-1, 1]. The equation for normalization is +x_norm = (x - x_min)/(x_max - x_min) whe...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/data_transformations.py
Add docstrings to my Python code
import warnings import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import pairwise_distances warnings.filterwarnings("ignore") TAG = "K-MEANS-CLUST/ " def get_initial_centroids(data, k, seed=None): # useful for obtaining consistent results rng = np.random.defa...
--- +++ @@ -1,3 +1,51 @@+"""README, Author - Anurag Kumar(mailto:anuragkumarak95@gmail.com) +Requirements: + - sklearn + - numpy + - matplotlib +Python: + - 3.5 +Inputs: + - X , a 2D numpy array of features. + - k , number of clusters to create. + - initial_centroids , initial centroid values generated by utilit...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/k_means_clust.py
Create documentation for each function signature
import math def prime_factors(n: int) -> list: if n <= 0: raise ValueError("Only positive integers have prime factors") pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) ...
--- +++ @@ -1,73 +1,122 @@- -import math - - -def prime_factors(n: int) -> list: - if n <= 0: - raise ValueError("Only positive integers have prime factors") - pf = [] - while n % 2 == 0: - pf.append(2) - n = int(n / 2) - for i in range(3, int(math.sqrt(n)) + 1, 2): - while n % i...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/basic_maths.py
Add documentation for all methods
from warnings import simplefilter import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def linear_regression_prediction( train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: ...
--- +++ @@ -1,3 +1,15 @@+""" +this is code for forecasting +but I modified it and used it for safety checker of data +for ex: you have an online shop and for some reason some data are +missing (the amount of data that u expected are not supposed to be) + then we can use it +*ps : 1. ofc we can use normal statist...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/forecasting/run.py
Document all endpoints with docstrings
from __future__ import annotations from dataclasses import dataclass, field @dataclass class TreeNode: name: str count: int parent: TreeNode | None = None children: dict[str, TreeNode] = field(default_factory=dict) node_link: TreeNode | None = None def __repr__(self) -> str: return...
--- +++ @@ -1,3 +1,14 @@+""" +The Frequent Pattern Growth algorithm (FP-Growth) is a widely used data mining +technique for discovering frequent itemsets in large transaction databases. + +It overcomes some of the limitations of traditional methods such as Apriori by +efficiently constructing the FP-Tree + +WIKI: https...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/frequent_pattern_growth.py
Annotate my code with docstrings
from collections import Counter from heapq import nsmallest import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split class KNN: def __init__( self, train_data: np.ndarray[float], train_target: np.ndarray[int], class_labels: list[str], ...
--- +++ @@ -1,3 +1,16 @@+""" +k-Nearest Neighbours (kNN) is a simple non-parametric supervised learning +algorithm used for classification. Given some labelled training data, a given +point is classified using its k nearest neighbours according to some distance +metric. The most commonly occurring label among the neigh...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/k_nearest_neighbours.py
Create Google-style docstrings for my code
from collections.abc import Callable from math import log from os import name, system from random import gauss, seed # Make a training dataset drawn from a gaussian distribution def gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list: seed(1) return [gauss(mean, std_dev) for _ in ...
--- +++ @@ -1,3 +1,47 @@+""" +Linear Discriminant Analysis + + + +Assumptions About Data : + 1. The input variables has a gaussian distribution. + 2. The variance calculated for each input variables by class grouping is the + same. + 3. The mix of classes in your training set is representative of the pro...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/linear_discriminant_analysis.py
Add missing documentation to my Python functions
import math class SelfOrganizingMap: def get_winner(self, weights: list[list[float]], sample: list[int]) -> int: d0 = 0.0 d1 = 0.0 for i in range(len(sample)): d0 += math.pow((sample[i] - weights[0][i]), 2) d1 += math.pow((sample[i] - weights[1][i]), 2) ...
--- +++ @@ -1,9 +1,18 @@+""" +https://en.wikipedia.org/wiki/Self-organizing_map +""" import math class SelfOrganizingMap: def get_winner(self, weights: list[list[float]], sample: list[int]) -> int: + """ + Compute the winning vector by Euclidean distance + + >>> SelfOrganizingMap().get...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/self_organizing_map.py
Write Python docstrings for this snippet
# XGBoost Regressor Example import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def data_handling(data: dict) -> tuple: # Split dataset int...
--- +++ @@ -8,12 +8,25 @@ def data_handling(data: dict) -> tuple: # Split dataset into features and target. Data is features. + """ + >>> data_handling(( + ... {'data':'[ 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 -122.23 ]' + ... ,'target':([4.526])})) + ('[ 8.3252 41. 6.9841269 ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/xgboost_regressor.py
Write clean docstrings for readability
# /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # "numpy", # ] # /// import httpx import numpy as np def collect_dataset(): response = httpx.get( "https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/" "master/Week1/ADRvsRating.csv", timeou...
--- +++ @@ -1,3 +1,12 @@+""" +Linear regression is the most basic type of regression commonly used for +predictive analysis. The idea is pretty simple: we have a dataset and we have +features associated with it. Features should be chosen very cautiously +as they determine how much our model will be able to make future ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/machine_learning/linear_regression.py