instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate documentation strings for clarity
import argparse import copy def generate_neighbours(path): dict_of_neighbours = {} with open(path) as f: for line in f: if line.split()[0] not in dict_of_neighbours: _list = [] _list.append([line.split()[1], line.split()[2]]) dict_of_neigh...
--- +++ @@ -1,9 +1,51 @@+""" +This is pure Python implementation of Tabu search algorithm for a Travelling Salesman +Problem, that the distances between the cities are symmetric (the distance between city +'a' and city 'b' is the same between city 'b' and city 'a'). +The TSP can be represented into a graph. The cities ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/tabu_search.py
Annotate my code with docstrings
def bead_sort(sequence: list) -> list: if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") for _ in range(len(sequence)): for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): # noqa: RUF007 ...
--- +++ @@ -1,6 +1,33 @@+""" +Bead sort only works for sequences of non-negative integers. +https://en.wikipedia.org/wiki/Bead_sort +""" def bead_sort(sequence: list) -> list: + """ + >>> bead_sort([6, 11, 12, 4, 1, 5]) + [1, 4, 5, 6, 11, 12] + + >>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1]) + [1, 2, 3...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bead_sort.py
Insert docstrings into my code
import multiprocessing as mp # lock used to ensure that two processes do not access a pipe at the same time # NOTE This breaks testing on build runner. May work better locally # process_lock = mp.Lock() """ The function run by the processes that sorts the list position = the position in the list the process represe...
--- +++ @@ -1,3 +1,15 @@+""" +This is an implementation of odd-even transposition sort. + +It works by performing a series of parallel swaps between odd and even pairs of +variables in the list. + +This implementation represents each variable in the list with a process and +each process communicates with its neighborin...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/odd_even_transposition_parallel.py
Create docstrings for API functions
import math from collections.abc import Sequence from typing import Any, Protocol class Comparable(Protocol): def __lt__(self, other: Any, /) -> bool: ... def jump_search[T: Comparable](arr: Sequence[T], item: T) -> int: arr_size = len(arr) block_size = int(math.sqrt(arr_size)) prev = 0 step ...
--- +++ @@ -1,3 +1,12 @@+""" +Pure Python implementation of the jump search algorithm. +This algorithm iterates through a sorted collection with a step of n^(1/2), +until the element compared is bigger than the one searched. +It will then perform a linear search until it matches the wanted number. +If not found, it ret...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/jump_search.py
Add structured docstrings to improve clarity
def pancake_sort(arr): cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cu...
--- +++ @@ -1,6 +1,26 @@+""" +This is a pure Python implementation of the pancake sort algorithm +For doctests run following command: +python3 -m doctest -v pancake_sort.py +or +python -m doctest -v pancake_sort.py +For manual testing run: +python pancake_sort.py +""" def pancake_sort(arr): + """Sort Array with...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/pancake_sort.py
Add docstrings for better understanding
from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: if len(array) == 0: return array _min, _max = min(array), max(array) # Compute the variables holes_range = _max - _min + 1 holes, holes_repeat = [0] * holes_range, [0] * holes_range # Make the sortin...
--- +++ @@ -1,8 +1,30 @@+""" +This is an implementation of Pigeon Hole Sort. +For doctests run following command: + +python3 -m doctest -v pigeon_sort.py +or +python -m doctest -v pigeon_sort.py + +For manual testing run: +python pigeon_sort.py +""" from __future__ import annotations def pigeon_sort(array: list...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/pigeon_sort.py
Write docstrings for backend logic
def odd_even_sort(input_list: list) -> list: is_sorted = False while is_sorted is False: # Until all the indices are traversed keep looping is_sorted = True for i in range(0, len(input_list) - 1, 2): # iterating over all even indices if input_list[i] > input_list[i + 1]: ...
--- +++ @@ -1,6 +1,30 @@+""" +Odd even sort implementation. + +https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort +""" def odd_even_sort(input_list: list) -> list: + """ + Sort input with odd even sort. + + This algorithm uses the same idea of bubblesort, + but by first dividing in two phase (odd and ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/odd_even_sort.py
Write Python docstrings for this snippet
def odd_even_transposition(arr: list) -> list: arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1))...
--- +++ @@ -1,6 +1,24 @@+""" +Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort + +This is a non-parallelized implementation of odd-even transposition sort. + +Normally the swaps in each set happen simultaneously, without that the algorithm +is no better than bubble sort. +""" def odd_even_transposition(...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/odd_even_transposition_single_threaded.py
Create docstrings for each class method
def binary_insertion_sort(collection: list) -> list: n = len(collection) for i in range(1, n): value_to_insert = collection[i] low = 0 high = i - 1 while low <= high: mid = (low + high) // 2 if value_to_insert < collection[mid]: high = ...
--- +++ @@ -1,6 +1,42 @@+""" +This is a pure Python implementation of the binary insertion sort algorithm + +For doctests run following command: +python -m doctest -v binary_insertion_sort.py +or +python3 -m doctest -v binary_insertion_sort.py + +For manual testing run: +python binary_insertion_sort.py +""" def bi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/binary_insertion_sort.py
Generate helpful docstrings for debugging
from __future__ import annotations RADIX = 10 def radix_sort(list_of_ints: list[int]) -> list[int]: placement = 1 max_digit = max(list_of_ints) while placement <= max_digit: # declare and initialize empty buckets buckets: list[list] = [[] for _ in range(RADIX)] # split list_of_in...
--- +++ @@ -1,3 +1,8 @@+""" +This is a pure Python implementation of the radix sort algorithm + +Source: https://en.wikipedia.org/wiki/Radix_sort +""" from __future__ import annotations @@ -5,6 +10,18 @@ def radix_sort(list_of_ints: list[int]) -> list[int]: + """ + Examples: + >>> radix_sort([0, 5, 3,...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/radix_sort.py
Add clean documentation to messy code
from __future__ import annotations def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None: if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid...
--- +++ @@ -1,8 +1,40 @@+""" +Slowsort is a sorting algorithm. It is of humorous nature and not useful. +It's based on the principle of multiply and surrender, +a tongue-in-cheek joke of divide and conquer. +It was published in 1986 by Andrei Broder and Jorge Stolfi +in their paper Pessimal Algorithms and Simplexity An...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/slowsort.py
Write beginner-friendly docstrings
def quick_sort_3partition(sorting: list, left: int, right: int) -> None: if right <= left: return a = i = left b = right pivot = sorting[left] while i <= b: if sorting[i] < pivot: sorting[a], sorting[i] = sorting[i], sorting[a] a += 1 i += 1 ...
--- +++ @@ -1,4 +1,27 @@ def quick_sort_3partition(sorting: list, left: int, right: int) -> None: + """ " + Python implementation of quick sort algorithm with 3-way partition. + The idea of 3-way quick sort is based on "Dutch National Flag algorithm". + + :param sorting: sort list + :param left: left end...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/quick_sort_3_partition.py
Provide clean and structured docstrings
def shell_sort(collection: list) -> list: # Choose an initial gap value gap = len(collection) # Set the gap value to be decreased by a factor of 1.3 # after each iteration shrink = 1.3 # Continue sorting until the gap is 1 while gap > 1: # Decrease the gap value gap = in...
--- +++ @@ -1,6 +1,39 @@+""" +This function implements the shell sort algorithm +which is slightly faster than its pure implementation. + +This shell sort is implemented using a gap, which +shrinks by a certain factor each iteration. In this +implementation, the gap is initially set to the +length of the collection. Th...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/shrink_shell_sort.py
Add docstrings for internal functions
def shell_sort(collection: list[int]) -> list[int]: # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_...
--- +++ @@ -1,6 +1,21 @@+""" +https://en.wikipedia.org/wiki/Shellsort#Pseudocode +""" def shell_sort(collection: list[int]) -> list[int]: + """Pure implementation of shell sort algorithm in Python + :param collection: Some mutable ordered collection with heterogeneous + comparable items inside + :retu...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/shell_sort.py
Help me write clear docstrings
from __future__ import annotations def rec_insertion_sort(collection: list, n: int): # Checks if the entire collection has been sorted if len(collection) <= 1 or n <= 1: return insert_next(collection, n - 1) rec_insertion_sort(collection, n - 1) def insert_next(collection: list, index: int...
--- +++ @@ -1,8 +1,33 @@+""" +A recursive implementation of the insertion sort algorithm +""" from __future__ import annotations def rec_insertion_sort(collection: list, n: int): + """ + Given a collection of numbers and its length, sorts the collections + in ascending order + + :param collection: A...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/recursive_insertion_sort.py
Add detailed documentation for each class
def wiggle_sort(nums: list) -> list: for i, _ in enumerate(nums): if (i % 2 == 1) == (nums[i - 1] > nums[i]): nums[i - 1], nums[i] = nums[i], nums[i - 1] return nums if __name__ == "__main__": print("Enter the array elements:") array = list(map(int, input().split())) print("...
--- +++ @@ -1,6 +1,27 @@+""" +Wiggle Sort. + +Given an unsorted array nums, reorder it such +that nums[0] < nums[1] > nums[2] < nums[3].... +For example: +if input numbers = [3, 5, 2, 1, 6, 4] +one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4]. +""" def wiggle_sort(nums: list) -> list: + """ + Python i...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/wiggle_sort.py
Add documentation for all methods
"""https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array...
--- +++ @@ -1,8 +1,23 @@+"""A merge sort which accepts an array as input and recursively +splits an array in half and sorts and combines them. +""" """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: + """Return a sorted array. + >>> merge([10,9,8,7,6,5,4,3,2,1]) + [...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/recursive_mergesort_array.py
Document classes and their methods
def stalin_sort(sequence: list[int]) -> list[int]: result = [sequence[0]] for element in sequence[1:]: if element >= result[-1]: result.append(element) return result if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,38 @@+""" +Stalin Sort algorithm: Removes elements that are out of order. +Elements that are not greater than or equal to the previous element are discarded. +Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420 +""" def stalin_sort(sequence: list[int]) -> list[in...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/stalin_sort.py
Add docstrings for production code
def merge_sort(collection): start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection...
--- +++ @@ -1,6 +1,28 @@+""" +Python implementation of a sort algorithm. +Best Case Scenario : O(n) +Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are +already O(n) +""" def merge_sort(collection): + """Pure implementation of the fastest merge sort algorithm in Python + + :...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/unknown_sort.py
Generate consistent docstrings
from __future__ import annotations import collections import pprint from pathlib import Path def signature(word: str) -> str: frequencies = collections.Counter(word) return "".join( f"{char}{frequency}" for char, frequency in sorted(frequencies.items()) ) def anagram(my_word: str) -> list[str]:...
--- +++ @@ -6,6 +6,16 @@ def signature(word: str) -> str: + """ + Return a word's frequency-based signature. + + >>> signature("test") + 'e1s1t2' + >>> signature("this is a test") + ' 3a1e1h1i2s3t3' + >>> signature("finaltest") + 'a1e1f1i1l1n1s1t2' + """ frequencies = collections.Cou...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/anagrams.py
Add detailed documentation for each class
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: val: 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,8 @@+""" +Tree_sort algorithm. + +Build a Binary Search Tree and then iterate thru it to get a sorted list. +""" from __future__ import annotations @@ -35,6 +40,23 @@ def tree_sort(arr: list[int]) -> tuple[int, ...]: + """ + >>> tree_sort([]) + () + >>> tree_sort((1,)) + (1,) ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/tree_sort.py
Can you add docstrings to this Python file?
class BoyerMooreSearch: def __init__(self, text: str, pattern: str): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) def match_in_pattern(self, char: str) -> int: for i in range(self.patLen - 1, -1, -1): if char == self.pattern...
--- +++ @@ -1,12 +1,53 @@+""" +The algorithm finds the pattern in given text using following rule. + +The bad-character rule considers the mismatched character in Text. +The next occurrence of that character to the left in Pattern is found, + +If the mismatched character occurs to the left in Pattern, +a shift is propo...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/boyer_moore_search.py
Add docstrings that explain purpose and usage
from __future__ import annotations from random import randrange def quick_sort(collection: list) -> list: # Base case: if the collection has 0 or 1 elements, it is already sorted if len(collection) < 2: return collection # Randomly select a pivot index and remove the pivot element from the coll...
--- +++ @@ -1,3 +1,12 @@+""" +A pure Python implementation of the quick sort algorithm + +For doctests run following command: +python3 -m doctest -v quick_sort.py + +For manual testing run: +python3 quick_sort.py +""" from __future__ import annotations @@ -5,6 +14,19 @@ def quick_sort(collection: list) -> list...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/quick_sort.py
Add docstrings to my Python code
def get_check_digit(barcode: int) -> int: barcode //= 10 # exclude the last digit checker = False s = 0 # extract and check each digit while barcode != 0: mult = 1 if checker else 3 s += mult * (barcode % 10) barcode //= 10 checker = not checker return (10 - ...
--- +++ @@ -1,6 +1,23 @@+""" +https://en.wikipedia.org/wiki/Check_digit#Algorithms +""" def get_check_digit(barcode: int) -> int: + """ + Returns the last digit of barcode by excluding the last digit first + and then computing to reach the actual last digit from the remaining + 12 digits. + + >>> ge...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/barcode_validator.py
Add documentation for all methods
def damerau_levenshtein_distance(first_string: str, second_string: str) -> int: # Create a dynamic programming matrix to store the distances dp_matrix = [[0] * (len(second_string) + 1) for _ in range(len(first_string) + 1)] # Initialize the matrix for i in range(len(first_string) + 1): dp_mat...
--- +++ @@ -1,6 +1,38 @@+""" +This script is a implementation of the Damerau-Levenshtein distance algorithm. + +It's an algorithm that measures the edit distance between two string sequences + +More information about this algorithm can be found in this wikipedia article: +https://en.wikipedia.org/wiki/Damerau%E2%80%93L...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/damerau_levenshtein_distance.py
Provide clean and structured docstrings
def is_pangram( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: # Declare frequency as a set to have unique occurrences of letters frequency = set() # Replace all the whitespace in our sentence input_str = input_str.replace(" ", "") for alpha in input_str: i...
--- +++ @@ -1,8 +1,26 @@+""" +wiki: https://en.wikipedia.org/wiki/Pangram +""" def is_pangram( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: + """ + A Pangram String contains all the alphabets at least once. + >>> is_pangram("The quick brown fox jumps over the lazy dog")...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/is_pangram.py
Improve documentation using docstrings
def validate_initial_digits(credit_card_number: str) -> bool: return credit_card_number.startswith(("34", "35", "37", "4", "5", "6")) def luhn_validation(credit_card_number: str) -> bool: cc_number = credit_card_number total = 0 half_len = len(cc_number) - 2 for i in range(half_len, -1, -2): ...
--- +++ @@ -1,10 +1,33 @@+""" +Functions for testing the validity of credit card numbers. + +https://en.wikipedia.org/wiki/Luhn_algorithm +""" def validate_initial_digits(credit_card_number: str) -> bool: + """ + Function to validate initial digits of a given credit card number. + >>> valid = "41111111111...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/credit_card_validator.py
Add docstrings with type hints explained
# Frequency Finder import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency english_letter_freq = { "E": 12.70, "T": 9.06, "A": 8.17, "O": 7.51, "I": 6.97, "N": 6.75, "S": 6.33, "H": 6.09, "R": 5.99, "D": 4.25, "L": 4.03, "C": 2.78, "U": 2...
--- +++ @@ -49,6 +49,15 @@ def get_frequency_order(message: str) -> str: + """ + Get the frequency order of the letters in the given string + >>> get_frequency_order('Hello World') + 'LOWDRHEZQXJKVBPYGFMUCSNIAT' + >>> get_frequency_order('Hello@') + 'LHOEZQXJKVBPYGFWMUCDRSNIAT' + >>> get_freque...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/frequency_finder.py
Add docstrings to make code maintainable
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_count...
--- +++ @@ -11,10 +11,34 @@ def can_string_be_rearranged_as_palindrome_counter( input_str: str = "", ) -> bool: + """ + A Palindrome is a String that reads the same forward as it does backwards. + Examples of Palindromes mom, dad, malayalam + >>> can_string_be_rearranged_as_palindrome_counter("Momo") ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/can_string_be_rearranged_as_palindrome.py
Add docstrings to improve readability
import os from string import ascii_letters LETTERS_AND_SPACE = ascii_letters + " \t\n" def load_dictionary() -> dict[str, None]: path = os.path.split(os.path.realpath(__file__)) english_words: dict[str, None] = {} with open(path[0] + "/dictionary.txt") as dictionary_file: for word in dictionary_f...
--- +++ @@ -25,12 +25,30 @@ def remove_non_letters(message: str) -> str: + """ + >>> remove_non_letters("Hi! how are you?") + 'Hi how are you' + >>> remove_non_letters("P^y%t)h@o*n") + 'Python' + >>> remove_non_letters("1+1=2") + '' + >>> remove_non_letters("www.google.com/") + 'wwwgoogle...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/detecting_english_programmatically.py
Add docstrings to incomplete code
def bitap_string_match(text: str, pattern: str) -> int: if not pattern: return 0 m = len(pattern) if m > len(text): return -1 # Initial state of bit string 1110 state = ~1 # Bit = 0 if character appears at index, and 1 otherwise pattern_mask: list[int] = [~0] * 27 # 1111 ...
--- +++ @@ -1,6 +1,45 @@+""" +Bitap exact string matching +https://en.wikipedia.org/wiki/Bitap_algorithm + +Searches for a pattern inside text, and returns the index of the first occurrence +of the pattern. Both text and pattern consist of lowercase alphabetical characters only. + +Complexity: O(m*n) + n = length of...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/bitap_string_match.py
Add docstrings to clarify complex logic
def is_isogram(string: str) -> bool: if not all(x.isalpha() for x in string): raise ValueError("String must only contain alphabetic characters.") letters = sorted(string.lower()) return len(letters) == len(set(letters)) if __name__ == "__main__": input_str = input("Enter a string ").strip()...
--- +++ @@ -1,6 +1,21 @@+""" +wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms +""" def is_isogram(string: str) -> bool: + """ + An isogram is a word in which no letter is repeated. + Examples of isograms are uncopyrightable and ambidextrously. + >>> is_isogram('Uncopyrightable') + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/is_isogram.py
Provide docstrings following PEP 257
from collections import defaultdict def check_anagrams(first_str: str, second_str: str) -> bool: first_str = first_str.lower().strip() second_str = second_str.lower().strip() # Remove whitespace first_str = first_str.replace(" ", "") second_str = second_str.replace(" ", "") # Strings of dif...
--- +++ @@ -1,37 +1,52 @@- -from collections import defaultdict - - -def check_anagrams(first_str: str, second_str: str) -> bool: - first_str = first_str.lower().strip() - second_str = second_str.lower().strip() - - # Remove whitespace - first_str = first_str.replace(" ", "") - second_str = second_str.re...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/check_anagrams.py
Generate missing documentation strings
def jaro_winkler(str1: str, str2: str) -> float: def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, char in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2...
--- +++ @@ -1,6 +1,29 @@+"""https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance""" def jaro_winkler(str1: str, str2: str) -> float: + """ + Jaro-Winkler distance is a string metric measuring an edit distance between two + sequences. + Output value is between 0.0 and 1.0. + + >>> jaro_winkler...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/jaro_winkler.py
Fully document this Python code with docstrings
from typing import Any def bubble_sort_iterative(collection: list[Any]) -> list[Any]: length = len(collection) for i in reversed(range(length)): swapped = False for j in range(i): if collection[j] > collection[j + 1]: swapped = True collection[j], co...
--- +++ @@ -2,6 +2,52 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]: + """Pure implementation of bubble sort algorithm in Python + + :param collection: some mutable ordered collection with heterogeneous + comparable items inside + :return: the same collection ordered in ascending orde...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bubble_sort.py
Document this script properly
from __future__ import annotations def knuth_morris_pratt(text: str, pattern: str) -> int: # 1) Construct the failure array failure = get_failure_array(pattern) # 2) Step through text searching for pattern i, j = 0, 0 # index into text, pattern while i < len(text): if pattern[j] == text...
--- +++ @@ -2,6 +2,25 @@ def knuth_morris_pratt(text: str, pattern: str) -> int: + """ + The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text + with complexity O(n + m) + + 1) Preprocess pattern to identify any suffixes that are identical to prefixes + + This tells us whe...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/knuth_morris_pratt.py
Write reusable docstrings
from collections.abc import Callable def levenshtein_distance(first_word: str, second_word: str) -> int: # The longer word should come first if len(first_word) < len(second_word): return levenshtein_distance(second_word, first_word) if len(second_word) == 0: return len(first_word) pr...
--- +++ @@ -2,6 +2,27 @@ def levenshtein_distance(first_word: str, second_word: str) -> int: + """ + Implementation of the Levenshtein distance in Python. + :param first_word: the first word to measure the difference. + :param second_word: the second word to measure the difference. + :return: the lev...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/levenshtein_distance.py
Write docstrings describing functionality
def create_ngram(sentence: str, ngram_size: int) -> list[str]: return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)] if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -1,10 +1,23 @@+""" +https://en.wikipedia.org/wiki/N-gram +""" def create_ngram(sentence: str, ngram_size: int) -> list[str]: + """ + Create ngrams from a sentence + + >>> create_ngram("I am a sentence", 2) + ['I ', ' a', 'am', 'm ', ' a', 'a ', ' s', 'se', 'en', 'nt', 'te', 'en', 'nc', 'ce']...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/ngram.py
Document all endpoints with docstrings
def compute_transform_tables( source_string: str, destination_string: str, copy_cost: int, replace_cost: int, delete_cost: int, insert_cost: int, ) -> tuple[list[list[int]], list[list[str]]]: source_seq = list(source_string) destination_seq = list(destination_string) len_source_seq...
--- +++ @@ -1,3 +1,12 @@+""" +Algorithm for calculating the most cost-efficient sequence for converting one string +into another. +The only allowed operations are +--- Cost to copy a character is copy_cost +--- Cost to replace a character is replace_cost +--- Cost to delete a character is delete_cost +--- Cost to inser...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/min_cost_string_conversion.py
Write docstrings that follow conventions
def circle_sort(collection: list) -> list: if len(collection) < 2: return collection def circle_sort_util(collection: list, low: int, high: int) -> bool: swapped = False if low == high: return swapped left = low right = high while left < right:...
--- +++ @@ -1,11 +1,43 @@+""" +This is a Python implementation of the circle sort algorithm + +For doctests run following command: +python3 -m doctest -v circle_sort.py + +For manual testing run: +python3 circle_sort.py +""" def circle_sort(collection: list) -> list: + """A pure Python implementation of circle ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/circle_sort.py
Provide clean and structured docstrings
def join(separator: str, separated: list[str]) -> str: # Check that all elements are strings for word_or_phrase in separated: # If the element is not a string, raise an exception if not isinstance(word_or_phrase, str): raise Exception("join() accepts only strings") joined: st...
--- +++ @@ -1,6 +1,43 @@+""" +Program to join a list of strings with a separator +""" def join(separator: str, separated: list[str]) -> str: + """ + Joins a list of strings using a separator + and returns the result. + + :param separator: Separator to be used + for joining the strings. +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/join.py
Document helper functions with docstrings
from __future__ import annotations def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None: if (direction == 1 and array[index1] > array[index2]) or ( direction == 0 and array[index1] < array[index2] ): array[index1], array[index2] = array[index2], array[index1] ...
--- +++ @@ -1,8 +1,37 @@+""" +Python program for Bitonic Sort. + +Note that this program works only when size of input is a power of 2. +""" from __future__ import annotations def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None: + """Compare the value at given index1 and ind...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bitonic_sort.py
Generate docstrings for this script
def gnome_sort(lst: list) -> list: if len(lst) <= 1: return lst i = 1 while i < len(lst): if lst[i - 1] <= lst[i]: i += 1 else: lst[i - 1], lst[i] = lst[i], lst[i - 1] i -= 1 if i == 0: i = 1 return lst if __n...
--- +++ @@ -1,6 +1,38 @@+""" +Gnome Sort Algorithm (A.K.A. Stupid Sort) + +This algorithm iterates over a list comparing an element with the previous one. +If order is not respected, it swaps element backward until order is respected with +previous element. It resumes the initial iteration from element new position. +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/gnome_sort.py
Add docstrings for better understanding
from collections import Counter from functools import total_ordering from data_structures.heap.heap import Heap @total_ordering class WordCount: def __init__(self, word: str, count: int) -> None: self.word = word self.count = count def __eq__(self, other: object) -> bool: if not isi...
--- +++ @@ -1,3 +1,17 @@+""" +Finds the top K most frequent words from the provided word list. + +This implementation aims to show how to solve the problem using the Heap class +already present in this repository. +Computing order statistics is, in fact, a typical usage of heaps. + +This is mostly shown for educational...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/top_k_frequent_words.py
Create docstrings for all classes and functions
def cocktail_shaker_sort(arr: list[int]) -> list[int]: start, end = 0, len(arr) - 1 while start < end: swapped = False # Pass from left to right for i in range(start, end): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swa...
--- +++ @@ -1,6 +1,34 @@+""" +An implementation of the cocktail shaker sort algorithm in pure Python. + +https://en.wikipedia.org/wiki/Cocktail_shaker_sort +""" def cocktail_shaker_sort(arr: list[int]) -> list[int]: + """ + Sorts a list using the Cocktail Shaker Sort algorithm. + + :param arr: List of ele...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/cocktail_shaker_sort.py
Generate NumPy-style docstrings
def comb_sort(data: list) -> list: shrink_factor = 1.3 gap = len(data) completed = False while not completed: # Update the gap value for a next comb gap = int(gap / shrink_factor) if gap <= 1: completed = True index = 0 while index + gap < len(data...
--- +++ @@ -1,6 +1,36 @@+""" +This is pure Python implementation of comb sort algorithm. +Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz +Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991. +Comb sort improves on bubble sort algorithm. +In bubble so...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/comb_sort.py
Add standardized docstrings across the file
def counting_sort(collection): # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection coll_len = len(collection) coll_max = max(collection) coll_min = min(collection) # create the counting array counting_arr_leng...
--- +++ @@ -1,6 +1,27 @@+""" +This is pure Python implementation of counting sort algorithm +For doctests run following command: +python -m doctest -v counting_sort.py +or +python3 -m doctest -v counting_sort.py +For manual testing run: +python counting_sort.py +""" def counting_sort(collection): + """Pure impl...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/counting_sort.py
Document all endpoints with docstrings
import random def bogo_sort(collection: list) -> list: def is_sorted(collection: list) -> bool: for i in range(len(collection) - 1): if collection[i] > collection[i + 1]: return False return True while not is_sorted(collection): random.shuffle(collection)...
--- +++ @@ -1,8 +1,34 @@+""" +This is a pure Python implementation of the bogosort algorithm, +also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. +Bogosort generates random permutations until it guesses the correct one. + +More info on: https://en.wikipedia.org/wiki/Bogosort + +For doc...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bogo_sort.py
Add docstrings to incomplete code
# Python program to sort a sequence containing only 0, 1 and 2 in a single pass. red = 0 # The first color of the flag. white = 1 # The second color of the flag. blue = 2 # The third color of the flag. colors = (red, white, blue) def dutch_national_flag_sort(sequence: list) -> list: if not sequence: r...
--- +++ @@ -1,3 +1,27 @@+""" +A pure implementation of Dutch national flag (DNF) sort algorithm in Python. +Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra. +It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can +sort a sequence of n size with [0 <= a...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/dutch_national_flag_sort.py
Add docstrings that explain logic
def cyclic_sort(nums: list[int]) -> list[int]: # Perform cyclic sort index = 0 while index < len(nums): # Calculate the correct index for the current element correct_index = nums[index] - 1 # If the current element is not at its correct position, # swap it with the element...
--- +++ @@ -1,6 +1,33 @@+""" +This is a pure Python implementation of the Cyclic Sort algorithm. + +For doctests run following command: +python -m doctest -v cyclic_sort.py +or +python3 -m doctest -v cyclic_sort.py +For manual testing run: +python cyclic_sort.py +or +python3 cyclic_sort.py +""" def cyclic_sort(num...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/cyclic_sort.py
Add detailed docstrings explaining each function
import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = arr...
--- +++ @@ -1,8 +1,30 @@+""" +Introspective Sort is a hybrid sort (Quick Sort + Heap Sort + Insertion Sort) +if the size of the list is under 16, use insertion sort +https://en.wikipedia.org/wiki/Introsort +""" import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: + """ + >>> ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/intro_sort.py
Create simple docstrings for beginners
from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_o...
--- +++ @@ -1,8 +1,32 @@+""" +Python implementation of the MSD radix sort algorithm. +It used the binary representation of the integers to sort +them. +https://en.wikipedia.org/wiki/Radix_sort +""" from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: + """ + Impleme...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/msd_radix_sort.py
Write Python docstrings for this snippet
from collections.abc import MutableSequence from typing import Any, Protocol, TypeVar class Comparable(Protocol): def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) def insertion_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]: for insert_index in r...
--- +++ @@ -1,3 +1,17 @@+""" +A pure Python implementation of the insertion sort algorithm + +This algorithm sorts a collection by comparing adjacent elements. +When it finds that order is not respected, it moves the element compared +backward until the order is correct. It then goes back directly to the +element's in...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/insertion_sort.py
Add docstrings for utility scripts
def naive_pattern_search(s: str, pattern: str) -> list: pat_len = len(pattern) position = [] for i in range(len(s) - pat_len + 1): match_found = True for j in range(pat_len): if s[i + j] != pattern[j]: match_found = False break if match_f...
--- +++ @@ -1,6 +1,27 @@+""" +https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search +this algorithm tries to find the pattern from every position of +the mainString if pattern is found from position i it add it to +the answer and does the same for position i+1 +Complexity : O(n*m) + n=len...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/naive_string_search.py
Provide clean and structured docstrings
from __future__ import annotations def binary_search_insertion(sorted_list, item): left = 0 right = len(sorted_list) - 1 while left <= right: middle = (left + right) // 2 if left == right: if sorted_list[middle] < item: left = middle + 1 break ...
--- +++ @@ -1,8 +1,24 @@+""" +This is a pure Python implementation of the merge-insertion sort algorithm +Source: https://en.wikipedia.org/wiki/Merge-insertion_sort + +For doctests run following command: +python3 -m doctest -v merge_insertion_sort.py +or +python -m doctest -v merge_insertion_sort.py + +For manual testi...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/merge_insertion_sort.py
Add docstrings for production code
import string email_tests: tuple[tuple[str, bool], ...] = ( ("simple@example.com", True), ("very.common@example.com", True), ("disposable.style.email.with+symbol@example.com", True), ("other-email-with-hyphen@and.subdomains.example.com", True), ("fully-qualified-domain@example.com", True), ("u...
--- +++ @@ -1,3 +1,8 @@+""" +Implements an is valid email address algorithm + +@ https://en.wikipedia.org/wiki/Email_address +""" import string @@ -36,6 +41,36 @@ def is_valid_email_address(email: str) -> bool: + """ + Returns True if the passed email address is valid. + + The local part of the email ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/is_valid_email_address.py
Add detailed documentation for each class
# Algorithms to determine if a string is palindrome from timeit import timeit test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" "abcdba": False, "A...
--- +++ @@ -19,6 +19,12 @@ def is_palindrome(s: str) -> bool: + """ + Return True if s is a palindrome otherwise return False. + + >>> all(is_palindrome(key) == value for key, value in test_data.items()) + True + """ start_i = 0 end_i = len(s) - 1 @@ -32,6 +38,12 @@ def is_palindrome_...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/palindrome.py
Write reusable docstrings
def prefix_function(input_string: str) -> list: # list for the result values prefix_result = [0] * len(input_string) for i in range(1, len(input_string)): # use last results for better performance - dynamic programming j = prefix_result[i - 1] while j > 0 and input_string[i] != i...
--- +++ @@ -1,6 +1,29 @@+""" +https://cp-algorithms.com/string/prefix-function.html + +Prefix function Knuth-Morris-Pratt algorithm + +Different algorithm than Knuth-Morris-Pratt pattern finding + +E.x. Finding longest prefix which is also suffix + +Time Complexity: O(n) - where n is the length of the string +""" ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/prefix_function.py
Add docstrings to improve code quality
def cycle_sort(array: list) -> list: array_len = len(array) for cycle_start in range(array_len - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 if pos == cycle_start: ...
--- +++ @@ -1,6 +1,23 @@+""" +Code contributed by Honey Sharma +Source: https://en.wikipedia.org/wiki/Cycle_sort +""" def cycle_sort(array: list) -> list: + """ + >>> cycle_sort([4, 3, 2, 1]) + [1, 2, 3, 4] + + >>> cycle_sort([-4, 20, 0, -50, 100, -1]) + [-50, -4, -1, 0, 20, 100] + + >>> cycle_so...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/cycle_sort.py
Help me add docstrings to my project
def merge_sort(collection: list) -> list: def merge(left: list, right: list) -> list: result = [] while left and right: result.append(left.pop(0) if left[0] <= right[0] else right.pop(0)) result.extend(left) result.extend(right) return result if len(collec...
--- +++ @@ -1,8 +1,42 @@+""" +This is a pure Python implementation of the merge sort algorithm. + +For doctests run following command: +python -m doctest -v merge_sort.py +or +python3 -m doctest -v merge_sort.py +For manual testing run: +python merge_sort.py +""" def merge_sort(collection: list) -> list: + """ ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/merge_sort.py
Generate helpful docstrings for debugging
from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = re...
--- +++ @@ -1,8 +1,22 @@+""" +Implementation of iterative merge sort in Python +Author: Aman Gupta + +For doctests run following command: +python3 -m doctest -v iterative_merge_sort.py + +For manual testing run: +python3 iterative_merge_sort.py +""" from __future__ import annotations def merge(input_list: list,...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/iterative_merge_sort.py
Document all public functions with docstrings
def heapify(unsorted: list[int], index: int, heap_size: int) -> None: largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > ...
--- +++ @@ -1,6 +1,22 @@+""" +A pure Python implementation of the heap sort algorithm. +""" def heapify(unsorted: list[int], index: int, heap_size: int) -> None: + """ + :param unsorted: unsorted list containing integers numbers + :param index: index + :param heap_size: size of the heap + :return: N...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/heap_sort.py
Generate docstrings for each module
import re """ general info: https://en.wikipedia.org/wiki/Naming_convention_(programming)#Python_and_Ruby pascal case [ an upper Camel Case ]: https://en.wikipedia.org/wiki/Camel_case camel case: https://en.wikipedia.org/wiki/Camel_case kebab case [ can be found in general info ]: https://en.wikipedia.org/wiki/Nami...
--- +++ @@ -17,10 +17,24 @@ # assistant functions def split_input(str_: str) -> list: + """ + >>> split_input("one two 31235three4four") + [['one', 'two', '31235three4four']] + """ return [char.split() for char in re.split(r"[^ a-z A-Z 0-9 \s]", str_)] def to_simple_case(str_: str) -> str: + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/string_switch_case.py
Add docstrings including usage examples
def to_title_case(word: str) -> str: """ Convert the first character to uppercase if it's lowercase """ if "a" <= word[0] <= "z": word = chr(ord(word[0]) - 32) + word[1:] """ Convert the remaining characters to lowercase if they are uppercase """ for i in range(1, len(word)): ...
--- +++ @@ -1,27 +1,57 @@-def to_title_case(word: str) -> str: - - """ - Convert the first character to uppercase if it's lowercase - """ - if "a" <= word[0] <= "z": - word = chr(ord(word[0]) - 32) + word[1:] - - """ - Convert the remaining characters to lowercase if they are uppercase - """...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/title.py
Can you add docstrings to this Python file?
def match_pattern(input_string: str, pattern: str) -> bool: len_string = len(input_string) + 1 len_pattern = len(pattern) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stand...
--- +++ @@ -1,6 +1,58 @@+""" +Implementation of regular expression matching with support for '.' and '*'. +'.' Matches any single character. +'*' Matches zero or more of the preceding element. +The matching should cover the entire input string (not partial). + +""" def match_pattern(input_string: str, pattern: str...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/wildcard_pattern_matching.py
Write clean docstrings for readability
def z_function(input_str: str) -> list[int]: z_result = [0 for i in range(len(input_str))] # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_point...
--- +++ @@ -1,6 +1,32 @@+""" +https://cp-algorithms.com/string/z-function.html + +Z-function or Z algorithm + +Efficient algorithm for pattern occurrence in a string + +Time Complexity: O(n) - where n is the length of the string + +""" def z_function(input_str: str) -> list[int]: + """ + For the given string...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/z_function.py
Create simple docstrings for beginners
# /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # ] # /// import os import httpx URL_BASE = "https://www.amdoren.com/api/currency.php" # Currency and their description list_of_currencies = """ AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Net...
--- +++ @@ -1,3 +1,7 @@+""" +This is used to convert the currency using the Amdoren Currency API +https://www.amdoren.com +""" # /// script # requires-python = ">=3.13" @@ -174,6 +178,7 @@ def convert_currency( from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = "" ) -> str: + """https...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/currency_converter.py
Can you add docstrings to this Python file?
# /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # ] # /// from __future__ import annotations __author__ = "Muhammad Umer Farooq" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Muhammad Umer Farooq" __email__ = "contact@muhammadumerfarooq.me" __status__ = "Alpha" import re fr...
--- +++ @@ -1,3 +1,4 @@+"""Get the site emails from URL.""" # /// script # requires-python = ">=3.13" @@ -29,6 +30,9 @@ self.domain = domain def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + """ + This function parse html to take takes url from tags + ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/emails_from_url.py
Document functions with detailed explanations
#!/usr/bin/env python3 # /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # ] # /// from __future__ import annotations import os from typing import Any import httpx BASE_URL = "https://api.github.com" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authentic...
--- +++ @@ -1,4 +1,22 @@ #!/usr/bin/env python3 +""" +Created by sarathkaul on 14/11/19 +Updated by lawric1 on 24/11/20 + +Authentication will be made via access token. +To generate your personal access token visit https://github.com/settings/tokens. + +NOTE: +Never hardcode any credential information in the code. Alwa...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/fetch_github_info.py
Add docstrings to make code maintainable
import httpx from bs4 import BeautifulSoup BASE_URL = "https://www.wellrx.com/prescriptions/{}/{}/?freshSearch=true" def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None: try: # Has user provided both inputs? if not drug_name or not zip_code: return None ...
--- +++ @@ -1,3 +1,9 @@+""" + +Scrape the price and pharmacy name for a prescription drug from rx site +after providing the drug name and zipcode. + +""" import httpx from bs4 import BeautifulSoup @@ -6,6 +12,27 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None: + """[summary...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/fetch_well_rx_price.py
Add docstrings following best practices
# /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # "rich", # ] # /// from datetime import UTC, date, datetime import httpx from rich import box from rich import console as rich_console from rich import table as rich_table LIMIT = 10 TODAY = datetime.now(tz=UTC) API_URL = ( "https:...
--- +++ @@ -1,3 +1,7 @@+""" +CAUTION: You may get a json.decoding error. +This works for some of us but fails for others. +""" # /// script # requires-python = ">=3.13" @@ -24,6 +28,29 @@ def years_old(birth_timestamp: int, today: date | None = None) -> int: + """ + Calculate the age in years based on the...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/get_top_billionaires.py
Generate docstrings for each module
# /// script # requires-python = ">=3.13" # dependencies = [ # "beautifulsoup4", # "fake-useragent", # "httpx", # ] # /// import os import httpx from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} URL = "https://www.mywaifulist.moe/random" def ...
--- +++ @@ -18,12 +18,18 @@ def save_image(image_url: str, image_title: str) -> None: + """ + Saves the image of anime character + """ image = httpx.get(image_url, headers=headers, timeout=10) with open(image_title, "wb") as file: file.write(image.content) def random_anime_character...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/random_anime_character.py
Add docstrings to improve collaboration
# /// script # requires-python = ">=3.13" # dependencies = [ # "beautifulsoup4", # "fake-useragent", # "httpx", # ] # /// import httpx from bs4 import BeautifulSoup, NavigableString, Tag from fake_useragent import UserAgent BASE_URL = "https://ww7.gogoanime2.org" def search_scraper(anime_name: str) -> l...
--- +++ @@ -15,6 +15,23 @@ def search_scraper(anime_name: str) -> list: + """[summary] + + Take an url and + return list of anime after scraping the site. + + >>> type(search_scraper("demon_slayer")) + <class 'list'> + + Args: + anime_name (str): [Name of anime] + + Raises: + e: [...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/fetch_anime_and_play.py
Expand my code with proper documentation strings
# /// script # requires-python = ">=3.13" # dependencies = [ # "beautifulsoup4", # "httpx", # "pandas", # ] # /// from itertools import zip_longest import httpx from bs4 import BeautifulSoup from pandas import DataFrame def get_amazon_product_data(product: str = "laptop") -> DataFrame: url = f"http...
--- +++ @@ -1,3 +1,8 @@+""" +This file provides a function which will take a product name as input from the user, +and fetch from Amazon information about products of this name or category. The product +information will include title, URL, price, ratings, and the discount available. +""" # /// script # requires-py...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/get_amazon_product_data.py
Write docstrings for this repository
# /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # ] # /// from json import JSONDecodeError import httpx def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict: new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes if new_olid.count("/") != 1...
--- +++ @@ -1,3 +1,8 @@+""" +Get book and author data from https://openlibrary.org + +ISBN: https://en.wikipedia.org/wiki/International_Standard_Book_Number +""" # /// script # requires-python = ">=3.13" @@ -12,6 +17,17 @@ def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict: + """ + Given an '...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/search_books_by_isbn.py
Write proper docstrings for these functions
# This script is copied from the compvis/stable-diffusion repo (aka the SD V1 repo) # Original filename: ldm/models/diffusion/ddpm.py # The purpose to reinstate the old DDPM logic which works with VQ, whereas the V2 one doesn't # Some models such as LDSR require VQ to work correctly # The classes are suffixed with "V1"...
--- +++ @@ -31,6 +31,8 @@ def disabled_train(self, mode=True): + """Overwrite model.train with this function to make sure train/eval mode + does not change anymore.""" return self @@ -199,6 +201,12 @@ print(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): + ...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/LDSR/sd_hijack_ddpm_v1.py
Add docstrings for internal functions
#!/usr/bin/env python3 # /// script # requires-python = ">=3.13" # dependencies = [ # "beautifulsoup4", # "fake-useragent", # "httpx", # ] # /// from __future__ import annotations import json import httpx from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAge...
--- +++ @@ -21,18 +21,34 @@ def extract_user_profile(script) -> dict: + """ + May raise json.decoder.JSONDecodeError + """ data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: +...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/instagram_crawler.py
Generate docstrings with parameter types
# /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # ] # /// import httpx def get_apod_data(api_key: str) -> dict: url = "https://api.nasa.gov/planetary/apod" return httpx.get(url, params={"api_key": api_key}, timeout=10).json() def save_apod(api_key: str, path: str = ".") -> dict:...
--- +++ @@ -9,6 +9,10 @@ def get_apod_data(api_key: str) -> dict: + """ + Get the APOD(Astronomical Picture of the day) data + Get your API Key from: https://api.nasa.gov/ + """ url = "https://api.nasa.gov/planetary/apod" return httpx.get(url, params={"api_key": api_key}, timeout=10).json() ...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/nasa_data.py
Create Google-style docstrings for my code
#!/usr/bin/env python3 # /// script # requires-python = ">=3.13" # dependencies = [ # "beautifulsoup4", # "httpx", # ] # /// import httpx from bs4 import BeautifulSoup def world_covid19_stats( url: str = "https://www.worldometers.info/coronavirus/", ) -> dict: soup = BeautifulSoup( httpx.ge...
--- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python3 +""" +Provide the current worldwide COVID-19 statistics. +This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. +""" # /// script # requires-python = ">=3.13" @@ -16,6 +20,9 @@ def world_covid19_stats( url: str = "https://www.worldometer...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/world_covid19_stats.py
Document helper functions with docstrings
from __future__ import annotations import gradio as gr import logging import os import re import lora_patches import network import network_lora import network_glora import network_hada import network_ia3 import network_lokr import network_full import network_norm import network_oft import torch from typing import Un...
--- +++ @@ -1,728 +1,737 @@-from __future__ import annotations -import gradio as gr -import logging -import os -import re - -import lora_patches -import network -import network_lora -import network_glora -import network_hada -import network_ia3 -import network_lokr -import network_full -import network_norm -import netw...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/Lora/networks.py
Add docstrings to existing functions
import json import os import os.path import threading import diskcache import tqdm from modules.paths import data_path, script_path cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json")) cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache")) caches =...
--- +++ @@ -1,92 +1,123 @@-import json -import os -import os.path -import threading - -import diskcache -import tqdm - -from modules.paths import data_path, script_path - -cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json")) -cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.p...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/cache.py
Create structured documentation for my script
import sys import contextlib from functools import lru_cache import torch from modules import errors, shared, npu_specific if sys.platform == "darwin": from modules import mac_specific if shared.cmd_opts.use_ipex: from modules import xpu_specific def has_xpu() -> bool: return shared.cmd_opts.use_ipex a...
--- +++ @@ -267,6 +267,10 @@ @lru_cache def first_time_calculation(): + """ + just do any calculation with pytorch layers - the first time this is done it allocates about 700MB of memory and + spends about 2.7 seconds doing that, at least with NVidia. + """ x = torch.zeros((1, 1)).to(device, dtype...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/devices.py
Write docstrings that follow conventions
from __future__ import annotations from dataclasses import dataclass from typing import Callable from functools import wraps, cache import math import torch.nn as nn import random from einops import rearrange @dataclass class HypertileParams: depth = 0 layer_name = "" tile_size: int = 0 swap_size...
--- +++ @@ -1,3 +1,8 @@+""" +Hypertile module for splitting attention layers in SD-1.5 U-Net and SD-1.5 VAE +Warn: The patch works well only if the input image has a width and height that are multiples of 128 +Original author: @tfernd Github: https://github.com/tfernd/HyperTile +""" from __future__ import annotation...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/hypertile/hypertile.py
Include argument descriptions in docstrings
import json import os import re import logging from collections import defaultdict from modules import errors extra_network_registry = {} extra_network_aliases = {} def initialize(): extra_network_registry.clear() extra_network_aliases.clear() def register_extra_network(extra_network): extra_network_r...
--- +++ @@ -1,175 +1,225 @@-import json -import os -import re -import logging -from collections import defaultdict - -from modules import errors - -extra_network_registry = {} -extra_network_aliases = {} - - -def initialize(): - extra_network_registry.clear() - extra_network_aliases.clear() - - -def register_extr...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/extra_networks.py
Generate docstrings with examples
import base64 import io import os import time import datetime import uvicorn import ipaddress import requests import gradio as gr from threading import Lock from io import BytesIO from fastapi import APIRouter, Depends, FastAPI, Request, Response from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi...
--- +++ @@ -56,6 +56,7 @@ def verify_url(url): + """Returns True if the url refers to a global resource.""" import socket from urllib.parse import urlparse @@ -360,6 +361,12 @@ return script_args def apply_infotext(self, request, tabname, *, script_runner=None, mentioned_script_args=No...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/api/api.py
Generate docstrings for each module
from __future__ import annotations import logging import os from functools import cached_property from typing import TYPE_CHECKING, Callable import cv2 import numpy as np import torch from modules import devices, errors, face_restoration, shared if TYPE_CHECKING: from facexlib.utils.face_restoration_helper impo...
--- +++ @@ -18,6 +18,7 @@ def bgr_image_to_rgb_tensor(img: np.ndarray) -> torch.Tensor: + """Convert a BGR NumPy image in [0..1] range to a PyTorch RGB float32 tensor.""" assert img.shape[2] == 3, "image must be RGB" if img.dtype == "float64": img = img.astype("float32") @@ -26,6 +27,9 @@ ...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/face_restoration_utils.py
Add return value explanations in docstrings
import numpy as np import gradio as gr import math from modules.ui_components import InputAccordion import modules.scripts as scripts from modules.torch_utils import float64 class SoftInpaintingSettings: def __init__(self, mask_blend_power, mask_blend_scale, inpa...
--- +++ @@ -48,6 +48,12 @@ def latent_blend(settings, a, b, t): + """ + Interpolates two latent image representations according to the parameter t, + where the interpolated vectors' magnitudes are also interpolated separately. + The "detail_preservation" factor biases the magnitude interpolation towards...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/soft-inpainting/scripts/soft_inpainting.py
Add docstrings explaining edge cases
import inspect from pydantic import BaseModel, Field, create_model from typing import Any, Optional, Literal from inflection import underscore from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img from modules.shared import sd_upscalers, opts, parser API_NOT_ALLOWED = [ ...
--- +++ @@ -25,6 +25,7 @@ ] class ModelDef(BaseModel): + """Assistance Class for Pydantic Dynamic Model Generation""" field: str field_alias: str @@ -34,6 +35,11 @@ class PydanticModelGenerator: + """ + Takes in created classes and stubs them out in a way FastAPI/Pydantic is happy about: + ...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/api/models.py
Include argument descriptions in docstrings
from __future__ import annotations import configparser import dataclasses import os import threading import re from modules import shared, errors, cache, scripts from modules.gitpython_hack import Repo from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401 extensions: li...
--- +++ @@ -1,294 +1,299 @@-from __future__ import annotations - -import configparser -import dataclasses -import os -import threading -import re - -from modules import shared, errors, cache, scripts -from modules.gitpython_hack import Repo -from modules.paths_internal import extensions_dir, extensions_builtin_dir, scr...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/extensions.py
Create docstrings for each class method
from __future__ import annotations import datetime import functools import pytz import io import math import os from collections import namedtuple import re import numpy as np import piexif import piexif.helper from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImagePlugin, ImageOps # pillow_avif needs to be...
--- +++ @@ -1,811 +1,877 @@-from __future__ import annotations - -import datetime -import functools -import pytz -import io -import math -import os -from collections import namedtuple -import re - -import numpy as np -import piexif -import piexif.helper -from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImage...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/images.py
Add standardized docstrings across the file
### This file contains impls for underlying related models (CLIP, T5, etc) import torch import math from torch import nn from transformers import CLIPTokenizer, T5TokenizerFast from modules import sd_hijack ################################################################################################# ### Core/Ut...
--- +++ @@ -14,12 +14,19 @@ class AutocastLinear(nn.Linear): + """Same as usual linear layer, but casts its weights to whatever the parameter type is. + + This is different from torch.autocast in a way that float16 layer processing float32 input + will return float16 with autocast on, and float32 with this...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/sd3/other_impls.py
Improve my code by adding docstrings
import json import os import signal import sys import re from modules.timer import startup_timer def gradio_server_name(): from modules.shared_cmd_options import cmd_opts if cmd_opts.server_name: return cmd_opts.server_name else: return "0.0.0.0" if cmd_opts.listen else None def fix_to...
--- +++ @@ -1,197 +1,215 @@-import json -import os -import signal -import sys -import re - -from modules.timer import startup_timer - - -def gradio_server_name(): - from modules.shared_cmd_options import cmd_opts - - if cmd_opts.server_name: - return cmd_opts.server_name - else: - return "0.0.0.0...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/initialize_util.py
Generate descriptive docstrings automatically
import importlib import logging import os import sys import warnings from threading import Thread from modules.timer import startup_timer def imports(): logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh... logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is no...
--- +++ @@ -1,160 +1,169 @@-import importlib -import logging -import os -import sys -import warnings -from threading import Thread - -from modules.timer import startup_timer - - -def imports(): - logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh... - logging.getLogger("xformers").addFilter...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/initialize.py
Auto-generate documentation strings for this file
from __future__ import annotations import base64 import io import json import os import re import sys import gradio as gr from modules.paths import data_path from modules import shared, ui_tempdir, script_callbacks, processing, infotext_versions, images, prompt_parser, errors from PIL import Image sys.modules['module...
--- +++ @@ -1,510 +1,546 @@-from __future__ import annotations -import base64 -import io -import json -import os -import re -import sys - -import gradio as gr -from modules.paths import data_path -from modules import shared, ui_tempdir, script_callbacks, processing, infotext_versions, images, prompt_parser, errors -fro...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/infotext_utils.py
Improve my code by adding docstrings
from PIL import Image, ImageFilter, ImageOps def get_crop_region_v2(mask, pad=0): mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask) if box := mask.getbbox(): x1, y1, x2, y2 = box return (max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.s...
--- +++ @@ -1,73 +1,96 @@-from PIL import Image, ImageFilter, ImageOps - - -def get_crop_region_v2(mask, pad=0): - mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask) - if box := mask.getbbox(): - x1, y1, x2, y2 = box - return (max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, ma...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/masking.py
Document helper functions with docstrings
from __future__ import annotations import importlib import logging import os from typing import TYPE_CHECKING from urllib.parse import urlparse import torch from modules import shared from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone if TYPE_CHECKING: import spandrel logger ...
--- +++ @@ -25,6 +25,10 @@ file_name: str | None = None, hash_prefix: str | None = None, ) -> str: + """Download a file from `url` into `model_dir`, using the file present if possible. + + Returns the path to the downloaded file. + """ os.makedirs(model_dir, exist_ok=True) if not file_name:...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/modelloader.py
Write docstrings describing functionality
import torch from modules import devices, rng_philox, shared def randn(seed, shape, generator=None): manual_seed(seed) if shared.opts.randn_source == "NV": return torch.asarray((generator or nv_rng).randn(shape), device=devices.device) if shared.opts.randn_source == "CPU" or devices.device.typ...
--- +++ @@ -1,157 +1,170 @@-import torch - -from modules import devices, rng_philox, shared - - -def randn(seed, shape, generator=None): - - manual_seed(seed) - - if shared.opts.randn_source == "NV": - return torch.asarray((generator or nv_rng).randn(shape), device=devices.device) - - if shared.opts.ran...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/rng.py
Document my Python code with docstrings
### This file contains impls for MM-DiT, the core model component of SD3 import math from typing import Dict, Optional import numpy as np import torch import torch.nn as nn from einops import rearrange, repeat from modules.models.sd3.other_impls import attention, Mlp class PatchEmbed(nn.Module): def __init__( ...
--- +++ @@ -10,6 +10,7 @@ class PatchEmbed(nn.Module): + """ 2D Image to Patch Embedding""" def __init__( self, img_size: Optional[int] = 224, @@ -61,6 +62,11 @@ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0, scaling_factor=None, offset=None)...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/sd3/mmdit.py
Write Python docstrings for this snippet
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion). # See more details in LICENSE. import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from context...
--- +++ @@ -1,3 +1,10 @@+""" +wild mixture of +https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py +https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/diffusion/ddpm_edit.py
Write reusable docstrings
### Impls of the SD3 core diffusion model and VAE import torch import math import einops from modules.models.sd3.mmdit import MMDiT from PIL import Image ################################################################################################# ### MMDiT Model Wrapping ########################################...
--- +++ @@ -13,6 +13,7 @@ class ModelSamplingDiscreteFlow(torch.nn.Module): + """Helper for sampler scheduling (ie timestep/sigma calculations) for Discrete Flow models""" def __init__(self, shift=1.0): super().__init__() self.shift = shift @@ -46,6 +47,7 @@ class BaseModel(torch.nn.Mo...
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/sd3/sd3_impls.py