instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add standardized docstrings across the file |
from __future__ import annotations
class XORCipher:
def __init__(self, key: int = 0):
# private field
self.__key = key
def encrypt(self, content: str, key: int) -> list[str]:
# precondition
assert isinstance(key, int)
assert isinstance(content, str)
key = k... | --- +++ @@ -1,14 +1,58 @@+"""
+author: Christian Bender
+date: 21.12.2017
+class: XORCipher
+
+This class implements the XOR-cipher algorithm and provides
+some useful methods for encrypting and decrypting strings and
+files.
+
+Overview about methods
+
+- encrypt : list of char
+- decrypt : list of char
+- encrypt_str... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/xor_cipher.py |
Help me document legacy Python code | LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main() -> None:
message = input("Enter message: ")
key = input("Enter key [alphanumeric]: ")
mode = input("Encrypt/Decrypt [e/d]: ")
if mode.lower().startswith("e"):
mode = "encrypt"
translated = encrypt_message(key, message)
elif mode.lo... | --- +++ @@ -18,10 +18,18 @@
def encrypt_message(key: str, message: str) -> str:
+ """
+ >>> encrypt_message('HDarji', 'This is Harshil Darji from Dharmaj.')
+ 'Akij ra Odrjqqs Gaisq muod Mphumrs.'
+ """
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: st... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/vigenere_cipher.py |
Generate consistent documentation across files |
import imageio.v2 as imageio
import numpy as np
def root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float:
return float(np.sqrt(((original - reference) ** 2).mean()))
def normalize_image(
image: np.ndarray, cap: float = 255.0, data_type: np.dtype = np.uint8
) -> np.ndarray:
norma... | --- +++ @@ -1,35 +1,134 @@+"""
+https://en.wikipedia.org/wiki/Image_texture
+https://en.wikipedia.org/wiki/Co-occurrence_matrix#Application_to_image_analysis
+"""
import imageio.v2 as imageio
import numpy as np
def root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float:
+ """Simple imp... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/computer_vision/haralick_descriptors.py |
Document all endpoints with docstrings |
from __future__ import annotations
from enum import Enum
class SIUnit(Enum):
yotta = 24
zetta = 21
exa = 18
peta = 15
tera = 12
giga = 9
mega = 6
kilo = 3
hecto = 2
deca = 1
deci = -1
centi = -2
milli = -3
micro = -6
nano = -9
pico = -12
femto = -1... | --- +++ @@ -1,3 +1,6 @@+"""
+Convert International System of Units (SI) and Binary prefixes
+"""
from __future__ import annotations
@@ -43,6 +46,20 @@ known_prefix: str | SIUnit,
unknown_prefix: str | SIUnit,
) -> float:
+ """
+ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/prefix_conversions.py |
Create structured documentation for my script |
from __future__ import annotations
# fmt: off
TEST_CHARACTER_TO_NUMBER = {
"A": "111", "B": "112", "C": "113", "D": "121", "E": "122", "F": "123", "G": "131",
"H": "132", "I": "133", "J": "211", "K": "212", "L": "213", "M": "221", "N": "222",
"O": "223", "P": "231", "Q": "232", "R": "233", "S": "311", "T"... | --- +++ @@ -1,106 +1,215 @@-
-from __future__ import annotations
-
-# fmt: off
-TEST_CHARACTER_TO_NUMBER = {
- "A": "111", "B": "112", "C": "113", "D": "121", "E": "122", "F": "123", "G": "131",
- "H": "132", "I": "133", "J": "211", "K": "212", "L": "213", "M": "221", "N": "222",
- "O": "223", "P": "231", "Q":... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/trifid_cipher.py |
Fill in missing docstrings in my code |
from string import ascii_uppercase
ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase}
def decimal_to_any(num: int, base: int) -> str:
if isinstance(num, float):
raise TypeError("int() can't convert non-string with explicit base")
if num < 0:
raise ValueError("parameter must be ... | --- +++ @@ -1,3 +1,4 @@+"""Convert a positive Decimal Number to Any Other Representation"""
from string import ascii_uppercase
@@ -5,6 +6,57 @@
def decimal_to_any(num: int, base: int) -> str:
+ """
+ Convert a positive integer to another base as str.
+ >>> decimal_to_any(0, 2)
+ '0'
+ >>> decima... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/decimal_to_any.py |
Create structured documentation for my script | import cv2
import numpy as np
"""
Harris Corner Detector
https://en.wikipedia.org/wiki/Harris_Corner_Detector
"""
class HarrisCorner:
def __init__(self, k: float, window_size: int):
if k in (0.04, 0.06):
self.k = k
self.window_size = window_size
else:
raise Va... | --- +++ @@ -9,6 +9,10 @@
class HarrisCorner:
def __init__(self, k: float, window_size: int):
+ """
+ k : is an empirically determined constant in [0.04,0.06]
+ window_size : neighbourhoods considered
+ """
if k in (0.04, 0.06):
self.k = k
@@ -20,6 +24,11 @@ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/computer_vision/harris_corner.py |
Provide docstrings following PEP 257 | import glob
import os
import random
from string import ascii_lowercase, digits
import cv2
"""
Flip image and bounding box for computer vision task
https://paperswithcode.com/method/randomhorizontalflip
"""
# Params
LABEL_DIR = ""
IMAGE_DIR = ""
OUTPUT_DIR = ""
FLIP_TYPE = 1 # (0 is vertical, 1 is horizontal)
def ... | --- +++ @@ -18,6 +18,11 @@
def main() -> None:
+ """
+ Get images list and annotations list from input dir.
+ Update new images and annotations.
+ Save images and annotations in output dir.
+ """
img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR)
print("Processing...")
new_images, ne... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/computer_vision/flip_augmentation.py |
Write docstrings for this repository | # Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling
# Importing the libraries
import numpy as np
from PIL import Image
# Maxpooling Function
def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray:
arr = np.array(arr)
if arr.shape[0] != arr.shape[1]:
raise ValueErr... | --- +++ @@ -6,6 +6,22 @@
# Maxpooling Function
def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray:
+ """
+ This function is used to perform maxpooling on the input array of 2D matrix(image)
+ Args:
+ arr: numpy array
+ size: size of pooling matrix
+ stride: the number... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/computer_vision/pooling_functions.py |
Write docstrings including parameters and return values |
import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num: int) -> str:
octal = 0
counter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.floor(math.pow(10, counter)))
cou... | --- +++ @@ -1,3 +1,4 @@+"""Convert a Decimal Number to an Octal Number."""
import math
@@ -6,6 +7,12 @@
def decimal_to_octal(num: int) -> str:
+ """Convert a Decimal Number to an Octal Number.
+
+ >>> all(decimal_to_octal(i) == oct(i) for i
+ ... in (0, 2, 8, 64, 65, 216, 255, 256, 512))
+ True... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/decimal_to_octal.py |
Help me comply with documentation standards |
# set decimal value for each hexadecimal digit
values = {
0: "0",
1: "1",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
9: "9",
10: "a",
11: "b",
12: "c",
13: "d",
14: "e",
15: "f",
}
def decimal_to_hexadecimal(decimal: float) -> str:
asse... | --- +++ @@ -1,3 +1,4 @@+"""Convert Base 10 (Decimal) Values to Hexadecimal Representations"""
# set decimal value for each hexadecimal digit
values = {
@@ -21,6 +22,41 @@
def decimal_to_hexadecimal(decimal: float) -> str:
+ """
+ take integer decimal value, return hexadecimal representation as str beginni... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/decimal_to_hexadecimal.py |
Add docstrings that explain inputs and outputs | from enum import Enum
from typing import Literal
class NumberingSystem(Enum):
SHORT = (
(15, "quadrillion"),
(12, "trillion"),
(9, "billion"),
(6, "million"),
(3, "thousand"),
(2, "hundred"),
)
LONG = (
(15, "billiard"),
(9, "milliard"),
... | --- +++ @@ -31,6 +31,16 @@
@classmethod
def max_value(cls, system: str) -> int:
+ """
+ Gets the max value supported by the given number system.
+
+ >>> NumberingSystem.max_value("short") == 10**18 - 1
+ True
+ >>> NumberingSystem.max_value("long") == 10**21 - 1
+ Tr... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/convert_number_to_words.py |
Add docstrings to make code maintainable |
def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float:
return round((float(celsius) * 9 / 5) + 32, ndigits)
def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float:
return round(float(celsius) + 273.15, ndigits)
def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float:
... | --- +++ @@ -1,70 +1,385 @@+"""Convert between different units of temperature"""
def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float:
+ """
+ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places.
+ Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/temperature_conversions.py |
Generate docstrings for this script |
KILOGRAM_CHART: dict[str, float] = {
"kilogram": 1,
"gram": pow(10, 3),
"milligram": pow(10, 6),
"metric-ton": pow(10, -3),
"long-ton": 0.0009842073,
"short-ton": 0.0011023122,
"pound": 2.2046244202,
"stone": 0.1574731728,
"ounce": 35.273990723,
"carrat": 5000,
"atomic-mass-... | --- +++ @@ -1,3 +1,34 @@+"""
+Conversion of weight units.
+
+__author__ = "Anubhav Solanki"
+__license__ = "MIT"
+__version__ = "1.1.0"
+__maintainer__ = "Anubhav Solanki"
+__email__ = "anubhavsolanki0@gmail.com"
+
+USAGE :
+-> Import this file into their respective project.
+-> Use the function weight_conversion() for... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/weight_conversion.py |
Add standardized docstrings across the file |
from typing import NamedTuple
class FromTo(NamedTuple):
from_factor: float
to_factor: float
TYPE_CONVERSION = {
"millimeter": "mm",
"centimeter": "cm",
"meter": "m",
"kilometer": "km",
"inch": "in",
"inche": "in", # Trailing 's' has been stripped off
"feet": "ft",
"foot": "... | --- +++ @@ -1,62 +1,132 @@-
-from typing import NamedTuple
-
-
-class FromTo(NamedTuple):
- from_factor: float
- to_factor: float
-
-
-TYPE_CONVERSION = {
- "millimeter": "mm",
- "centimeter": "cm",
- "meter": "m",
- "kilometer": "km",
- "inch": "in",
- "inche": "in", # Trailing 's' has been st... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/length_conversion.py |
Fully document this Python code with docstrings |
import math
import sys
def read_file_binary(file_path: str) -> str:
result = ""
try:
with open(file_path, "rb") as binary_file:
data = binary_file.read()
for dat in data:
curr_byte = f"{dat:08b}"
result += curr_byte
return result
except OSError:... | --- +++ @@ -1,9 +1,16 @@+"""
+One of the several implementations of Lempel-Ziv-Welch decompression algorithm
+https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch
+"""
import math
import sys
def read_file_binary(file_path: str) -> str:
+ """
+ Reads given file as bytes and returns them as a lon... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_compression/lempel_ziv_decompress.py |
Help me write clear docstrings | # https://www.geeksforgeeks.org/convert-ip-address-to-integer-and-vice-versa/
def ipv4_to_decimal(ipv4_address: str) -> int:
octets = [int(octet) for octet in ipv4_address.split(".")]
if len(octets) != 4:
raise ValueError("Invalid IPv4 address format")
decimal_ipv4 = 0
for octet in octets:
... | --- +++ @@ -2,6 +2,28 @@
def ipv4_to_decimal(ipv4_address: str) -> int:
+ """
+ Convert an IPv4 address to its decimal representation.
+
+ Args:
+ ip_address: A string representing an IPv4 address (e.g., "192.168.0.1").
+
+ Returns:
+ int: The decimal representation of the IP address.
+
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/ipv4_conversion.py |
Add inline docstrings for readability |
ENERGY_CONVERSION: dict[str, float] = {
"joule": 1.0,
"kilojoule": 1_000,
"megajoule": 1_000_000,
"gigajoule": 1_000_000_000,
"wattsecond": 1.0,
"watthour": 3_600,
"kilowatthour": 3_600_000,
"newtonmeter": 1.0,
"calorie_nutr": 4_186.8,
"kilocalorie_nutr": 4_186_800.00,
"elec... | --- +++ @@ -1,3 +1,29 @@+"""
+Conversion of energy units.
+
+Available units: joule, kilojoule, megajoule, gigajoule,\
+ wattsecond, watthour, kilowatthour, newtonmeter, calorie_nutr,\
+ kilocalorie_nutr, electronvolt, britishthermalunit_it, footpound
+
+USAGE :
+-> Import this file into their respective ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/energy_conversions.py |
Add verbose docstrings with examples |
import random
import time
def cross(items_a, items_b):
return [a + b for a in items_a for b in items_b]
digits = "123456789"
rows = "ABCDEFGHI"
cols = digits
squares = cross(rows, cols)
unitlist = (
[cross(rows, c) for c in cols]
+ [cross(r, cols) for r in rows]
+ [cross(rs, cs) for rs in ("ABC", "... | --- +++ @@ -1,9 +1,30 @@+"""
+Please do not modify this file! It is published at https://norvig.com/sudoku.html with
+only minimal changes to work with modern versions of Python. If you have improvements,
+please make them in a separate file.
+"""
import random
import time
def cross(items_a, items_b):
+ "... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/sudoku_solver.py |
Write reusable docstrings | from __future__ import annotations
import sys
class Letter:
def __init__(self, letter: str, freq: int):
self.letter: str = letter
self.freq: int = freq
self.bitstring: dict[str, str] = {}
def __repr__(self) -> str:
return f"{self.letter}:{self.freq}"
class TreeNode:
def... | --- +++ @@ -21,6 +21,10 @@
def parse_file(file_path: str) -> list[Letter]:
+ """
+ Read the file and build a dict of all letters and their
+ frequencies, then convert the dict into a list of Letters.
+ """
chars: dict[str, int] = {}
with open(file_path) as f:
while True:
@@ -32,6 +36,... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_compression/huffman.py |
Add docstrings for internal functions |
from __future__ import annotations
class Node:
def __init__(self, value: int) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
class BinaryTreePathSum:
target: int
def __init__(self) -> None:
self.paths = 0
def depth_first_... | --- +++ @@ -1,8 +1,19 @@+"""
+Given the root of a binary tree and an integer target,
+find the number of paths where the sum of the values
+along the path equals target.
+
+
+Leetcode reference: https://leetcode.com/problems/path-sum-iii/
+"""
from __future__ import annotations
class Node:
+ """
+ A Node ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/binary_tree_path_sum.py |
Document this code for team use |
speed_chart: dict[str, float] = {
"km/h": 1.0,
"m/s": 3.6,
"mph": 1.609344,
"knot": 1.852,
}
speed_chart_inverse: dict[str, float] = {
"km/h": 1.0,
"m/s": 0.277777778,
"mph": 0.621371192,
"knot": 0.539956803,
}
def convert_speed(speed: float, unit_from: str, unit_to: str) -> float:
... | --- +++ @@ -1,3 +1,11 @@+"""
+Convert speed units
+
+https://en.wikipedia.org/wiki/Kilometres_per_hour
+https://en.wikipedia.org/wiki/Miles_per_hour
+https://en.wikipedia.org/wiki/Knot_(unit)
+https://en.wikipedia.org/wiki/Metre_per_second
+"""
speed_chart: dict[str, float] = {
"km/h": 1.0,
@@ -15,6 +23,39 @@
... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/speed_conversions.py |
Add structured docstrings to improve clarity |
from typing import NamedTuple
class FromTo(NamedTuple):
from_factor: float
to_factor: float
PRESSURE_CONVERSION = {
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.1013... | --- +++ @@ -1,43 +1,87 @@-
-from typing import NamedTuple
-
-
-class FromTo(NamedTuple):
- from_factor: float
- to_factor: float
-
-
-PRESSURE_CONVERSION = {
- "atm": FromTo(1, 1),
- "pascal": FromTo(0.0000098, 101325),
- "bar": FromTo(0.986923, 1.01325),
- "kilopascal": FromTo(0.00986923, 101.325),
-... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/pressure_conversions.py |
Add verbose docstrings with examples | from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Node:
data: int
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[int]:
if self.left:
yield from self.left
yield self... | --- +++ @@ -40,6 +40,14 @@
@classmethod
def small_tree(cls) -> BinaryTree:
+ """
+ Return a small binary tree with 3 nodes.
+ >>> binary_tree = BinaryTree.small_tree()
+ >>> len(binary_tree)
+ 3
+ >>> list(binary_tree)
+ [1, 2, 3]
+ """
binary_... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/basic_binary_tree.py |
Generate consistent docstrings |
def octal_to_binary(octal_number: str) -> str:
if not octal_number:
raise ValueError("Empty string was passed to the function")
binary_number = ""
octal_digits = "01234567"
for digit in octal_number:
if digit not in octal_digits:
raise ValueError("Non-octal value was passe... | --- +++ @@ -1,6 +1,34 @@+"""
+* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+* Description: Convert a Octal number to Binary.
+
+References for better understanding:
+https://en.wikipedia.org/wiki/Binary_number
+https://en.wikipedia.org/wiki/Octal
+"""
def octal_to_binary(octal_number: s... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/octal_to_binary.py |
Add docstrings to existing functions |
from dataclasses import dataclass
__version__ = "0.1"
__author__ = "Lucia Harcekova"
@dataclass
class Token:
offset: int
length: int
indicator: str
def __repr__(self) -> str:
return f"({self.offset}, {self.length}, {self.indicator})"
class LZ77Compressor:
def __init__(self, window_s... | --- +++ @@ -1,3 +1,32 @@+"""
+LZ77 compression algorithm
+- lossless data compression published in papers by Abraham Lempel and Jacob Ziv in 1977
+- also known as LZ1 or sliding-window compression
+- form the basis for many variations including LZW, LZSS, LZMA and others
+
+It uses a “sliding window” method. Within the... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_compression/lz77.py |
Add docstrings for better understanding | ROMAN = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
def roman_to_int(roman: str) -> int:
vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, ... | --- +++ @@ -1,45 +1,61 @@-ROMAN = [
- (1000, "M"),
- (900, "CM"),
- (500, "D"),
- (400, "CD"),
- (100, "C"),
- (90, "XC"),
- (50, "L"),
- (40, "XL"),
- (10, "X"),
- (9, "IX"),
- (5, "V"),
- (4, "IV"),
- (1, "I"),
-]
-
-
-def roman_to_int(roman: str) -> int:
- vals = {"I": 1, "V... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/roman_numerals.py |
Add docstrings that explain logic |
from __future__ import annotations
from enum import Enum, unique
from typing import TypeVar
# Create a generic variable that can be 'Enum', or any subclass.
T = TypeVar("T", bound="Enum")
@unique
class BinaryUnit(Enum):
yotta = 80
zetta = 70
exa = 60
peta = 50
tera = 40
giga = 30
mega =... | --- +++ @@ -1,3 +1,12 @@+"""
+* Author: Manuel Di Lullo (https://github.com/manueldilullo)
+* Description: Convert a number to use the correct SI or Binary unit prefix.
+
+Inspired by prefix_conversion.py file in this repository by lance-pyles
+
+URL: https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes
+URL... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/prefix_conversions_string.py |
Document this code for team use |
def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]:
if hue < 0 or hue > 360:
raise Exception("hue should be between 0 and 360")
if saturation < 0 or saturation > 1:
raise Exception("saturation should be between 0 and 1")
if value < 0 or value > 1:
raise Exce... | --- +++ @@ -1,6 +1,44 @@+"""
+The RGB color model is an additive color model in which red, green, and blue light
+are added together in various ways to reproduce a broad array of colors. The name
+of the model comes from the initials of the three additive primary colors, red,
+green, and blue. Meanwhile, the HSV repres... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/rgb_hsv_conversion.py |
Add clean documentation to messy code |
from __future__ import annotations
import math
import random
from typing import Any
class MyQueue:
def __init__(self) -> None:
self.data: list[Any] = []
self.head: int = 0
self.tail: int = 0
def is_empty(self) -> bool:
return self.head == self.tail
def push(self, data: ... | --- +++ @@ -1,3 +1,10 @@+"""
+Implementation of an auto-balanced binary tree!
+For doctests run following command:
+python3 -m doctest -v avl_tree.py
+For testing run:
+python avl_tree.py
+"""
from __future__ import annotations
@@ -78,6 +85,16 @@
def right_rotation(node: MyNode) -> MyNode:
+ r"""
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/avl_tree.py |
Add verbose docstrings with examples |
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Index2DArrayIterator:
matrix: list[list[int]]
def __iter__(self) -> Iterator[int]:
for row in self.matrix:
yield from row
def index_2d_array_in_1d(array: list[list[int]], index: int) -> int:
row... | --- +++ @@ -1,3 +1,24 @@+"""
+Retrieves the value of an 0-indexed 1D index from a 2D array.
+There are two ways to retrieve value(s):
+
+1. Index2DArrayIterator(matrix) -> Iterator[int]
+This iterator allows you to iterate through a 2D array by passing in the matrix and
+calling next(your_iterator). You can also use th... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/index_2d_array_in_1d.py |
Provide clean and structured docstrings |
class CoordinateCompressor:
def __init__(self, arr: list[int | float | str]) -> None:
# A dictionary to store compressed coordinates
self.coordinate_map: dict[int | float | str, int] = {}
# A list to store reverse mapping
self.reverse_map: list[int | float | str] = [-1] * len(ar... | --- +++ @@ -1,8 +1,51 @@+"""
+Assumption:
+ - The values to compress are assumed to be comparable,
+ values can be sorted and compared with '<' and '>' operators.
+"""
class CoordinateCompressor:
+ """
+ A class for coordinate compression.
+
+ This class allows you to compress and decompress a lis... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_compression/coordinate_compression.py |
Generate consistent docstrings |
class PrefixSum:
def __init__(self, array: list[int]) -> None:
len_array = len(array)
self.prefix_sum = [0] * len_array
if len_array > 0:
self.prefix_sum[0] = array[0]
for i in range(1, len_array):
self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i]
... | --- +++ @@ -1,3 +1,10 @@+"""
+Author : Alexander Pantyukhin
+Date : November 3, 2022
+
+Implement the class of prefix sum with useful functions based on it.
+
+"""
class PrefixSum:
@@ -12,6 +19,34 @@ self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i]
def get_sum(self, start: int, end: in... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/prefix_sum.py |
Document helper functions with docstrings |
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:
return round(float(moles / volume) * nfactor)
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
return round(float((moles * 0.0821 * temperature) / (volume)))
def moles_to_volume(pressure: float, ... | --- +++ @@ -1,24 +1,91 @@+"""
+Functions useful for doing molecular chemistry:
+* molarity_to_normality
+* moles_to_pressure
+* moles_to_volume
+* pressure_and_volume_to_temperature
+"""
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:
+ """
+ Convert molarity to normality.
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/molecular_chemistry.py |
Add clean documentation to messy code |
def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int):
if not root or root not in binary_tree_mirror_dictionary:
return
left_child, right_child = binary_tree_mirror_dictionary[root][:2]
binary_tree_mirror_dictionary[root] = [right_child, left_child]
binary_tree_mirror_dic... | --- +++ @@ -1,3 +1,7 @@+"""
+Problem Description:
+Given a binary tree, return its mirror.
+"""
def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int):
@@ -10,6 +14,20 @@
def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:
+ """
+ >>> binary_tree_mirror({ 1: [2,3], 2: [... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/binary_tree_mirror.py |
Add return value explanations in docstrings |
time_chart: dict[str, float] = {
"seconds": 1.0,
"minutes": 60.0, # 1 minute = 60 sec
"hours": 3600.0, # 1 hour = 60 minutes = 3600 seconds
"days": 86400.0, # 1 day = 24 hours = 1440 min = 86400 sec
"weeks": 604800.0, # 1 week=7d=168hr=10080min = 604800 sec
"months": 2629800.0, # Approxima... | --- +++ @@ -1,3 +1,11 @@+"""
+A unit of time is any particular time interval, used as a standard way of measuring or
+expressing duration. The base unit of time in the International System of Units (SI),
+and by extension most of the Western world, is the second, defined as about 9 billion
+oscillations of the caesium... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/time_conversions.py |
Create docstrings for each class method |
from typing import NamedTuple
class FromTo(NamedTuple):
from_factor: float
to_factor: float
METRIC_CONVERSION = {
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic ... | --- +++ @@ -1,42 +1,83 @@-
-from typing import NamedTuple
-
-
-class FromTo(NamedTuple):
- from_factor: float
- to_factor: float
-
-
-METRIC_CONVERSION = {
- "cubic meter": FromTo(1, 1),
- "litre": FromTo(0.001, 1000),
- "kilolitre": FromTo(1, 1),
- "gallon": FromTo(0.00454, 264.172),
- "cubic yard... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/volume_conversions.py |
Include argument descriptions in docstrings |
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Node:
data: float
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[float]:
if self.left:
yield from self.left
yield... | --- +++ @@ -1,3 +1,18 @@+"""
+Given the root of a binary tree, determine if it is a valid binary search tree (BST).
+
+A valid binary search tree is defined as follows:
+- The left subtree of a node contains only nodes with keys less than the node's key.
+- The right subtree of a node contains only nodes with keys grea... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/is_sorted.py |
Add clean documentation to messy code |
def product_sum(arr: list[int | list], depth: int) -> int:
total_sum = 0
for ele in arr:
total_sum += product_sum(ele, depth + 1) if isinstance(ele, list) else ele
return total_sum * depth
def product_sum_array(array: list[int | list]) -> int:
return product_sum(array, 1)
if __name__ == "_... | --- +++ @@ -1,6 +1,63 @@+"""
+Calculate the Product Sum from a Special Array.
+reference: https://dev.to/sfrasica/algorithms-product-sum-from-an-array-dc6
+
+Python doctests can be run with the following command:
+python -m doctest -v product_sum.py
+
+Calculate the product sum of a "special" array which can contain in... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/product_sum.py |
Create Google-style docstrings for my code |
def equilibrium_index(arr: list[int]) -> int:
total_sum = sum(arr)
left_sum = 0
for i, value in enumerate(arr):
total_sum -= value
if left_sum == total_sum:
return i
left_sum += value
return -1
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,45 @@+"""
+Find the Equilibrium Index of an Array.
+Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
+
+Python doctest can be run with the following command:
+python -m doctest -v equilibrium_index_in_array.py
+
+Given a sequence arr[] of size n, this function returns
+an equil... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/equilibrium_index_in_array.py |
Create documentation for each function signature |
def partition(arr: list[int], low: int, high: int) -> int:
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] >= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def kth_largest_element(arr: l... | --- +++ @@ -1,6 +1,36 @@+"""
+Given an array of integers and an integer k, find the kth largest element in the array.
+
+https://stackoverflow.com/questions/251781
+"""
def partition(arr: list[int], low: int, high: int) -> int:
+ """
+ Partitions list based on the pivot element.
+
+ This function rearrang... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/kth_largest_element.py |
Add docstrings that explain purpose and usage |
from __future__ import annotations
from dataclasses import dataclass
from typing import NamedTuple
@dataclass
class TreeNode:
data: int
left: TreeNode | None = None
right: TreeNode | None = None
class CoinsDistribResult(NamedTuple):
moves: int
excess: int
def distribute_coins(root: TreeNode ... | --- +++ @@ -1,3 +1,41 @@+"""
+Author : Alexander Pantyukhin
+Date : November 7, 2022
+
+Task:
+You are given a tree root of a binary tree with n nodes, where each node has
+node.data coins. There are exactly n coins in whole tree.
+
+In one move, we may choose two adjacent nodes and move one coin from one node
+to ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/distribute_coins.py |
Add docstrings that explain logic | # https://en.wikipedia.org/wiki/Run-length_encoding
def run_length_encode(text: str) -> list:
encoded = []
count = 1
for i in range(len(text)):
if i + 1 < len(text) and text[i] == text[i + 1]:
count += 1
else:
encoded.append((text[i], count))
count = 1
... | --- +++ @@ -2,6 +2,17 @@
def run_length_encode(text: str) -> list:
+ """
+ Performs Run Length Encoding
+ >>> run_length_encode("AAAABBBCCDAA")
+ [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)]
+ >>> run_length_encode("A")
+ [('A', 1)]
+ >>> run_length_encode("AA")
+ [('A', 2)]
+ >>> r... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_compression/run_length_encoding.py |
Document my Python code with docstrings |
from __future__ import annotations
from typing import TypedDict
class BWTTransformDict(TypedDict):
bwt_string: str
idx_original_string: int
def all_rotations(s: str) -> list[str]:
if not isinstance(s, str):
raise TypeError("The parameter s type must be str.")
return [s[i:] + s[:i] for i i... | --- +++ @@ -1,3 +1,15 @@+"""
+https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform
+
+The Burrows-Wheeler transform (BWT, also called block-sorting compression)
+rearranges a character string into runs of similar characters. This is useful
+for compression, since it tends to be easy to compress a string that... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_compression/burrows_wheeler.py |
Document this script properly | from itertools import combinations
def find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]:
return [
list(x)
for x in sorted({abc for abc in combinations(sorted(nums), 3) if not sum(abc)})
]
def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]:
target_sum = 0
... | --- +++ @@ -2,6 +2,22 @@
def find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]:
+ """
+ Given a list of integers, return elements a, b, c such that a + b + c = 0.
+ Args:
+ nums: list of integers
+ Returns:
+ list of lists of integers where sum(each_list) == 0
+ Examples:
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/find_triplets_with_0_sum.py |
Add docstrings that explain inputs and outputs | def permute_recursive(nums: list[int]) -> list[list[int]]:
result: list[list[int]] = []
if len(nums) == 0:
return [[]]
for _ in range(len(nums)):
n = nums.pop(0)
permutations = permute_recursive(nums.copy())
for perm in permutations:
perm.append(n)
result.... | --- +++ @@ -1,4 +1,10 @@ def permute_recursive(nums: list[int]) -> list[list[int]]:
+ """
+ Return all permutations.
+
+ >>> permute_recursive([1, 2, 3])
+ [[3, 2, 1], [2, 3, 1], [1, 3, 2], [3, 1, 2], [2, 1, 3], [1, 2, 3]]
+ """
result: list[list[int]] = []
if len(nums) == 0:
return [[... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/permutations.py |
Document my Python code with docstrings | class MaxFenwickTree:
def __init__(self, size: int) -> None:
self.size = size
self.arr = [0] * size
self.tree = [0] * size
@staticmethod
def get_next(index: int) -> int:
return index | (index + 1)
@staticmethod
def get_prev(index: int) -> int:
return (index... | --- +++ @@ -1,19 +1,80 @@ class MaxFenwickTree:
+ """
+ Maximum Fenwick Tree
+
+ More info: https://cp-algorithms.com/data_structures/fenwick.html
+ ---------
+ >>> ft = MaxFenwickTree(5)
+ >>> ft.query(0, 5)
+ 0
+ >>> ft.update(4, 100)
+ >>> ft.query(0, 5)
+ 100
+ >>> ft.update(4, 0)
+... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/maximum_fenwick_tree.py |
Help me comply with documentation standards | def rotate_array(arr: list[int], steps: int) -> list[int]:
n = len(arr)
if n == 0:
return arr
steps = steps % n
if steps < 0:
steps += n
def reverse(start: int, end: int) -> None:
while start < end:
arr[start], arr[end] = arr[end], arr[start]
star... | --- +++ @@ -1,4 +1,24 @@ def rotate_array(arr: list[int], steps: int) -> list[int]:
+ """
+ Rotates a list to the right by steps positions.
+
+ Parameters:
+ arr (List[int]): The list of integers to rotate.
+ steps (int): Number of positions to rotate. Can be negative for left rotation.
+
+ Returns:
+... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/rotate_array.py |
Create structured documentation for my script |
import math
import os
import sys
def read_file_binary(file_path: str) -> str:
result = ""
try:
with open(file_path, "rb") as binary_file:
data = binary_file.read()
for dat in data:
curr_byte = f"{dat:08b}"
result += curr_byte
return result
excep... | --- +++ @@ -1,3 +1,7 @@+"""
+One of the several implementations of Lempel-Ziv-Welch compression algorithm
+https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch
+"""
import math
import os
@@ -5,6 +9,9 @@
def read_file_binary(file_path: str) -> str:
+ """
+ Reads given file as bytes and returns th... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_compression/lempel_ziv.py |
Add docstrings including usage examples |
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Node:
data: int
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[int]:
if self.left:
yield from self.left
yield sel... | --- +++ @@ -1,3 +1,8 @@+"""
+Is a binary tree a sum tree where the value of every non-leaf node is equal to the sum
+of the values of its left and right subtrees?
+https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree
+"""
from __future__ import annotations
@@ -12,6 +17,14 @@ right: Node | None... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/is_sum_tree.py |
Replace inline comments with docstrings |
from math import log2
def build_sparse_table(number_list: list[int]) -> list[list[int]]:
if not number_list:
raise ValueError("empty number list not allowed")
length = len(number_list)
# Initialise sparse_table -- sparse_table[j][i] represents the minimum value of the
# subset of length (2 *... | --- +++ @@ -1,8 +1,33 @@+"""
+Sparse table is a data structure that allows answering range queries on
+a static number list, i.e. the elements do not change throughout all the queries.
+
+The implementation below will solve the problem of Range Minimum Query:
+Finding the minimum value of a subset [L..R] of a static nu... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/sparse_table.py |
Document this module using docstrings | #!/usr/bin/env python3
from itertools import combinations
def pairs_with_sum(arr: list, req_sum: int) -> int:
return len([1 for a, b in combinations(arr, 2) if a + b == req_sum])
if __name__ == "__main__":
from doctest import testmod
testmod() | --- +++ @@ -1,14 +1,29 @@ #!/usr/bin/env python3
+"""
+Given an array of integers and an integer req_sum, find the number of pairs of array
+elements whose sum is equal to req_sum.
+
+https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0
+"""
from itertools import combinations
def pairs... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/pairs_with_given_sum.py |
Write docstrings that follow conventions | import math
class SegmentTree:
def __init__(self, a):
self.A = a
self.N = len(self.A)
self.st = [0] * (
4 * self.N
) # approximate the overall size of segment tree with array N
if self.N:
self.build(1, 0, self.N - 1)
def left(self, idx):
... | --- +++ @@ -12,9 +12,27 @@ self.build(1, 0, self.N - 1)
def left(self, idx):
+ """
+ Returns the left child index for a given index in a binary tree.
+
+ >>> s = SegmentTree([1, 2, 3])
+ >>> s.left(1)
+ 2
+ >>> s.left(2)
+ 4
+ """
retur... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/segment_tree.py |
Write docstrings for utility functions |
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
if not nums1 and not nums2:
raise ValueError("Both input arrays are empty.")
# Merge the arrays into a single sorted array.
merged = sorted(nums1 + nums2)
total = len(merged)
if total % 2 == 1: # If the total nu... | --- +++ @@ -1,6 +1,43 @@+"""
+https://www.enjoyalgorithms.com/blog/median-of-two-sorted-arrays
+"""
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
+ """
+ Find the median of two arrays.
+
+ Args:
+ nums1: The first array.
+ nums2: The second array.
+
+ Returns... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/arrays/median_two_array.py |
Generate docstrings for script automation |
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from typing import Any, Self
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
parent: Node | None = None # Added in order to delete a node easier
... | --- +++ @@ -1,3 +1,93 @@+r"""
+A binary search Tree
+
+Example
+ 8
+ / \
+ 3 10
+ / \ \
+ 1 6 14
+ / \ /
+ 4 7 13
+
+>>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7)
+>>> print(" ".join(repr(i.value) for i in t.tr... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/binary_search_tree.py |
Generate docstrings for this script |
from __future__ import annotations
import unittest
from collections.abc import Iterator
import pytest
class Node:
def __init__(self, label: int, parent: Node | None) -> None:
self.label = label
self.parent = parent
self.left: Node | None = None
self.right: Node | None = None
c... | --- +++ @@ -1,3 +1,12 @@+"""
+This is a python3 implementation of binary search tree using recursion
+
+To run tests:
+python -m unittest binary_search_tree_recursive.py
+
+To run an example:
+python binary_search_tree_recursive.py
+"""
from __future__ import annotations
@@ -20,12 +29,46 @@ self.root: Node... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/binary_search_tree_recursive.py |
Add docstrings explaining edge cases |
from __future__ import annotations
from collections.abc import Iterator
class Node:
def __init__(self, value: int) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
class BinaryTreeNodeSum:
def __init__(self, tree: Node) -> None:
sel... | --- +++ @@ -1,34 +1,75 @@-
-from __future__ import annotations
-
-from collections.abc import Iterator
-
-
-class Node:
-
- def __init__(self, value: int) -> None:
- self.value = value
- self.left: Node | None = None
- self.right: Node | None = None
-
-
-class BinaryTreeNodeSum:
-
- def __ini... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/binary_tree_node_sum.py |
Create docstrings for API functions |
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node
def make_set(x: Node) -> None:
# rank is the distance from x to its' parent
# root's rank is 0
x.rank = 0
x.parent = x
def union_set(x: Node, y: Node) -> None:
x, y ... | --- +++ @@ -1,64 +1,85 @@-
-
-class Node:
- def __init__(self, data: int) -> None:
- self.data = data
- self.rank: int
- self.parent: Node
-
-
-def make_set(x: Node) -> None:
- # rank is the distance from x to its' parent
- # root's rank is 0
- x.rank = 0
- x.parent = x
-
-
-def unio... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/disjoint_set/disjoint_set.py |
Annotate my code with docstrings | from copy import deepcopy
class FenwickTree:
def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None:
if arr is None and size is not None:
self.size = size
self.tree = [0] * size
elif arr is not None:
self.init(arr)
else:
... | --- +++ @@ -2,8 +2,20 @@
class FenwickTree:
+ """
+ Fenwick Tree
+
+ More info: https://en.wikipedia.org/wiki/Fenwick_tree
+ """
def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None:
+ """
+ Constructor for the Fenwick tree
+
+ Parameters:
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/fenwick_tree.py |
Help me document legacy Python code |
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: TreeNode | None = None
right: TreeNode | None = None
def make_tree() -> TreeNode:
return TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7... | --- +++ @@ -1,3 +1,10 @@+r"""
+Problem: Given root of a binary tree, return the:
+1. binary-tree-right-side-view
+2. binary-tree-left-side-view
+3. binary-tree-top-side-view
+4. binary-tree-bottom-side-view
+"""
from __future__ import annotations
@@ -13,14 +20,36 @@
def make_tree() -> TreeNode:
+ """
+ >... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/diff_views_of_binary_tree.py |
Write documentation strings for class attributes | from __future__ import annotations
from collections import deque
from collections.abc import Generator
from dataclasses import dataclass
# https://en.wikipedia.org/wiki/Tree_traversal
@dataclass
class Node:
data: int
left: Node | None = None
right: Node | None = None
def make_tree() -> Node | None:
... | --- +++ @@ -1,150 +1,213 @@-from __future__ import annotations
-
-from collections import deque
-from collections.abc import Generator
-from dataclasses import dataclass
-
-
-# https://en.wikipedia.org/wiki/Tree_traversal
-@dataclass
-class Node:
- data: int
- left: Node | None = None
- right: Node | None = No... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/binary_tree_traversals.py |
Generate docstrings for exported functions |
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
data: int
left: Node | None = None
right: Node | None = None
def depth(self) -> int:
left_depth = self.left.depth() if self.left else 0
right_depth = self.right.depth() if self.right else 0
... | --- +++ @@ -1,3 +1,7 @@+"""
+The diameter/width of a tree is defined as the number of nodes on the longest path
+between two end nodes.
+"""
from __future__ import annotations
@@ -11,11 +15,37 @@ right: Node | None = None
def depth(self) -> int:
+ """
+ >>> root = Node(1)
+ >>> root... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/diameter_of_binary_tree.py |
Document my Python code with docstrings |
class BinaryTreeNode:
def __init__(self, data: int) -> None:
self.data = data
self.left_child: BinaryTreeNode | None = None
self.right_child: BinaryTreeNode | None = None
def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None:
if node is None:
node ... | --- +++ @@ -1,6 +1,12 @@+"""
+Illustrate how to implement inorder traversal in binary search tree.
+Author: Gurneet Singh
+https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
+"""
class BinaryTreeNode:
+ """Defining the structure of BinaryTreeNode"""
def __init__(self, data: int... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/inorder_tree_traversal_2022.py |
Create docstrings for each class method |
from __future__ import annotations
class TreeNode:
def __init__(self, data: int) -> None:
self.data = data
self.left: TreeNode | None = None
self.right: TreeNode | None = None
def build_tree() -> TreeNode:
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
... | --- +++ @@ -1,8 +1,24 @@+"""
+Binary Tree Flattening Algorithm
+
+This code defines an algorithm to flatten a binary tree into a linked list
+represented using the right pointers of the tree nodes. It uses in-place
+flattening and demonstrates the flattening process along with a display
+function to visualize the flatt... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py |
Add missing documentation to my Python functions |
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[int]:
if self.left:
yield from self.left
yield s... | --- +++ @@ -1,3 +1,8 @@+"""
+Given the root of a binary tree, mirror the tree, and return its root.
+
+Leetcode problem reference: https://leetcode.com/problems/mirror-binary-tree/
+"""
from __future__ import annotations
@@ -7,6 +12,9 @@
@dataclass
class Node:
+ """
+ A Node has value variable and pointer... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/mirror_binary_tree.py |
Add well-formatted docstrings | from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class TreeNode:
value: int = 0
left: TreeNode | None = None
right: TreeNode | None = None
def __post_init__(self):
if not isinstance(self.value, int):
raise TypeE... | --- +++ @@ -6,6 +6,14 @@
@dataclass
class TreeNode:
+ """
+ A binary tree node has a value, left child, and right child.
+
+ Props:
+ value: The value of the node.
+ left: The left child of the node.
+ right: The right child of the node.
+ """
value: int = 0
left: TreeNod... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/serialize_deserialize_binary_tree.py |
Document helper functions with docstrings | from __future__ import annotations
import sys
from dataclasses import dataclass
INT_MIN = -sys.maxsize + 1
INT_MAX = sys.maxsize - 1
@dataclass
class TreeNode:
val: int = 0
left: TreeNode | None = None
right: TreeNode | None = None
def max_sum_bst(root: TreeNode | None) -> int:
ans: int = 0
d... | --- +++ @@ -15,9 +15,44 @@
def max_sum_bst(root: TreeNode | None) -> int:
+ """
+ The solution traverses a binary tree to find the maximum sum of
+ keys in any subtree that is a Binary Search Tree (BST). It uses
+ recursion to validate BST properties and calculates sums, returning
+ the highest sum f... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/maximum_sum_bst.py |
Document functions with detailed explanations |
from __future__ import annotations
from collections.abc import Callable
from typing import Any, TypeVar
T = TypeVar("T")
class SegmentTree[T]:
def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None:
any_type: Any | T = None
self.N: int = len(arr)
self.st: list[T] = [any_typ... | --- +++ @@ -1,3 +1,40 @@+"""
+A non-recursive Segment Tree implementation with range query and single element update,
+works virtually with any list of the same type of elements with a "commutative"
+combiner.
+
+Explanation:
+https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/
+https://www.geeksf... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/non_recursive_segment_tree.py |
Add verbose docstrings with examples | from __future__ import annotations
import math
class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
se... | --- +++ @@ -13,9 +13,27 @@ self.flag = [0 for i in range(4 * size)] # flag for lazy update
def left(self, idx: int) -> int:
+ """
+ >>> segment_tree = SegmentTree(15)
+ >>> segment_tree.left(1)
+ 2
+ >>> segment_tree.left(2)
+ 4
+ >>> segment_tree.left(12... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/lazy_segment_tree.py |
Improve my code by adding docstrings |
"""
Our Contribution:
Basically we Create the 2 function:
1. catalan_number(node_count: int) -> int
Returns the number of possible binary search trees for n nodes.
2. binary_tree_count(node_count: int) -> int
Returns the number of possible binary trees for n nodes.
"""
def binomial_coefficien... | --- +++ @@ -1,3 +1,11 @@+"""
+Hey, we are going to find an exciting number called Catalan number which is use to find
+the number of possible binary search trees from tree of a given number of nodes.
+
+We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i)
+
+Further details at Wikipedia: https://en.wikiped... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/number_of_possible_binary_trees.py |
Write docstrings describing each step | from collections.abc import Callable
class Heap:
def __init__(self, key: Callable | None = None) -> None:
# Stores actual heap items.
self.arr: list = []
# Stores indexes of each item for supporting updates and deletion.
self.pos_map: dict = {}
# Stores current size of hea... | --- +++ @@ -2,6 +2,10 @@
class Heap:
+ """
+ A generic Heap class, can be used as min or max by passing the key function
+ accordingly.
+ """
def __init__(self, key: Callable | None = None) -> None:
# Stores actual heap items.
@@ -15,17 +19,21 @@ self.key = key or (lambda x: x)
... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/heap/heap_generic.py |
Add docstrings to improve readability |
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[int]:
if self.left:
yield from self.left
yield self... | --- +++ @@ -1,3 +1,14 @@+"""
+In a binary search tree (BST):
+* The floor of key 'k' is the maximum value that is smaller than or equal to 'k'.
+* The ceiling of key 'k' is the minimum value that is greater than or equal to 'k'.
+
+Reference:
+https://bit.ly/46uB0a2
+
+Author : Arunkumar
+Date : 14th October 2023
+"""
... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/floor_and_ceiling.py |
Document all endpoints with docstrings | from __future__ import annotations
from random import random
class Node:
def __init__(self, value: int | None = None):
self.value = value
self.prior = random()
self.left: Node | None = None
self.right: Node | None = None
def __repr__(self) -> str:
from pprint import ... | --- +++ @@ -4,6 +4,10 @@
class Node:
+ """
+ Treap's node
+ Treap is a binary tree by value and heap by priority
+ """
def __init__(self, value: int | None = None):
self.value = value
@@ -29,6 +33,12 @@
def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]:
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/treap.py |
Document this module using docstrings | from __future__ import annotations
from collections.abc import Iterator
class RedBlackTree:
def __init__(
self,
label: int | None = None,
color: int = 0,
parent: RedBlackTree | None = None,
left: RedBlackTree | None = None,
right: RedBlackTree | None = None,
)... | --- +++ @@ -1,616 +1,716 @@-from __future__ import annotations
-
-from collections.abc import Iterator
-
-
-class RedBlackTree:
-
- def __init__(
- self,
- label: int | None = None,
- color: int = 0,
- parent: RedBlackTree | None = None,
- left: RedBlackTree | None = None,
- ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/red_black_tree.py |
Create docstrings for all classes and functions | #!/usr/local/bin/python3
from __future__ import annotations
class Node:
def __init__(self, value: int = 0) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node | None:
if ... | --- +++ @@ -1,9 +1,18 @@ #!/usr/local/bin/python3
+"""
+Problem Description: Given two binary tree, return the merged tree.
+The rule for merging is that if two nodes overlap, then put the value sum of
+both nodes to the new value of the merged node. Otherwise, the NOT null node
+will be used as the node of new tree.
+... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/merge_two_binary_trees.py |
Write docstrings for data processing functions |
from collections.abc import Sequence
from queue import Queue
class SegmentTreeNode:
def __init__(self, start, end, val, left=None, right=None):
self.start = start
self.end = end
self.val = val
self.mid = (start + end) // 2
self.left = left
self.right = right
d... | --- +++ @@ -1,3 +1,8 @@+"""
+Segment_tree creates a segment tree with a given array and function,
+allowing queries to be done later in log(N) time
+function takes 2 values and returns a same type value
+"""
from collections.abc import Sequence
from queue import Queue
@@ -17,6 +22,110 @@
class SegmentTree:
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/segment_tree_other.py |
Write Python docstrings for this snippet | # https://en.wikipedia.org/wiki/Lowest_common_ancestor
# https://en.wikipedia.org/wiki/Breadth-first_search
from __future__ import annotations
from queue import Queue
def swap(a: int, b: int) -> tuple[int, int]:
a ^= b
b ^= a
a ^= b
return a, b
def create_sparse(max_node: int, parent: list[list[in... | --- +++ @@ -7,6 +7,17 @@
def swap(a: int, b: int) -> tuple[int, int]:
+ """
+ Return a tuple (b, a) when given two integers a and b
+ >>> swap(2,3)
+ (3, 2)
+ >>> swap(3,4)
+ (4, 3)
+ >>> swap(67, 12)
+ (12, 67)
+ >>> swap(3,-4)
+ (-4, 3)
+ """
a ^= b
b ^= a
a ^= b
@@... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/lowest_common_ancestor.py |
Add documentation for all methods |
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
data: int
left: Node | None = None
right: Node | None = None
def make_symmetric_tree() -> Node:
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.ri... | --- +++ @@ -1,3 +1,9 @@+"""
+Given the root of a binary tree, check whether it is a mirror of itself
+(i.e., symmetric around its center).
+
+Leetcode reference: https://leetcode.com/problems/symmetric-tree/
+"""
from __future__ import annotations
@@ -6,6 +12,23 @@
@dataclass
class Node:
+ """
+ A Node re... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/symmetric_tree.py |
Document all public functions with docstrings |
from __future__ import annotations
test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]
class Node:
def __init__(self, length: int) -> None:
self.minn: int = -1
self.maxx: int = -1
self.map_left: list[int] = [-1] * length
self.left: Node | None = None
... | --- +++ @@ -1,3 +1,12 @@+"""
+Wavelet tree is a data-structure designed to efficiently answer various range queries
+for arrays. Wavelets trees are different from other binary trees in the sense that
+the nodes are split based on the actual values of the elements and not on indices,
+such as the with segment trees or f... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/binary_tree/wavelet_tree.py |
Write docstrings that follow conventions | #!/usr/bin/env python3
from .hash_table import HashTable
from .number_theory.prime_numbers import is_prime, next_prime
class DoubleHash(HashTable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __hash_function_2(self, value, data):
next_prime_gt = (
... | --- +++ @@ -1,10 +1,25 @@ #!/usr/bin/env python3
+"""
+Double hashing is a collision resolving technique in Open Addressed Hash tables.
+Double hashing uses the idea of applying a second hash function to key when a collision
+occurs. The advantage of Double hashing is that it is one of the best form of probing,
+produ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/hashing/double_hash.py |
Add docstrings for utility scripts |
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any, Self
@dataclass
class Node:
data: Any
next_node: Self | None = None
@dataclass
class LinkedList:
head: Node | None = None
def __iter__(self) -> Iterator:
visited = []
node = self.head
... | --- +++ @@ -1,3 +1,14 @@+"""
+Floyd's cycle detection algorithm is a popular algorithm used to detect cycles
+in a linked list. It uses two pointers, a slow pointer and a fast pointer,
+to traverse the linked list. The slow pointer moves one node at a time while the fast
+pointer moves two nodes at a time. If there is ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/floyds_cycle_detection.py |
Add docstrings to existing functions | #!/usr/bin/env python3
from abc import abstractmethod
from .number_theory.prime_numbers import next_prime
class HashTable:
def __init__(
self,
size_table: int,
charge_factor: int | None = None,
lim_charge: float | None = None,
) -> None:
self.size_table = size_table
... | --- +++ @@ -5,6 +5,9 @@
class HashTable:
+ """
+ Basic Hash Table example with open addressing and linear probing
+ """
def __init__(
self,
@@ -20,6 +23,29 @@ self._keys: dict = {}
def keys(self):
+ """
+ The keys function returns a dictionary containing the key... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/hashing/hash_table.py |
Write clean docstrings for readability |
class DisjointSet:
def __init__(self, set_counts: list) -> None:
self.set_counts = set_counts
self.max_set = max(set_counts)
num_sets = len(set_counts)
self.ranks = [1] * num_sets
self.parents = list(range(num_sets))
def merge(self, src: int, dst: int) -> bool:
... | --- +++ @@ -1,7 +1,15 @@+"""
+Implements a disjoint set using Lists and some added heuristics for efficiency
+Union by Rank Heuristic and Path Compression
+"""
class DisjointSet:
def __init__(self, set_counts: list) -> None:
+ """
+ Initialize with a list of the number of items in each set
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/disjoint_set/alternate_disjoint_set.py |
Add docstrings that explain logic | #!/usr/bin/env python3
from .hash_table import HashTable
class QuadraticProbing(HashTable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _collision_resolution(self, key, data=None): # noqa: ARG002
i = 1
new_key = self.hash_function(key + i * i)
... | --- +++ @@ -4,11 +4,62 @@
class QuadraticProbing(HashTable):
+ """
+ Basic Hash Table example with open addressing using Quadratic Probing
+ """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _collision_resolution(self, key, data=None): # noqa: ARG002
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/hashing/quadratic_probing.py |
Add docstrings with type hints explained |
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import TypeVar
KEY = TypeVar("KEY")
VAL = TypeVar("VAL")
@dataclass(slots=True)
class _Item[KEY, VAL]:
key: KEY
val: VAL
class _DeletedItem(_Item):
def __init__(self) -> None:
super().__init__(No... | --- +++ @@ -1,3 +1,12 @@+"""
+Hash map with open addressing.
+
+https://en.wikipedia.org/wiki/Hash_table
+
+Another hash map implementation, with a good explanation.
+Modern Dictionaries by Raymond Hettinger
+https://www.youtube.com/watch?v=p33CVV29OG8
+"""
from collections.abc import Iterator, MutableMapping
from ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/hashing/hash_map.py |
Write Python docstrings for this snippet | #!/usr/bin/env python3
import math
def is_prime(number: int) -> bool:
# precondition
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
... | --- +++ @@ -1,9 +1,35 @@ #!/usr/bin/env python3
+"""
+module to operations with prime numbers
+"""
import math
def is_prime(number: int) -> bool:
+ """Checks to see if a number is a prime in O(sqrt(n)).
+
+ A number is prime if it has exactly two factors: 1 and itself.
+
+ >>> is_prime(0)
+ False
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/hashing/number_theory/prime_numbers.py |
Add docstrings to existing functions | 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, ints: Iterable[int]) -> None:
self.head: Node | None = None
for i in in... | --- +++ @@ -17,18 +17,54 @@ self.append(i)
def __iter__(self) -> Iterator[int]:
+ """
+ >>> ints = []
+ >>> list(LinkedList(ints)) == ints
+ True
+ >>> ints = tuple(range(5))
+ >>> tuple(LinkedList(ints)) == ints
+ True
+ """
node = sel... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/reverse_k_group.py |
Add docstrings for production code |
class Node:
def __init__(self, val):
self.val = val
# Number of nodes in left subtree
self.left_tree_size = 0
self.left = None
self.right = None
self.parent = None
def merge_trees(self, other):
assert self.left_tree_size == other.left_tree_size, "Unequ... | --- +++ @@ -1,286 +1,401 @@-
-
-class Node:
-
- def __init__(self, val):
- self.val = val
- # Number of nodes in left subtree
- self.left_tree_size = 0
- self.left = None
- self.right = None
- self.parent = None
-
- def merge_trees(self, other):
- assert self.left_... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/heap/binomial_heap.py |
Write docstrings for backend logic |
from __future__ import annotations
from typing import Any
class Node:
def __init__(self, item: Any, next: Any) -> None: # noqa: A002
self.item = item
self.next = next
class LinkedList:
def __init__(self) -> None:
self.head: Node | None = None
self.size = 0
def add(sel... | --- +++ @@ -1,3 +1,10 @@+"""
+Linked Lists consists of Nodes.
+Nodes contain data and also may link to other nodes:
+ - Head Node: First node, the address of the
+ head node gives us access of the complete list
+ - Last node: points to null
+"""
from __future__ import annotations
@@ -16,6 +23... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/__init__.py |
Generate docstrings with parameter types | from __future__ import annotations
from abc import abstractmethod
from collections.abc import Iterable
from typing import Protocol, TypeVar
class Comparable(Protocol):
@abstractmethod
def __lt__(self: T, other: T) -> bool:
pass
@abstractmethod
def __gt__(self: T, other: T) -> bool:
p... | --- +++ @@ -23,6 +23,27 @@
class Heap[T: Comparable]:
+ """A Max Heap Implementation
+
+ >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5]
+ >>> h = Heap()
+ >>> h.build_max_heap(unsorted)
+ >>> h
+ [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]
+ >>>
+ >>> h.extract_max()
+ 209
+... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/heap/heap.py |
Add concise docstrings to each method | 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 LinkedList:
head: Node | None = None
def __iter__(self) -> Iterator:
node = self.... | --- +++ @@ -1,62 +1,148 @@-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 LinkedList:
- head: Node | None = None
-
- def __it... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/swap_nodes.py |
Document this module using docstrings | #!/usr/bin/env python3
from __future__ import annotations
import random
from collections.abc import Iterable
from typing import Any, TypeVar
T = TypeVar("T", bound=bool)
class RandomizedHeapNode[T: bool]:
def __init__(self, value: T) -> None:
self._value: T = value
self.left: RandomizedHeapNod... | --- +++ @@ -10,6 +10,10 @@
class RandomizedHeapNode[T: bool]:
+ """
+ One node of the randomized heap. Contains the value and references to
+ two children.
+ """
def __init__(self, value: T) -> None:
self._value: T = value
@@ -18,12 +22,40 @@
@property
def value(self) -> T:
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/heap/randomized_heap.py |
Generate missing documentation strings |
from typing import Literal
from .balanced_parentheses import balanced_parentheses
from .stack import Stack
PRECEDENCES: dict[str, int] = {
"+": 1,
"-": 1,
"*": 2,
"/": 2,
"^": 3,
}
ASSOCIATIVITIES: dict[str, Literal["LR", "RL"]] = {
"+": "LR",
"-": "LR",
"*": "LR",
"/": "LR",
... | --- +++ @@ -1,3 +1,8 @@+"""
+https://en.wikipedia.org/wiki/Infix_notation
+https://en.wikipedia.org/wiki/Reverse_Polish_notation
+https://en.wikipedia.org/wiki/Shunting-yard_algorithm
+"""
from typing import Literal
@@ -21,14 +26,43 @@
def precedence(char: str) -> int:
+ """
+ Return integer value repres... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/stacks/infix_to_postfix_conversion.py |
Write documentation strings for class attributes |
class _DoublyLinkedBase:
class _Node:
__slots__ = "_data", "_next", "_prev"
def __init__(self, link_p, element, link_n):
self._prev = link_p
self._data = element
self._next = link_n
def has_next_and_prev(self):
return (
f" ... | --- +++ @@ -1,6 +1,15 @@+"""
+Implementing Deque using DoublyLinkedList ...
+Operations:
+ 1. insertion in the front -> O(1)
+ 2. insertion in the end -> O(1)
+ 3. remove from the front -> O(1)
+ 4. remove from the end -> O(1)
+"""
class _DoublyLinkedBase:
+ """A Private class (to be inherited)"""
... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/deque_doubly.py |
Help me comply with documentation standards | # 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 __future__ import annotations
cla... | --- +++ @@ -10,6 +10,14 @@
class KDNode:
+ """
+ Represents a node in a KD-Tree.
+
+ Attributes:
+ point: The point stored in this node.
+ left: The left child node.
+ right: The right child node.
+ """
def __init__(
self,
@@ -17,6 +25,14 @@ left: KDNode | No... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/kd_tree/kd_node.py |
Add docstrings to clarify complex logic | #!/usr/bin/env python3
from __future__ import annotations
from collections.abc import Iterable, Iterator
from typing import Any, TypeVar
T = TypeVar("T", bound=bool)
class SkewNode[T: bool]:
def __init__(self, value: T) -> None:
self._value: T = value
self.left: SkewNode[T] | None = None
... | --- +++ @@ -9,6 +9,10 @@
class SkewNode[T: bool]:
+ """
+ One node of the skew heap. Contains the value and references to
+ two children.
+ """
def __init__(self, value: T) -> None:
self._value: T = value
@@ -17,12 +21,55 @@
@property
def value(self) -> T:
+ """
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/heap/skew_heap.py |
Document classes and their methods |
from __future__ import annotations
from collections.abc import Iterator
from typing import Any
class Node:
def __init__(self, data: Any) -> None:
self.data: Any = data
self.next: Node | None = None
def __str__(self) -> str:
return f"{self.data}"
class LinkedQueue:
def __init_... | --- +++ @@ -1,3 +1,4 @@+"""A Queue using a linked list like structure"""
from __future__ import annotations
@@ -15,6 +16,31 @@
class LinkedQueue:
+ """
+ >>> queue = LinkedQueue()
+ >>> queue.is_empty()
+ True
+ >>> queue.put(5)
+ >>> queue.put(9)
+ >>> queue.put('python')
+ >>> queue.i... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/queues/linked_queue.py |
Fully document this Python code with docstrings |
from dataclasses import dataclass
from typing import Self, TypeVar
DataType = TypeVar("DataType")
@dataclass
class Node[DataType]:
data: DataType
previous: Self | None = None
next: Self | None = None
def __str__(self) -> str:
return f"{self.data}"
class LinkedListIterator:
def __init_... | --- +++ @@ -1,3 +1,13 @@+"""
+- A linked list is similar to an array, it holds values. However, links in a linked
+ list do not have indexes.
+- This is an example of a double ended, doubly linked list.
+- Each link references the next link and the previous one.
+- A Doubly Linked List (DLL) contains an extra pointe... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/doubly_linked_list_two.py |
Include argument descriptions in docstrings |
class Node:
def __init__(self, data):
self.data = data
self.previous = None
self.next = None
def __str__(self):
return f"{self.data}"
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = sel... | --- +++ @@ -1,3 +1,6 @@+"""
+https://en.wikipedia.org/wiki/Doubly_linked_list
+"""
class Node:
@@ -16,15 +19,38 @@ self.tail = None
def __iter__(self):
+ """
+ >>> linked_list = DoublyLinkedList()
+ >>> linked_list.insert_at_head('b')
+ >>> linked_list.insert_at_head('a')... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/doubly_linked_list.py |
Help me comply with documentation standards | from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
data: int
next_node: Node | None = None
def print_linked_list(head: Node | None) -> None:
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = h... | --- +++ @@ -10,6 +10,25 @@
def print_linked_list(head: Node | None) -> None:
+ """
+ Print the entire linked list iteratively.
+
+ This function prints the elements of a linked list separated by '->'.
+
+ Parameters:
+ head (Node | None): The head of the linked list to be printed,... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/rotate_to_the_right.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.