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 = key or self.__key or 1 # make sure key is an appropriate size key %= 256 return [chr(ord(ch) ^ key) for ch in content] def decrypt(self, content: str, key: int) -> list[str]: # precondition assert isinstance(key, int) assert isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 256 return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self, content: str, key: int = 0) -> str: # precondition assert isinstance(key, int) assert isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 256 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def decrypt_string(self, content: str, key: int = 0) -> str: # precondition assert isinstance(key, int) assert isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 256 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def encrypt_file(self, file: str, key: int = 0) -> bool: # precondition assert isinstance(file, str) assert isinstance(key, int) # make sure key is an appropriate size key %= 256 try: with open(file) as fin, open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) except OSError: return False return True def decrypt_file(self, file: str, key: int) -> bool: # precondition assert isinstance(file, str) assert isinstance(key, int) # make sure key is an appropriate size key %= 256 try: with open(file) as fin, open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True if __name__ == "__main__": from doctest import testmod testmod() # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
--- +++ @@ -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_string : str +- decrypt_string : str +- encrypt_file : boolean +- decrypt_file : boolean +""" from __future__ import annotations class XORCipher: def __init__(self, key: int = 0): + """ + simple constructor that receives a key or uses + default key = 0 + """ # private field self.__key = key def encrypt(self, content: str, key: int) -> list[str]: + """ + input: 'content' of type string and 'key' of type int + output: encrypted string 'content' as a list of chars + if key not passed the method uses the key by the constructor. + otherwise key = 1 + + Empty list + >>> XORCipher().encrypt("", 5) + [] + + One key + >>> XORCipher().encrypt("hallo welt", 1) + ['i', '`', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u'] + + Normal key + >>> XORCipher().encrypt("HALLO WELT", 32) + ['h', 'a', 'l', 'l', 'o', '\\x00', 'w', 'e', 'l', 't'] + + Key greater than 255 + >>> XORCipher().encrypt("hallo welt", 256) + ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't'] + """ # precondition assert isinstance(key, int) @@ -22,6 +66,28 @@ return [chr(ord(ch) ^ key) for ch in content] def decrypt(self, content: str, key: int) -> list[str]: + """ + input: 'content' of type list and 'key' of type int + output: decrypted string 'content' as a list of chars + if key not passed the method uses the key by the constructor. + otherwise key = 1 + + Empty list + >>> XORCipher().decrypt("", 5) + [] + + One key + >>> XORCipher().decrypt("hallo welt", 1) + ['i', '`', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u'] + + Normal key + >>> XORCipher().decrypt("HALLO WELT", 32) + ['h', 'a', 'l', 'l', 'o', '\\x00', 'w', 'e', 'l', 't'] + + Key greater than 255 + >>> XORCipher().decrypt("hallo welt", 256) + ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't'] + """ # precondition assert isinstance(key, int) @@ -35,6 +101,28 @@ return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self, content: str, key: int = 0) -> str: + """ + input: 'content' of type string and 'key' of type int + output: encrypted string 'content' + if key not passed the method uses the key by the constructor. + otherwise key = 1 + + Empty list + >>> XORCipher().encrypt_string("", 5) + '' + + One key + >>> XORCipher().encrypt_string("hallo welt", 1) + 'i`mmn!vdmu' + + Normal key + >>> XORCipher().encrypt_string("HALLO WELT", 32) + 'hallo\\x00welt' + + Key greater than 255 + >>> XORCipher().encrypt_string("hallo welt", 256) + 'hallo welt' + """ # precondition assert isinstance(key, int) @@ -54,6 +142,28 @@ return ans def decrypt_string(self, content: str, key: int = 0) -> str: + """ + input: 'content' of type string and 'key' of type int + output: decrypted string 'content' + if key not passed the method uses the key by the constructor. + otherwise key = 1 + + Empty list + >>> XORCipher().decrypt_string("", 5) + '' + + One key + >>> XORCipher().decrypt_string("hallo welt", 1) + 'i`mmn!vdmu' + + Normal key + >>> XORCipher().decrypt_string("HALLO WELT", 32) + 'hallo\\x00welt' + + Key greater than 255 + >>> XORCipher().decrypt_string("hallo welt", 256) + 'hallo welt' + """ # precondition assert isinstance(key, int) @@ -73,6 +183,13 @@ return ans def encrypt_file(self, file: str, key: int = 0) -> bool: + """ + input: filename (str) and a key (int) + output: returns true if encrypt process was + successful otherwise false + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ # precondition assert isinstance(file, str) @@ -93,6 +210,13 @@ return True def decrypt_file(self, file: str, key: int) -> bool: + """ + input: filename (str) and a key (int) + output: returns true if decrypt process was + successful otherwise false + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ # precondition assert isinstance(file, str) @@ -141,4 +265,4 @@ # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: -# print("decrypt unsuccessful")+# print("decrypt unsuccessful")
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.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ed message:") print(translated) def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = [] key_index = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index]) elif mode == "decrypt": num -= LETTERS.find(key[key_index]) num %= len(LETTERS) if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) key_index += 1 if key_index == len(key): key_index = 0 else: translated.append(symbol) return "".join(translated) if __name__ == "__main__": main()
--- +++ @@ -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: str) -> str: + """ + >>> decrypt_message('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.') + 'This is Harshil Darji from Dharmaj.' + """ return translate_message(key, message, "decrypt") @@ -54,4 +62,4 @@ if __name__ == "__main__": - main()+ main()
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: normalized = (image - np.min(image)) / (np.max(image) - np.min(image)) * cap return normalized.astype(data_type) def normalize_array(array: np.ndarray, cap: float = 1) -> np.ndarray: diff = np.max(array) - np.min(array) return (array - np.min(array)) / (1 if diff == 0 else diff) * cap def grayscale(image: np.ndarray) -> np.ndarray: return np.dot(image[:, :, 0:3], [0.299, 0.587, 0.114]).astype(np.uint8) def binarize(image: np.ndarray, threshold: float = 127.0) -> np.ndarray: return np.where(image > threshold, 1, 0) def transform( image: np.ndarray, kind: str, kernel: np.ndarray | None = None ) -> np.ndarray: if kernel is None: kernel = np.ones((3, 3)) if kind == "erosion": constant = 1 apply = np.max else: constant = 0 apply = np.min center_x, center_y = (x // 2 for x in kernel.shape) # Use padded image when applying convolution # to not go out of bounds of the original the image transformed = np.zeros(image.shape, dtype=np.uint8) padded = np.pad(image, 1, "constant", constant_values=constant) for x in range(center_x, padded.shape[0] - center_x): for y in range(center_y, padded.shape[1] - center_y): center = padded[ x - center_x : x + center_x + 1, y - center_y : y + center_y + 1 ] # Apply transformation method to the centered section of the image transformed[x - center_x, y - center_y] = apply(center[kernel == 1]) return transformed def opening_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray: if kernel is None: np.ones((3, 3)) return transform(transform(image, "dilation", kernel), "erosion", kernel) def closing_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray: if kernel is None: kernel = np.ones((3, 3)) return transform(transform(image, "erosion", kernel), "dilation", kernel) def binary_mask( image_gray: np.ndarray, image_map: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: true_mask, false_mask = image_gray.copy(), image_gray.copy() true_mask[image_map == 1] = 1 false_mask[image_map == 0] = 0 return true_mask, false_mask def matrix_concurrency(image: np.ndarray, coordinate: tuple[int, int]) -> np.ndarray: matrix = np.zeros([np.max(image) + 1, np.max(image) + 1]) offset_x, offset_y = coordinate for x in range(1, image.shape[0] - 1): for y in range(1, image.shape[1] - 1): base_pixel = image[x, y] offset_pixel = image[x + offset_x, y + offset_y] matrix[base_pixel, offset_pixel] += 1 matrix_sum = np.sum(matrix) return matrix / (1 if matrix_sum == 0 else matrix_sum) def haralick_descriptors(matrix: np.ndarray) -> list[float]: # Function np.indices could be used for bigger input types, # but np.ogrid works just fine i, j = np.ogrid[0 : matrix.shape[0], 0 : matrix.shape[1]] # np.indices() # Pre-calculate frequent multiplication and subtraction prod = np.multiply(i, j) sub = np.subtract(i, j) # Calculate numerical value of Maximum Probability maximum_prob = np.max(matrix) # Using the definition for each descriptor individually to calculate its matrix correlation = prod * matrix energy = np.power(matrix, 2) contrast = matrix * np.power(sub, 2) dissimilarity = matrix * np.abs(sub) inverse_difference = matrix / (1 + np.abs(sub)) homogeneity = matrix / (1 + np.power(sub, 2)) entropy = -(matrix[matrix > 0] * np.log(matrix[matrix > 0])) # Sum values for descriptors ranging from the first one to the last, # as all are their respective origin matrix and not the resulting value yet. return [ maximum_prob, correlation.sum(), energy.sum(), contrast.sum(), dissimilarity.sum(), inverse_difference.sum(), homogeneity.sum(), entropy.sum(), ] def get_descriptors( masks: tuple[np.ndarray, np.ndarray], coordinate: tuple[int, int] ) -> np.ndarray: descriptors = np.array( [haralick_descriptors(matrix_concurrency(mask, coordinate)) for mask in masks] ) # Concatenate each individual descriptor into # one single list containing sequence of descriptors return np.concatenate(descriptors, axis=None) def euclidean(point_1: np.ndarray, point_2: np.ndarray) -> float: return float(np.sqrt(np.sum(np.square(point_1 - point_2)))) def get_distances(descriptors: np.ndarray, base: int) -> list[tuple[int, float]]: distances = np.array( [euclidean(descriptor, descriptors[base]) for descriptor in descriptors] ) # Normalize distances between range [0, 1] normalized_distances: list[float] = normalize_array(distances, 1).tolist() enum_distances = list(enumerate(normalized_distances)) enum_distances.sort(key=lambda tup: tup[1], reverse=True) return enum_distances if __name__ == "__main__": # Index to compare haralick descriptors to index = int(input()) q_value_list = [int(value) for value in input().split()] q_value = (q_value_list[0], q_value_list[1]) # Format is the respective filter to apply, # can be either 1 for the opening filter or else for the closing parameters = {"format": int(input()), "threshold": int(input())} # Number of images to perform methods on b_number = int(input()) files, descriptors = [], [] for _ in range(b_number): file = input().rstrip() files.append(file) # Open given image and calculate morphological filter, # respective masks and correspondent Harralick Descriptors. image = imageio.imread(file).astype(np.float32) gray = grayscale(image) threshold = binarize(gray, parameters["threshold"]) morphological = ( opening_filter(threshold) if parameters["format"] == 1 else closing_filter(threshold) ) masks = binary_mask(gray, morphological) descriptors.append(get_descriptors(masks, q_value)) # Transform ordered distances array into a sequence of indexes # corresponding to original file position distances = get_distances(np.array(descriptors), index) indexed_distances = np.array(distances).astype(np.uint8)[:, 0] # Finally, print distances considering the Haralick descriptions from the base # file to all other images using the morphology method of choice. print(f"Query: {files[index]}") print("Ranking:") for idx, file_idx in enumerate(indexed_distances): print(f"({idx}) {files[file_idx]}", end="\n")
--- +++ @@ -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 implementation of Root Mean Squared Error + for two N dimensional numpy arrays. + + Examples: + >>> root_mean_square_error(np.array([1, 2, 3]), np.array([1, 2, 3])) + 0.0 + >>> root_mean_square_error(np.array([1, 2, 3]), np.array([2, 2, 2])) + 0.816496580927726 + >>> root_mean_square_error(np.array([1, 2, 3]), np.array([6, 4, 2])) + 3.1622776601683795 + """ 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: + """ + Normalizes image in Numpy 2D array format, between ranges 0-cap, + as to fit uint8 type. + + Args: + image: 2D numpy array representing image as matrix, with values in any range + cap: Maximum cap amount for normalization + data_type: numpy data type to set output variable to + Returns: + return 2D numpy array of type uint8, corresponding to limited range matrix + + Examples: + >>> normalize_image(np.array([[1, 2, 3], [4, 5, 10]]), + ... cap=1.0, data_type=np.float64) + array([[0. , 0.11111111, 0.22222222], + [0.33333333, 0.44444444, 1. ]]) + >>> normalize_image(np.array([[4, 4, 3], [1, 7, 2]])) + array([[127, 127, 85], + [ 0, 255, 42]], dtype=uint8) + """ normalized = (image - np.min(image)) / (np.max(image) - np.min(image)) * cap return normalized.astype(data_type) def normalize_array(array: np.ndarray, cap: float = 1) -> np.ndarray: + """Normalizes a 1D array, between ranges 0-cap. + + Args: + array: List containing values to be normalized between cap range. + cap: Maximum cap amount for normalization. + Returns: + return 1D numpy array, corresponding to limited range array + + Examples: + >>> normalize_array(np.array([2, 3, 5, 7])) + array([0. , 0.2, 0.6, 1. ]) + >>> normalize_array(np.array([[5], [7], [11], [13]])) + array([[0. ], + [0.25], + [0.75], + [1. ]]) + """ diff = np.max(array) - np.min(array) return (array - np.min(array)) / (1 if diff == 0 else diff) * cap def grayscale(image: np.ndarray) -> np.ndarray: + """ + Uses luminance weights to transform RGB channel to greyscale, by + taking the dot product between the channel and the weights. + + Example: + >>> grayscale(np.array([[[108, 201, 72], [255, 11, 127]], + ... [[56, 56, 56], [128, 255, 107]]])) + array([[158, 97], + [ 56, 200]], dtype=uint8) + """ return np.dot(image[:, :, 0:3], [0.299, 0.587, 0.114]).astype(np.uint8) def binarize(image: np.ndarray, threshold: float = 127.0) -> np.ndarray: + """ + Binarizes a grayscale image based on a given threshold value, + setting values to 1 or 0 accordingly. + + Examples: + >>> binarize(np.array([[128, 255], [101, 156]])) + array([[1, 1], + [0, 1]]) + >>> binarize(np.array([[0.07, 1], [0.51, 0.3]]), threshold=0.5) + array([[0, 1], + [1, 0]]) + """ return np.where(image > threshold, 1, 0) def transform( image: np.ndarray, kind: str, kernel: np.ndarray | None = None ) -> np.ndarray: + """ + Simple image transformation using one of two available filter functions: + Erosion and Dilation. + + Args: + image: binarized input image, onto which to apply transformation + kind: Can be either 'erosion', in which case the :func:np.max + function is called, or 'dilation', when :func:np.min is used instead. + kernel: n x n kernel with shape < :attr:image.shape, + to be used when applying convolution to original image + + Returns: + returns a numpy array with same shape as input image, + corresponding to applied binary transformation. + + Examples: + >>> img = np.array([[1, 0.5], [0.2, 0.7]]) + >>> img = binarize(img, threshold=0.5) + >>> transform(img, 'erosion') + array([[1, 1], + [1, 1]], dtype=uint8) + >>> transform(img, 'dilation') + array([[0, 0], + [0, 0]], dtype=uint8) + """ if kernel is None: kernel = np.ones((3, 3)) @@ -59,6 +158,17 @@ def opening_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray: + """ + Opening filter, defined as the sequence of + erosion and then a dilation filter on the same image. + + Examples: + >>> img = np.array([[1, 0.5], [0.2, 0.7]]) + >>> img = binarize(img, threshold=0.5) + >>> opening_filter(img) + array([[1, 1], + [1, 1]], dtype=uint8) + """ if kernel is None: np.ones((3, 3)) @@ -66,6 +176,17 @@ def closing_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray: + """ + Opening filter, defined as the sequence of + dilation and then erosion filter on the same image. + + Examples: + >>> img = np.array([[1, 0.5], [0.2, 0.7]]) + >>> img = binarize(img, threshold=0.5) + >>> closing_filter(img) + array([[0, 0], + [0, 0]], dtype=uint8) + """ if kernel is None: kernel = np.ones((3, 3)) return transform(transform(image, "erosion", kernel), "dilation", kernel) @@ -74,6 +195,23 @@ def binary_mask( image_gray: np.ndarray, image_map: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: + """ + Apply binary mask, or thresholding based + on bit mask value (mapping mask is binary). + + Returns the mapped true value mask and its complementary false value mask. + + Example: + >>> img = np.array([[[108, 201, 72], [255, 11, 127]], + ... [[56, 56, 56], [128, 255, 107]]]) + >>> gray = grayscale(img) + >>> binary = binarize(gray) + >>> morphological = opening_filter(binary) + >>> binary_mask(gray, morphological) + (array([[1, 1], + [1, 1]], dtype=uint8), array([[158, 97], + [ 56, 200]], dtype=uint8)) + """ true_mask, false_mask = image_gray.copy(), image_gray.copy() true_mask[image_map == 1] = 1 false_mask[image_map == 0] = 0 @@ -82,6 +220,25 @@ def matrix_concurrency(image: np.ndarray, coordinate: tuple[int, int]) -> np.ndarray: + """ + Calculate sample co-occurrence matrix based on input image + as well as selected coordinates on image. + + Implementation is made using basic iteration, + as function to be performed (np.max) is non-linear and therefore + not callable on the frequency domain. + + Example: + >>> img = np.array([[[108, 201, 72], [255, 11, 127]], + ... [[56, 56, 56], [128, 255, 107]]]) + >>> gray = grayscale(img) + >>> binary = binarize(gray) + >>> morphological = opening_filter(binary) + >>> mask_1 = binary_mask(gray, morphological)[0] + >>> matrix_concurrency(mask_1, (0, 1)) + array([[0., 0.], + [0., 0.]]) + """ matrix = np.zeros([np.max(image) + 1, np.max(image) + 1]) offset_x, offset_y = coordinate @@ -97,6 +254,28 @@ def haralick_descriptors(matrix: np.ndarray) -> list[float]: + """Calculates all 8 Haralick descriptors based on co-occurrence input matrix. + All descriptors are as follows: + Maximum probability, Inverse Difference, Homogeneity, Entropy, + Energy, Dissimilarity, Contrast and Correlation + + Args: + matrix: Co-occurrence matrix to use as base for calculating descriptors. + + Returns: + Reverse ordered list of resulting descriptors + + Example: + >>> img = np.array([[[108, 201, 72], [255, 11, 127]], + ... [[56, 56, 56], [128, 255, 107]]]) + >>> gray = grayscale(img) + >>> binary = binarize(gray) + >>> morphological = opening_filter(binary) + >>> mask_1 = binary_mask(gray, morphological)[0] + >>> concurrency = matrix_concurrency(mask_1, (0, 1)) + >>> [float(f) for f in haralick_descriptors(concurrency)] + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + """ # Function np.indices could be used for bigger input types, # but np.ogrid works just fine i, j = np.ogrid[0 : matrix.shape[0], 0 : matrix.shape[1]] # np.indices() @@ -134,6 +313,19 @@ def get_descriptors( masks: tuple[np.ndarray, np.ndarray], coordinate: tuple[int, int] ) -> np.ndarray: + """ + Calculate all Haralick descriptors for a sequence of + different co-occurrence matrices, given input masks and coordinates. + + Example: + >>> img = np.array([[[108, 201, 72], [255, 11, 127]], + ... [[56, 56, 56], [128, 255, 107]]]) + >>> gray = grayscale(img) + >>> binary = binarize(gray) + >>> morphological = opening_filter(binary) + >>> get_descriptors(binary_mask(gray, morphological), (0, 1)) + array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) + """ descriptors = np.array( [haralick_descriptors(matrix_concurrency(mask, coordinate)) for mask in masks] ) @@ -144,10 +336,48 @@ def euclidean(point_1: np.ndarray, point_2: np.ndarray) -> float: + """ + Simple method for calculating the euclidean distance between two points, + with type np.ndarray. + + Example: + >>> a = np.array([1, 0, -2]) + >>> b = np.array([2, -1, 1]) + >>> euclidean(a, b) + 3.3166247903554 + """ return float(np.sqrt(np.sum(np.square(point_1 - point_2)))) def get_distances(descriptors: np.ndarray, base: int) -> list[tuple[int, float]]: + """ + Calculate all Euclidean distances between a selected base descriptor + and all other Haralick descriptors + The resulting comparison is return in decreasing order, + showing which descriptor is the most similar to the selected base. + + Args: + descriptors: Haralick descriptors to compare with base index + base: Haralick descriptor index to use as base when calculating respective + euclidean distance to other descriptors. + + Returns: + Ordered distances between descriptors + + Example: + >>> index = 1 + >>> img = np.array([[[108, 201, 72], [255, 11, 127]], + ... [[56, 56, 56], [128, 255, 107]]]) + >>> gray = grayscale(img) + >>> binary = binarize(gray) + >>> morphological = opening_filter(binary) + >>> get_distances(get_descriptors( + ... binary_mask(gray, morphological), (0, 1)), + ... index) + [(0, 0.0), (1, 0.0), (2, 0.0), (3, 0.0), (4, 0.0), (5, 0.0), \ +(6, 0.0), (7, 0.0), (8, 0.0), (9, 0.0), (10, 0.0), (11, 0.0), (12, 0.0), \ +(13, 0.0), (14, 0.0), (15, 0.0)] + """ distances = np.array( [euclidean(descriptor, descriptors[base]) for descriptor in descriptors] ) @@ -201,4 +431,4 @@ print(f"Query: {files[index]}") print("Ranking:") for idx, file_idx in enumerate(indexed_distances): - print(f"({idx}) {files[file_idx]}", end="\n")+ print(f"({idx}) {files[file_idx]}", end="\n")
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 = -15 atto = -18 zepto = -21 yocto = -24 class BinaryUnit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: str | SIUnit, unknown_prefix: str | SIUnit, ) -> float: if isinstance(known_prefix, str): known_prefix = SIUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SIUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: str | BinaryUnit, unknown_prefix: str | BinaryUnit, ) -> float: if isinstance(known_prefix, str): known_prefix = BinaryUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = BinaryUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 + Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units + >>> convert_si_prefix(1, SIUnit.giga, SIUnit.mega) + 1000 + >>> convert_si_prefix(1, SIUnit.mega, SIUnit.giga) + 0.001 + >>> convert_si_prefix(1, SIUnit.kilo, SIUnit.kilo) + 1 + >>> convert_si_prefix(1, 'giga', 'mega') + 1000 + >>> convert_si_prefix(1, 'gIGa', 'mEGa') + 1000 + """ if isinstance(known_prefix, str): known_prefix = SIUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): @@ -58,6 +75,19 @@ known_prefix: str | BinaryUnit, unknown_prefix: str | BinaryUnit, ) -> float: + """ + Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix + >>> convert_binary_prefix(1, BinaryUnit.giga, BinaryUnit.mega) + 1024 + >>> convert_binary_prefix(1, BinaryUnit.mega, BinaryUnit.giga) + 0.0009765625 + >>> convert_binary_prefix(1, BinaryUnit.kilo, BinaryUnit.kilo) + 1 + >>> convert_binary_prefix(1, 'giga', 'mega') + 1024 + >>> convert_binary_prefix(1, 'gIGa', 'mEGa') + 1024 + """ if isinstance(known_prefix, str): known_prefix = BinaryUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): @@ -71,4 +101,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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": "312", "U": "313", "V": "321", "W": "322", "X": "323", "Y": "331", "Z": "332", "+": "333", } # fmt: off TEST_NUMBER_TO_CHARACTER = {val: key for key, val in TEST_CHARACTER_TO_NUMBER.items()} def __encrypt_part(message_part: str, character_to_number: dict[str, str]) -> str: one, two, three = "", "", "" for each in (character_to_number[character] for character in message_part): one += each[0] two += each[1] three += each[2] return one + two + three def __decrypt_part( message_part: str, character_to_number: dict[str, str] ) -> tuple[str, str, str]: this_part = "".join(character_to_number[character] for character in message_part) result = [] tmp = "" for digit in this_part: tmp += digit if len(tmp) == len(message_part): result.append(tmp) tmp = "" return result[0], result[1], result[2] def __prepare( message: str, alphabet: str ) -> tuple[str, str, dict[str, str], dict[str, str]]: # Validate message and alphabet, set to upper and remove spaces alphabet = alphabet.replace(" ", "").upper() message = message.replace(" ", "").upper() # Check length and characters if len(alphabet) != 27: raise KeyError("Length of alphabet has to be 27.") if any(char not in alphabet for char in message): raise ValueError("Each message character has to be included in alphabet!") # Generate dictionares character_to_number = dict(zip(alphabet, TEST_CHARACTER_TO_NUMBER.values())) number_to_character = { number: letter for letter, number in character_to_number.items() } return message, alphabet, character_to_number, number_to_character def encrypt_message( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character_to_number, number_to_character = __prepare( message, alphabet ) encrypted_numeric = "" for i in range(0, len(message) + 1, period): encrypted_numeric += __encrypt_part( message[i : i + period], character_to_number ) encrypted = "" for i in range(0, len(encrypted_numeric), 3): encrypted += number_to_character[encrypted_numeric[i : i + 3]] return encrypted def decrypt_message( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character_to_number, number_to_character = __prepare( message, alphabet ) decrypted_numeric = [] for i in range(0, len(message), period): a, b, c = __decrypt_part(message[i : i + period], character_to_number) for j in range(len(a)): decrypted_numeric.append(a[j] + b[j] + c[j]) return "".join(number_to_character[each] for each in decrypted_numeric) if __name__ == "__main__": import doctest doctest.testmod() msg = "DEFEND THE EAST WALL OF THE CASTLE." encrypted = encrypt_message(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") decrypted = decrypt_message(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")
--- +++ @@ -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": "232", "R": "233", "S": "311", "T": "312", "U": "313", - "V": "321", "W": "322", "X": "323", "Y": "331", "Z": "332", "+": "333", -} -# fmt: off - -TEST_NUMBER_TO_CHARACTER = {val: key for key, val in TEST_CHARACTER_TO_NUMBER.items()} - - -def __encrypt_part(message_part: str, character_to_number: dict[str, str]) -> str: - one, two, three = "", "", "" - for each in (character_to_number[character] for character in message_part): - one += each[0] - two += each[1] - three += each[2] - - return one + two + three - - -def __decrypt_part( - message_part: str, character_to_number: dict[str, str] -) -> tuple[str, str, str]: - this_part = "".join(character_to_number[character] for character in message_part) - result = [] - tmp = "" - for digit in this_part: - tmp += digit - if len(tmp) == len(message_part): - result.append(tmp) - tmp = "" - - return result[0], result[1], result[2] - - -def __prepare( - message: str, alphabet: str -) -> tuple[str, str, dict[str, str], dict[str, str]]: - # Validate message and alphabet, set to upper and remove spaces - alphabet = alphabet.replace(" ", "").upper() - message = message.replace(" ", "").upper() - - # Check length and characters - if len(alphabet) != 27: - raise KeyError("Length of alphabet has to be 27.") - if any(char not in alphabet for char in message): - raise ValueError("Each message character has to be included in alphabet!") - - # Generate dictionares - character_to_number = dict(zip(alphabet, TEST_CHARACTER_TO_NUMBER.values())) - number_to_character = { - number: letter for letter, number in character_to_number.items() - } - - return message, alphabet, character_to_number, number_to_character - - -def encrypt_message( - message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 -) -> str: - message, alphabet, character_to_number, number_to_character = __prepare( - message, alphabet - ) - - encrypted_numeric = "" - for i in range(0, len(message) + 1, period): - encrypted_numeric += __encrypt_part( - message[i : i + period], character_to_number - ) - - encrypted = "" - for i in range(0, len(encrypted_numeric), 3): - encrypted += number_to_character[encrypted_numeric[i : i + 3]] - return encrypted - - -def decrypt_message( - message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 -) -> str: - message, alphabet, character_to_number, number_to_character = __prepare( - message, alphabet - ) - - decrypted_numeric = [] - for i in range(0, len(message), period): - a, b, c = __decrypt_part(message[i : i + period], character_to_number) - - for j in range(len(a)): - decrypted_numeric.append(a[j] + b[j] + c[j]) - - return "".join(number_to_character[each] for each in decrypted_numeric) - - -if __name__ == "__main__": - import doctest - - doctest.testmod() - msg = "DEFEND THE EAST WALL OF THE CASTLE." - encrypted = encrypt_message(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") - decrypted = decrypt_message(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") - print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")+""" +The trifid cipher uses a table to fractionate each plaintext letter into a trigram, +mixes the constituents of the trigrams, and then applies the table in reverse to turn +these mixed trigrams into ciphertext letters. + +https://en.wikipedia.org/wiki/Trifid_cipher +""" + +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": "312", "U": "313", + "V": "321", "W": "322", "X": "323", "Y": "331", "Z": "332", "+": "333", +} +# fmt: off + +TEST_NUMBER_TO_CHARACTER = {val: key for key, val in TEST_CHARACTER_TO_NUMBER.items()} + + +def __encrypt_part(message_part: str, character_to_number: dict[str, str]) -> str: + """ + Arrange the triagram value of each letter of `message_part` vertically and join + them horizontally. + + >>> __encrypt_part('ASK', TEST_CHARACTER_TO_NUMBER) + '132111112' + """ + one, two, three = "", "", "" + for each in (character_to_number[character] for character in message_part): + one += each[0] + two += each[1] + three += each[2] + + return one + two + three + + +def __decrypt_part( + message_part: str, character_to_number: dict[str, str] +) -> tuple[str, str, str]: + """ + Convert each letter of the input string into their respective trigram values, join + them and split them into three equal groups of strings which are returned. + + >>> __decrypt_part('ABCDE', TEST_CHARACTER_TO_NUMBER) + ('11111', '21131', '21122') + """ + this_part = "".join(character_to_number[character] for character in message_part) + result = [] + tmp = "" + for digit in this_part: + tmp += digit + if len(tmp) == len(message_part): + result.append(tmp) + tmp = "" + + return result[0], result[1], result[2] + + +def __prepare( + message: str, alphabet: str +) -> tuple[str, str, dict[str, str], dict[str, str]]: + """ + A helper function that generates the triagrams and assigns each letter of the + alphabet to its corresponding triagram and stores this in a dictionary + (`character_to_number` and `number_to_character`) after confirming if the + alphabet's length is ``27``. + + >>> test = __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVwxYZ+') + >>> expected = ('IAMABOY','ABCDEFGHIJKLMNOPQRSTUVWXYZ+', + ... TEST_CHARACTER_TO_NUMBER, TEST_NUMBER_TO_CHARACTER) + >>> test == expected + True + + Testing with incomplete alphabet + + >>> __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVw') + Traceback (most recent call last): + ... + KeyError: 'Length of alphabet has to be 27.' + + Testing with extra long alphabets + + >>> __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVwxyzzwwtyyujjgfd') + Traceback (most recent call last): + ... + KeyError: 'Length of alphabet has to be 27.' + + Testing with punctuation not in the given alphabet + + >>> __prepare('am i a boy?','abCdeFghijkLmnopqrStuVwxYZ+') + Traceback (most recent call last): + ... + ValueError: Each message character has to be included in alphabet! + + Testing with numbers + + >>> __prepare(500,'abCdeFghijkLmnopqrStuVwxYZ+') + Traceback (most recent call last): + ... + AttributeError: 'int' object has no attribute 'replace' + """ + # Validate message and alphabet, set to upper and remove spaces + alphabet = alphabet.replace(" ", "").upper() + message = message.replace(" ", "").upper() + + # Check length and characters + if len(alphabet) != 27: + raise KeyError("Length of alphabet has to be 27.") + if any(char not in alphabet for char in message): + raise ValueError("Each message character has to be included in alphabet!") + + # Generate dictionares + character_to_number = dict(zip(alphabet, TEST_CHARACTER_TO_NUMBER.values())) + number_to_character = { + number: letter for letter, number in character_to_number.items() + } + + return message, alphabet, character_to_number, number_to_character + + +def encrypt_message( + message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 +) -> str: + """ + encrypt_message + =============== + + Encrypts a message using the trifid_cipher. Any punctuatuion chars that + would be used should be added to the alphabet. + + PARAMETERS + ---------- + + * `message`: The message you want to encrypt. + * `alphabet` (optional): The characters to be used for the cipher . + * `period` (optional): The number of characters you want in a group whilst + encrypting. + + >>> encrypt_message('I am a boy') + 'BCDGBQY' + + >>> encrypt_message(' ') + '' + + >>> encrypt_message(' aide toi le c iel ta id era ', + ... 'FELIXMARDSTBCGHJKNOPQUVWYZ+',5) + 'FMJFVOISSUFTFPUFEQQC' + + """ + message, alphabet, character_to_number, number_to_character = __prepare( + message, alphabet + ) + + encrypted_numeric = "" + for i in range(0, len(message) + 1, period): + encrypted_numeric += __encrypt_part( + message[i : i + period], character_to_number + ) + + encrypted = "" + for i in range(0, len(encrypted_numeric), 3): + encrypted += number_to_character[encrypted_numeric[i : i + 3]] + return encrypted + + +def decrypt_message( + message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 +) -> str: + """ + decrypt_message + =============== + + Decrypts a trifid_cipher encrypted message. + + PARAMETERS + ---------- + + * `message`: The message you want to decrypt. + * `alphabet` (optional): The characters used for the cipher. + * `period` (optional): The number of characters used in grouping when it + was encrypted. + + >>> decrypt_message('BCDGBQY') + 'IAMABOY' + + Decrypting with your own alphabet and period + + >>> decrypt_message('FMJFVOISSUFTFPUFEQQC','FELIXMARDSTBCGHJKNOPQUVWYZ+',5) + 'AIDETOILECIELTAIDERA' + """ + message, alphabet, character_to_number, number_to_character = __prepare( + message, alphabet + ) + + decrypted_numeric = [] + for i in range(0, len(message), period): + a, b, c = __decrypt_part(message[i : i + period], character_to_number) + + for j in range(len(a)): + decrypted_numeric.append(a[j] + b[j] + c[j]) + + return "".join(number_to_character[each] for each in decrypted_numeric) + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + msg = "DEFEND THE EAST WALL OF THE CASTLE." + encrypted = encrypt_message(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") + decrypted = decrypt_message(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") + print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")
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 positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] else: actual_value = str(mod) new_value += actual_value div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
--- +++ @@ -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' + >>> decimal_to_any(5, 4) + '11' + >>> decimal_to_any(20, 3) + '202' + >>> decimal_to_any(58, 16) + '3A' + >>> decimal_to_any(243, 17) + 'E5' + >>> decimal_to_any(34923, 36) + 'QY3' + >>> decimal_to_any(10, 11) + 'A' + >>> decimal_to_any(16, 16) + '10' + >>> decimal_to_any(36, 36) + '10' + >>> # negatives will error + >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: parameter must be positive int + >>> # floats will error + >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: int() can't convert non-string with explicit base + >>> # a float base will error + >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'float' object cannot be interpreted as an integer + >>> # a str base will error + >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'str' object cannot be interpreted as an integer + >>> # a base less than 2 will error + >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: base must be >= 2 + >>> # a base greater than 36 will error + >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: base must be <= 36 + """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: @@ -50,4 +102,4 @@ base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), - )+ )
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 ValueError("invalid k value") def __str__(self) -> str: return str(self.k) def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
--- +++ @@ -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 @@ return str(self.k) def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: + """ + Returns the image with corners identified + img_path : path of the image + output : list of the corner positions, image + """ img = cv2.imread(img_path, 0) h, w = img.shape @@ -59,4 +68,4 @@ if __name__ == "__main__": edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") - cv2.imwrite("detect.png", color_img)+ cv2.imwrite("detect.png", color_img)
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 main() -> None: img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR) print("Processing...") new_images, new_annos, paths = update_image_and_anno(img_paths, annos, FLIP_TYPE) for index, image in enumerate(new_images): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Success {index + 1}/{len(new_images)} with {file_name}") annos_list = [] for anno in new_annos[index]: obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") boxes.append( [ int(obj[0]), float(obj[1]), float(obj[2]), float(obj[3]), float(obj[4]), ] ) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( img_list: list, anno_list: list, flip_type: int = 1 ) -> tuple[list, list, list]: new_annos_lists = [] path_list = [] new_imgs_list = [] for idx in range(len(img_list)): new_annos = [] path = img_list[idx] path_list.append(path) img_annos = anno_list[idx] img = cv2.imread(path) if flip_type == 1: new_img = cv2.flip(img, flip_type) for bbox in img_annos: x_center_new = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]]) elif flip_type == 0: new_img = cv2.flip(img, flip_type) for bbox in img_annos: y_center_new = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]]) new_annos_lists.append(new_annos) new_imgs_list.append(new_img) return new_imgs_list, new_annos_lists, path_list def random_chars(number_char: int = 32) -> str: assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
--- +++ @@ -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, new_annos, paths = update_image_and_anno(img_paths, annos, FLIP_TYPE) @@ -38,6 +43,11 @@ def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: + """ + - label_dir <type: str>: Path to label include annotation of images + - img_dir <type: str>: Path to folder contain images + Return <type: list>: List of images path and labels + """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): @@ -68,6 +78,15 @@ def update_image_and_anno( img_list: list, anno_list: list, flip_type: int = 1 ) -> tuple[list, list, list]: + """ + - img_list <type: list>: list of all images + - anno_list <type: list>: list of all annotations of specific image + - flip_type <type: int>: 0 is vertical, 1 is horizontal + Return: + - new_imgs_list <type: narray>: image after resize + - new_annos_lists <type: list>: list of new annotation after scale + - path_list <type: list>: list the name of image file + """ new_annos_lists = [] path_list = [] new_imgs_list = [] @@ -93,6 +112,12 @@ def random_chars(number_char: int = 32) -> str: + """ + Automatic generate random 32 characters. + Get random string code: '7b7ad245cdff75241935e4dd860f3bad' + >>> len(random_chars(32)) + 32 + """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) @@ -100,4 +125,4 @@ if __name__ == "__main__": main() - print("DONE ✅")+ print("DONE ✅")
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 ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix maxpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix avgpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image image = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
--- +++ @@ -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 of pixels shifts over the input matrix + Returns: + numpy array of maxpooled matrix + Sample Input Output: + >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) + array([[ 6., 8.], + [14., 16.]]) + >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) + array([[241., 180.], + [241., 157.]]) + """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") @@ -46,6 +62,22 @@ # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: + """ + This function is used to perform avgpooling on the input array of 2D matrix(image) + Args: + arr: numpy array + size: size of pooling matrix + stride: the number of pixels shifts over the input matrix + Returns: + numpy array of avgpooled matrix + Sample Input Output: + >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) + array([[ 3., 5.], + [11., 13.]]) + >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) + array([[161., 102.], + [114., 69.]]) + """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") @@ -100,4 +132,4 @@ # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix - Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()+ Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
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))) counter += 1 num = math.floor(num / 8) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"0o{int(octal)}" def main() -> None: print("\n2 in octal is:") print(decimal_to_octal(2)) # = 2 print("\n8 in octal is:") print(decimal_to_octal(8)) # = 10 print("\n65 in octal is:") print(decimal_to_octal(65)) # = 101 print("\n216 in octal is:") print(decimal_to_octal(216)) # = 330 print("\n512 in octal is:") print(decimal_to_octal(512)) # = 1000 print("\n") if __name__ == "__main__": main()
--- +++ @@ -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 + """ octal = 0 counter = 0 while num > 0: @@ -18,6 +25,7 @@ def main() -> None: + """Print octal equivalents of decimal numbers.""" print("\n2 in octal is:") print(decimal_to_octal(2)) # = 2 print("\n8 in octal is:") @@ -32,4 +40,4 @@ if __name__ == "__main__": - main()+ main()
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: assert isinstance(decimal, (int, float)) assert decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 beginning + with 0x + >>> decimal_to_hexadecimal(5) + '0x5' + >>> decimal_to_hexadecimal(15) + '0xf' + >>> decimal_to_hexadecimal(37) + '0x25' + >>> decimal_to_hexadecimal(255) + '0xff' + >>> decimal_to_hexadecimal(4096) + '0x1000' + >>> decimal_to_hexadecimal(999098) + '0xf3eba' + >>> # negatives work too + >>> decimal_to_hexadecimal(-256) + '-0x100' + >>> # floats are acceptable if equivalent to an int + >>> decimal_to_hexadecimal(17.0) + '0x11' + >>> # other floats will error + >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + AssertionError + >>> # strings will error as well + >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + AssertionError + >>> # results are the same when compared to Python's default hex function + >>> decimal_to_hexadecimal(-256) == hex(-256) + True + """ assert isinstance(decimal, (int, float)) assert decimal == int(decimal) decimal = int(decimal) @@ -41,4 +77,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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"), (6, "million"), (3, "thousand"), (2, "hundred"), ) INDIAN = ( (14, "crore crore"), (12, "lakh crore"), (7, "crore"), (5, "lakh"), (3, "thousand"), (2, "hundred"), ) @classmethod def max_value(cls, system: str) -> int: match system_enum := cls[system.upper()]: case cls.SHORT: max_exp = system_enum.value[0][0] + 3 case cls.LONG: max_exp = system_enum.value[0][0] + 6 case cls.INDIAN: max_exp = 19 case _: raise ValueError("Invalid numbering system") return 10**max_exp - 1 class NumberWords(Enum): ONES = { # noqa: RUF012 0: "", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", } TEENS = { # noqa: RUF012 0: "ten", 1: "eleven", 2: "twelve", 3: "thirteen", 4: "fourteen", 5: "fifteen", 6: "sixteen", 7: "seventeen", 8: "eighteen", 9: "nineteen", } TENS = { # noqa: RUF012 2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety", } def convert_small_number(num: int) -> str: if num < 0: raise ValueError("This function only accepts non-negative integers") if num >= 100: raise ValueError("This function only converts numbers less than 100") tens, ones = divmod(num, 10) if tens == 0: return NumberWords.ONES.value[ones] or "zero" if tens == 1: return NumberWords.TEENS.value[ones] return ( NumberWords.TENS.value[tens] + ("-" if NumberWords.ONES.value[ones] else "") + NumberWords.ONES.value[ones] ) def convert_number( num: int, system: Literal["short", "long", "indian"] = "short" ) -> str: word_groups = [] if num < 0: word_groups.append("negative") num *= -1 if num > NumberingSystem.max_value(system): raise ValueError("Input number is too large") for power, unit in NumberingSystem[system.upper()].value: digit_group, num = divmod(num, 10**power) if digit_group > 0: word_group = ( convert_number(digit_group, system) if digit_group >= 100 else convert_small_number(digit_group) ) word_groups.append(f"{word_group} {unit}") if num > 0 or not word_groups: # word_groups is only empty if input num was 0 word_groups.append(convert_small_number(num)) return " ".join(word_groups) if __name__ == "__main__": import doctest doctest.testmod() print(f"{convert_number(123456789) = }")
--- +++ @@ -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 + True + >>> NumberingSystem.max_value("indian") == 10**19 - 1 + True + """ match system_enum := cls[system.upper()]: case cls.SHORT: max_exp = system_enum.value[0][0] + 3 @@ -83,6 +93,31 @@ def convert_small_number(num: int) -> str: + """ + Converts small, non-negative integers with irregular constructions in English (i.e., + numbers under 100) into words. + + >>> convert_small_number(0) + 'zero' + >>> convert_small_number(5) + 'five' + >>> convert_small_number(10) + 'ten' + >>> convert_small_number(15) + 'fifteen' + >>> convert_small_number(20) + 'twenty' + >>> convert_small_number(25) + 'twenty-five' + >>> convert_small_number(-1) + Traceback (most recent call last): + ... + ValueError: This function only accepts non-negative integers + >>> convert_small_number(123) + Traceback (most recent call last): + ... + ValueError: This function only converts numbers less than 100 + """ if num < 0: raise ValueError("This function only accepts non-negative integers") if num >= 100: @@ -102,6 +137,43 @@ def convert_number( num: int, system: Literal["short", "long", "indian"] = "short" ) -> str: + """ + Converts an integer to English words. + + :param num: The integer to be converted + :param system: The numbering system (short, long, or Indian) + + >>> convert_number(0) + 'zero' + >>> convert_number(1) + 'one' + >>> convert_number(100) + 'one hundred' + >>> convert_number(-100) + 'negative one hundred' + >>> convert_number(123_456_789_012_345) # doctest: +NORMALIZE_WHITESPACE + 'one hundred twenty-three trillion four hundred fifty-six billion + seven hundred eighty-nine million twelve thousand three hundred forty-five' + >>> convert_number(123_456_789_012_345, "long") # doctest: +NORMALIZE_WHITESPACE + 'one hundred twenty-three thousand four hundred fifty-six milliard + seven hundred eighty-nine million twelve thousand three hundred forty-five' + >>> convert_number(12_34_56_78_90_12_345, "indian") # doctest: +NORMALIZE_WHITESPACE + 'one crore crore twenty-three lakh crore + forty-five thousand six hundred seventy-eight crore + ninety lakh twelve thousand three hundred forty-five' + >>> convert_number(10**18) + Traceback (most recent call last): + ... + ValueError: Input number is too large + >>> convert_number(10**21, "long") + Traceback (most recent call last): + ... + ValueError: Input number is too large + >>> convert_number(10**19, "indian") + Traceback (most recent call last): + ... + ValueError: Input number is too large + """ word_groups = [] if num < 0: @@ -130,4 +202,4 @@ doctest.testmod() - print(f"{convert_number(123456789) = }")+ print(f"{convert_number(123456789) = }")
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: return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 + Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit + + >>> celsius_to_fahrenheit(273.354, 3) + 524.037 + >>> celsius_to_fahrenheit(273.354, 0) + 524.0 + >>> celsius_to_fahrenheit(-40.0) + -40.0 + >>> celsius_to_fahrenheit(-20.0) + -4.0 + >>> celsius_to_fahrenheit(0) + 32.0 + >>> celsius_to_fahrenheit(20) + 68.0 + >>> celsius_to_fahrenheit("40") + 104.0 + >>> celsius_to_fahrenheit("celsius") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'celsius' + """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: + """ + Convert a given value from Celsius to Kelvin and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Celsius + Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin + + >>> celsius_to_kelvin(273.354, 3) + 546.504 + >>> celsius_to_kelvin(273.354, 0) + 547.0 + >>> celsius_to_kelvin(0) + 273.15 + >>> celsius_to_kelvin(20.0) + 293.15 + >>> celsius_to_kelvin("40") + 313.15 + >>> celsius_to_kelvin("celsius") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'celsius' + """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: + """ + Convert a given value from Celsius to Rankine and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Celsius + Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale + + >>> celsius_to_rankine(273.354, 3) + 983.707 + >>> celsius_to_rankine(273.354, 0) + 984.0 + >>> celsius_to_rankine(0) + 491.67 + >>> celsius_to_rankine(20.0) + 527.67 + >>> celsius_to_rankine("40") + 563.67 + >>> celsius_to_rankine("celsius") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'celsius' + """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: + """ + Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit + Wikipedia reference: https://en.wikipedia.org/wiki/Celsius + + >>> fahrenheit_to_celsius(273.354, 3) + 134.086 + >>> fahrenheit_to_celsius(273.354, 0) + 134.0 + >>> fahrenheit_to_celsius(0) + -17.78 + >>> fahrenheit_to_celsius(20.0) + -6.67 + >>> fahrenheit_to_celsius(40.0) + 4.44 + >>> fahrenheit_to_celsius(60) + 15.56 + >>> fahrenheit_to_celsius(80) + 26.67 + >>> fahrenheit_to_celsius("100") + 37.78 + >>> fahrenheit_to_celsius("fahrenheit") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'fahrenheit' + """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: + """ + Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit + Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin + + >>> fahrenheit_to_kelvin(273.354, 3) + 407.236 + >>> fahrenheit_to_kelvin(273.354, 0) + 407.0 + >>> fahrenheit_to_kelvin(0) + 255.37 + >>> fahrenheit_to_kelvin(20.0) + 266.48 + >>> fahrenheit_to_kelvin(40.0) + 277.59 + >>> fahrenheit_to_kelvin(60) + 288.71 + >>> fahrenheit_to_kelvin(80) + 299.82 + >>> fahrenheit_to_kelvin("100") + 310.93 + >>> fahrenheit_to_kelvin("fahrenheit") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'fahrenheit' + """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: + """ + Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit + Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale + + >>> fahrenheit_to_rankine(273.354, 3) + 733.024 + >>> fahrenheit_to_rankine(273.354, 0) + 733.0 + >>> fahrenheit_to_rankine(0) + 459.67 + >>> fahrenheit_to_rankine(20.0) + 479.67 + >>> fahrenheit_to_rankine(40.0) + 499.67 + >>> fahrenheit_to_rankine(60) + 519.67 + >>> fahrenheit_to_rankine(80) + 539.67 + >>> fahrenheit_to_rankine("100") + 559.67 + >>> fahrenheit_to_rankine("fahrenheit") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'fahrenheit' + """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: + """ + Convert a given value from Kelvin to Celsius and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin + Wikipedia reference: https://en.wikipedia.org/wiki/Celsius + + >>> kelvin_to_celsius(273.354, 3) + 0.204 + >>> kelvin_to_celsius(273.354, 0) + 0.0 + >>> kelvin_to_celsius(273.15) + 0.0 + >>> kelvin_to_celsius(300) + 26.85 + >>> kelvin_to_celsius("315.5") + 42.35 + >>> kelvin_to_celsius("kelvin") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'kelvin' + """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: + """ + Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin + Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit + + >>> kelvin_to_fahrenheit(273.354, 3) + 32.367 + >>> kelvin_to_fahrenheit(273.354, 0) + 32.0 + >>> kelvin_to_fahrenheit(273.15) + 32.0 + >>> kelvin_to_fahrenheit(300) + 80.33 + >>> kelvin_to_fahrenheit("315.5") + 108.23 + >>> kelvin_to_fahrenheit("kelvin") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'kelvin' + """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: + """ + Convert a given value from Kelvin to Rankine and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin + Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale + + >>> kelvin_to_rankine(273.354, 3) + 492.037 + >>> kelvin_to_rankine(273.354, 0) + 492.0 + >>> kelvin_to_rankine(0) + 0.0 + >>> kelvin_to_rankine(20.0) + 36.0 + >>> kelvin_to_rankine("40") + 72.0 + >>> kelvin_to_rankine("kelvin") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'kelvin' + """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: + """ + Convert a given value from Rankine to Celsius and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale + Wikipedia reference: https://en.wikipedia.org/wiki/Celsius + + >>> rankine_to_celsius(273.354, 3) + -121.287 + >>> rankine_to_celsius(273.354, 0) + -121.0 + >>> rankine_to_celsius(273.15) + -121.4 + >>> rankine_to_celsius(300) + -106.48 + >>> rankine_to_celsius("315.5") + -97.87 + >>> rankine_to_celsius("rankine") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'rankine' + """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: + """ + Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale + Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit + + >>> rankine_to_fahrenheit(273.15) + -186.52 + >>> rankine_to_fahrenheit(300) + -159.67 + >>> rankine_to_fahrenheit("315.5") + -144.17 + >>> rankine_to_fahrenheit("rankine") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'rankine' + """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: + """ + Convert a given value from Rankine to Kelvin and round it to 2 decimal places. + Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale + Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin + + >>> rankine_to_kelvin(0) + 0.0 + >>> rankine_to_kelvin(20.0) + 11.11 + >>> rankine_to_kelvin("40") + 22.22 + >>> rankine_to_kelvin("rankine") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'rankine' + """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: + """ + Convert a given value from reaumur to Kelvin and round it to 2 decimal places. + Reference:- http://www.csgnetwork.com/temp2conv.html + + >>> reaumur_to_kelvin(0) + 273.15 + >>> reaumur_to_kelvin(20.0) + 298.15 + >>> reaumur_to_kelvin(40) + 323.15 + >>> reaumur_to_kelvin("reaumur") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'reaumur' + """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: + """ + Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. + Reference:- http://www.csgnetwork.com/temp2conv.html + + >>> reaumur_to_fahrenheit(0) + 32.0 + >>> reaumur_to_fahrenheit(20.0) + 77.0 + >>> reaumur_to_fahrenheit(40) + 122.0 + >>> reaumur_to_fahrenheit("reaumur") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'reaumur' + """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: + """ + Convert a given value from reaumur to celsius and round it to 2 decimal places. + Reference:- http://www.csgnetwork.com/temp2conv.html + + >>> reaumur_to_celsius(0) + 0.0 + >>> reaumur_to_celsius(20.0) + 25.0 + >>> reaumur_to_celsius(40) + 50.0 + >>> reaumur_to_celsius("reaumur") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'reaumur' + """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: + """ + Convert a given value from reaumur to rankine and round it to 2 decimal places. + Reference:- http://www.csgnetwork.com/temp2conv.html + + >>> reaumur_to_rankine(0) + 491.67 + >>> reaumur_to_rankine(20.0) + 536.67 + >>> reaumur_to_rankine(40) + 581.67 + >>> reaumur_to_rankine("reaumur") + Traceback (most recent call last): + ... + ValueError: could not convert string to float: 'reaumur' + """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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-unit": 6.022136652e26, } WEIGHT_TYPE_CHART: dict[str, float] = { "kilogram": 1, "gram": pow(10, -3), "milligram": pow(10, -6), "metric-ton": pow(10, 3), "long-ton": 1016.04608, "short-ton": 907.184, "pound": 0.453592, "stone": 6.35029, "ounce": 0.0283495, "carrat": 0.0002, "atomic-mass-unit": 1.660540199e-27, } def weight_conversion(from_type: str, to_type: str, value: float) -> float: if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: msg = ( f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}" ) raise ValueError(msg) return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 conversion of weight units. +-> Parameters : + -> from_type : From which type you want to convert + -> to_type : To which type you want to convert + -> value : the value which you want to convert + +REFERENCES : + +-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilogram +-> Wikipedia reference: https://en.wikipedia.org/wiki/Gram +-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre +-> Wikipedia reference: https://en.wikipedia.org/wiki/Tonne +-> Wikipedia reference: https://en.wikipedia.org/wiki/Long_ton +-> Wikipedia reference: https://en.wikipedia.org/wiki/Short_ton +-> Wikipedia reference: https://en.wikipedia.org/wiki/Pound +-> Wikipedia reference: https://en.wikipedia.org/wiki/Ounce +-> Wikipedia reference: https://en.wikipedia.org/wiki/Fineness#Karat +-> Wikipedia reference: https://en.wikipedia.org/wiki/Dalton_(unit) +-> Wikipedia reference: https://en.wikipedia.org/wiki/Stone_(unit) +""" KILOGRAM_CHART: dict[str, float] = { "kilogram": 1, @@ -29,6 +60,250 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float: + """ + Conversion of weight unit with the help of KILOGRAM_CHART + + "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-unit" : 6.022136652E+26 + + >>> weight_conversion("kilogram","kilogram",4) + 4 + >>> weight_conversion("kilogram","gram",1) + 1000 + >>> weight_conversion("kilogram","milligram",4) + 4000000 + >>> weight_conversion("kilogram","metric-ton",4) + 0.004 + >>> weight_conversion("kilogram","long-ton",3) + 0.0029526219 + >>> weight_conversion("kilogram","short-ton",1) + 0.0011023122 + >>> weight_conversion("kilogram","pound",4) + 8.8184976808 + >>> weight_conversion("kilogram","stone",5) + 0.7873658640000001 + >>> weight_conversion("kilogram","ounce",4) + 141.095962892 + >>> weight_conversion("kilogram","carrat",3) + 15000 + >>> weight_conversion("kilogram","atomic-mass-unit",1) + 6.022136652e+26 + >>> weight_conversion("gram","kilogram",1) + 0.001 + >>> weight_conversion("gram","gram",3) + 3.0 + >>> weight_conversion("gram","milligram",2) + 2000.0 + >>> weight_conversion("gram","metric-ton",4) + 4e-06 + >>> weight_conversion("gram","long-ton",3) + 2.9526219e-06 + >>> weight_conversion("gram","short-ton",3) + 3.3069366000000003e-06 + >>> weight_conversion("gram","pound",3) + 0.0066138732606 + >>> weight_conversion("gram","stone",4) + 0.0006298926912000001 + >>> weight_conversion("gram","ounce",1) + 0.035273990723 + >>> weight_conversion("gram","carrat",2) + 10.0 + >>> weight_conversion("gram","atomic-mass-unit",1) + 6.022136652e+23 + >>> weight_conversion("milligram","kilogram",1) + 1e-06 + >>> weight_conversion("milligram","gram",2) + 0.002 + >>> weight_conversion("milligram","milligram",3) + 3.0 + >>> weight_conversion("milligram","metric-ton",3) + 3e-09 + >>> weight_conversion("milligram","long-ton",3) + 2.9526219e-09 + >>> weight_conversion("milligram","short-ton",1) + 1.1023122e-09 + >>> weight_conversion("milligram","pound",3) + 6.6138732605999995e-06 + >>> weight_conversion("milligram","ounce",2) + 7.054798144599999e-05 + >>> weight_conversion("milligram","carrat",1) + 0.005 + >>> weight_conversion("milligram","atomic-mass-unit",1) + 6.022136652e+20 + >>> weight_conversion("metric-ton","kilogram",2) + 2000 + >>> weight_conversion("metric-ton","gram",2) + 2000000 + >>> weight_conversion("metric-ton","milligram",3) + 3000000000 + >>> weight_conversion("metric-ton","metric-ton",2) + 2.0 + >>> weight_conversion("metric-ton","long-ton",3) + 2.9526219 + >>> weight_conversion("metric-ton","short-ton",2) + 2.2046244 + >>> weight_conversion("metric-ton","pound",3) + 6613.8732606 + >>> weight_conversion("metric-ton","ounce",4) + 141095.96289199998 + >>> weight_conversion("metric-ton","carrat",4) + 20000000 + >>> weight_conversion("metric-ton","atomic-mass-unit",1) + 6.022136652e+29 + >>> weight_conversion("long-ton","kilogram",4) + 4064.18432 + >>> weight_conversion("long-ton","gram",4) + 4064184.32 + >>> weight_conversion("long-ton","milligram",3) + 3048138240.0 + >>> weight_conversion("long-ton","metric-ton",4) + 4.06418432 + >>> weight_conversion("long-ton","long-ton",3) + 2.999999907217152 + >>> weight_conversion("long-ton","short-ton",1) + 1.119999989746176 + >>> weight_conversion("long-ton","pound",3) + 6720.000000049448 + >>> weight_conversion("long-ton","ounce",1) + 35840.000000060514 + >>> weight_conversion("long-ton","carrat",4) + 20320921.599999998 + >>> weight_conversion("long-ton","atomic-mass-unit",4) + 2.4475073353955697e+30 + >>> weight_conversion("short-ton","kilogram",3) + 2721.5519999999997 + >>> weight_conversion("short-ton","gram",3) + 2721552.0 + >>> weight_conversion("short-ton","milligram",1) + 907184000.0 + >>> weight_conversion("short-ton","metric-ton",4) + 3.628736 + >>> weight_conversion("short-ton","long-ton",3) + 2.6785713457296 + >>> weight_conversion("short-ton","short-ton",3) + 2.9999999725344 + >>> weight_conversion("short-ton","pound",2) + 4000.0000000294335 + >>> weight_conversion("short-ton","ounce",4) + 128000.00000021611 + >>> weight_conversion("short-ton","carrat",4) + 18143680.0 + >>> weight_conversion("short-ton","atomic-mass-unit",1) + 5.463186016507968e+29 + >>> weight_conversion("pound","kilogram",4) + 1.814368 + >>> weight_conversion("pound","gram",2) + 907.184 + >>> weight_conversion("pound","milligram",3) + 1360776.0 + >>> weight_conversion("pound","metric-ton",3) + 0.001360776 + >>> weight_conversion("pound","long-ton",2) + 0.0008928571152432 + >>> weight_conversion("pound","short-ton",1) + 0.0004999999954224 + >>> weight_conversion("pound","pound",3) + 3.0000000000220752 + >>> weight_conversion("pound","ounce",1) + 16.000000000027015 + >>> weight_conversion("pound","carrat",1) + 2267.96 + >>> weight_conversion("pound","atomic-mass-unit",4) + 1.0926372033015936e+27 + >>> weight_conversion("stone","kilogram",5) + 31.751450000000002 + >>> weight_conversion("stone","gram",2) + 12700.58 + >>> weight_conversion("stone","milligram",3) + 19050870.0 + >>> weight_conversion("stone","metric-ton",3) + 0.01905087 + >>> weight_conversion("stone","long-ton",3) + 0.018750005325351003 + >>> weight_conversion("stone","short-ton",3) + 0.021000006421614002 + >>> weight_conversion("stone","pound",2) + 28.00000881870372 + >>> weight_conversion("stone","ounce",1) + 224.00007054835967 + >>> weight_conversion("stone","carrat",2) + 63502.9 + >>> weight_conversion("ounce","kilogram",3) + 0.0850485 + >>> weight_conversion("ounce","gram",3) + 85.0485 + >>> weight_conversion("ounce","milligram",4) + 113398.0 + >>> weight_conversion("ounce","metric-ton",4) + 0.000113398 + >>> weight_conversion("ounce","long-ton",4) + 0.0001116071394054 + >>> weight_conversion("ounce","short-ton",4) + 0.0001249999988556 + >>> weight_conversion("ounce","pound",1) + 0.0625000000004599 + >>> weight_conversion("ounce","ounce",2) + 2.000000000003377 + >>> weight_conversion("ounce","carrat",1) + 141.7475 + >>> weight_conversion("ounce","atomic-mass-unit",1) + 1.70724563015874e+25 + >>> weight_conversion("carrat","kilogram",1) + 0.0002 + >>> weight_conversion("carrat","gram",4) + 0.8 + >>> weight_conversion("carrat","milligram",2) + 400.0 + >>> weight_conversion("carrat","metric-ton",2) + 4.0000000000000003e-07 + >>> weight_conversion("carrat","long-ton",3) + 5.9052438e-07 + >>> weight_conversion("carrat","short-ton",4) + 8.818497600000002e-07 + >>> weight_conversion("carrat","pound",1) + 0.00044092488404000004 + >>> weight_conversion("carrat","ounce",2) + 0.0141095962892 + >>> weight_conversion("carrat","carrat",4) + 4.0 + >>> weight_conversion("carrat","atomic-mass-unit",4) + 4.8177093216e+23 + >>> weight_conversion("atomic-mass-unit","kilogram",4) + 6.642160796e-27 + >>> weight_conversion("atomic-mass-unit","gram",2) + 3.321080398e-24 + >>> weight_conversion("atomic-mass-unit","milligram",2) + 3.3210803980000002e-21 + >>> weight_conversion("atomic-mass-unit","metric-ton",3) + 4.9816205970000004e-30 + >>> weight_conversion("atomic-mass-unit","long-ton",3) + 4.9029473573977584e-30 + >>> weight_conversion("atomic-mass-unit","short-ton",1) + 1.830433719948128e-30 + >>> weight_conversion("atomic-mass-unit","pound",3) + 1.0982602420317504e-26 + >>> weight_conversion("atomic-mass-unit","ounce",2) + 1.1714775914938915e-25 + >>> weight_conversion("atomic-mass-unit","carrat",2) + 1.660540199e-23 + >>> weight_conversion("atomic-mass-unit","atomic-mass-unit",2) + 1.999999998903455 + >>> weight_conversion("slug", "kilogram", 1) + Traceback (most recent call last): + ... + ValueError: Invalid 'from_type' or 'to_type' value: 'slug', 'kilogram' + Supported values are: kilogram, gram, milligram, metric-ton, long-ton, short-ton, \ +pound, stone, ounce, carrat, atomic-mass-unit + """ if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: msg = ( f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" @@ -41,4 +316,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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": "ft", "yard": "yd", "mile": "mi", } METRIC_CONVERSION = { "mm": FromTo(0.001, 1000), "cm": FromTo(0.01, 100), "m": FromTo(1, 1), "km": FromTo(1000, 0.001), "in": FromTo(0.0254, 39.3701), "ft": FromTo(0.3048, 3.28084), "yd": FromTo(0.9144, 1.09361), "mi": FromTo(1609.34, 0.000621371), } def length_conversion(value: float, from_type: str, to_type: str) -> float: new_from = from_type.lower().rstrip("s") new_from = TYPE_CONVERSION.get(new_from, new_from) new_to = to_type.lower().rstrip("s") new_to = TYPE_CONVERSION.get(new_to, new_to) if new_from not in METRIC_CONVERSION: msg = ( f"Invalid 'from_type' value: {from_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) if new_to not in METRIC_CONVERSION: msg = ( f"Invalid 'to_type' value: {to_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) return ( value * METRIC_CONVERSION[new_from].from_factor * METRIC_CONVERSION[new_to].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 stripped off - "feet": "ft", - "foot": "ft", - "yard": "yd", - "mile": "mi", -} - -METRIC_CONVERSION = { - "mm": FromTo(0.001, 1000), - "cm": FromTo(0.01, 100), - "m": FromTo(1, 1), - "km": FromTo(1000, 0.001), - "in": FromTo(0.0254, 39.3701), - "ft": FromTo(0.3048, 3.28084), - "yd": FromTo(0.9144, 1.09361), - "mi": FromTo(1609.34, 0.000621371), -} - - -def length_conversion(value: float, from_type: str, to_type: str) -> float: - new_from = from_type.lower().rstrip("s") - new_from = TYPE_CONVERSION.get(new_from, new_from) - new_to = to_type.lower().rstrip("s") - new_to = TYPE_CONVERSION.get(new_to, new_to) - if new_from not in METRIC_CONVERSION: - msg = ( - f"Invalid 'from_type' value: {from_type!r}.\n" - f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" - ) - raise ValueError(msg) - if new_to not in METRIC_CONVERSION: - msg = ( - f"Invalid 'to_type' value: {to_type!r}.\n" - f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" - ) - raise ValueError(msg) - return ( - value - * METRIC_CONVERSION[new_from].from_factor - * METRIC_CONVERSION[new_to].to_factor - ) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +Conversion of length units. +Available Units:- Metre,Kilometre,Feet,Inch,Centimeter,Yard,Foot,Mile,Millimeter + +USAGE : +-> Import this file into their respective project. +-> Use the function length_conversion() for conversion of length units. +-> Parameters : + -> value : The number of from units you want to convert + -> from_type : From which type you want to convert + -> to_type : To which type you want to convert + +REFERENCES : +-> Wikipedia reference: https://en.wikipedia.org/wiki/Meter +-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilometer +-> Wikipedia reference: https://en.wikipedia.org/wiki/Feet +-> Wikipedia reference: https://en.wikipedia.org/wiki/Inch +-> Wikipedia reference: https://en.wikipedia.org/wiki/Centimeter +-> Wikipedia reference: https://en.wikipedia.org/wiki/Yard +-> Wikipedia reference: https://en.wikipedia.org/wiki/Foot +-> Wikipedia reference: https://en.wikipedia.org/wiki/Mile +-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter +""" + +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": "ft", + "yard": "yd", + "mile": "mi", +} + +METRIC_CONVERSION = { + "mm": FromTo(0.001, 1000), + "cm": FromTo(0.01, 100), + "m": FromTo(1, 1), + "km": FromTo(1000, 0.001), + "in": FromTo(0.0254, 39.3701), + "ft": FromTo(0.3048, 3.28084), + "yd": FromTo(0.9144, 1.09361), + "mi": FromTo(1609.34, 0.000621371), +} + + +def length_conversion(value: float, from_type: str, to_type: str) -> float: + """ + Conversion between length units. + + >>> length_conversion(4, "METER", "FEET") + 13.12336 + >>> length_conversion(4, "M", "FT") + 13.12336 + >>> length_conversion(1, "meter", "kilometer") + 0.001 + >>> length_conversion(1, "kilometer", "inch") + 39370.1 + >>> length_conversion(3, "kilometer", "mile") + 1.8641130000000001 + >>> length_conversion(2, "feet", "meter") + 0.6096 + >>> length_conversion(4, "feet", "yard") + 1.333329312 + >>> length_conversion(1, "inch", "meter") + 0.0254 + >>> length_conversion(2, "inch", "mile") + 3.15656468e-05 + >>> length_conversion(2, "centimeter", "millimeter") + 20.0 + >>> length_conversion(2, "centimeter", "yard") + 0.0218722 + >>> length_conversion(4, "yard", "meter") + 3.6576 + >>> length_conversion(4, "yard", "kilometer") + 0.0036576 + >>> length_conversion(3, "foot", "meter") + 0.9144000000000001 + >>> length_conversion(3, "foot", "inch") + 36.00001944 + >>> length_conversion(4, "mile", "kilometer") + 6.43736 + >>> length_conversion(2, "miles", "InChEs") + 126719.753468 + >>> length_conversion(3, "millimeter", "centimeter") + 0.3 + >>> length_conversion(3, "mm", "in") + 0.1181103 + >>> length_conversion(4, "wrongUnit", "inch") + Traceback (most recent call last): + ... + ValueError: Invalid 'from_type' value: 'wrongUnit'. + Conversion abbreviations are: mm, cm, m, km, in, ft, yd, mi + """ + new_from = from_type.lower().rstrip("s") + new_from = TYPE_CONVERSION.get(new_from, new_from) + new_to = to_type.lower().rstrip("s") + new_to = TYPE_CONVERSION.get(new_to, new_to) + if new_from not in METRIC_CONVERSION: + msg = ( + f"Invalid 'from_type' value: {from_type!r}.\n" + f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" + ) + raise ValueError(msg) + if new_to not in METRIC_CONVERSION: + msg = ( + f"Invalid 'to_type' value: {to_type!r}.\n" + f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" + ) + raise ValueError(msg) + return ( + value + * METRIC_CONVERSION[new_from].from_factor + * METRIC_CONVERSION[new_to].to_factor + ) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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: print("File not accessible") sys.exit() def decompress_data(data_bits: str) -> str: lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id lexicon[curr_string] = last_match_id + "0" if math.log2(index).is_integer(): new_lex = {} for curr_key in list(lexicon): new_lex["0" + curr_key] = lexicon.pop(curr_key) lexicon = new_lex lexicon[bin(index)[2:]] = last_match_id + "1" index += 1 curr_string = "" return result def write_file_binary(file_path: str, to_write: str) -> None: byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def remove_prefix(data_bits: str) -> str: counter = 0 for letter in data_bits: if letter == "1": break counter += 1 data_bits = data_bits[counter:] data_bits = data_bits[counter + 1 :] return data_bits def compress(source_path: str, destination_path: str) -> None: data_bits = read_file_binary(source_path) data_bits = remove_prefix(data_bits) decompressed = decompress_data(data_bits) write_file_binary(destination_path, decompressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
--- +++ @@ -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 long string + """ result = "" try: with open(file_path, "rb") as binary_file: @@ -18,6 +25,10 @@ def decompress_data(data_bits: str) -> str: + """ + Decompresses given data_bits using Lempel-Ziv-Welch compression algorithm + and returns the result as a string + """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) @@ -44,6 +55,10 @@ def write_file_binary(file_path: str, to_write: str) -> None: + """ + Writes given to_write string (should only consist of 0's and 1's) as bytes in the + file + """ byte_length = 8 try: with open(file_path, "wb") as opened_file: @@ -67,6 +82,10 @@ def remove_prefix(data_bits: str) -> str: + """ + Removes size prefix, that compressed file should have + Returns the result + """ counter = 0 for letter in data_bits: if letter == "1": @@ -79,6 +98,9 @@ def compress(source_path: str, destination_path: str) -> None: + """ + Reads source file, decompresses it and writes the result in destination file + """ data_bits = read_file_binary(source_path) data_bits = remove_prefix(data_bits) decompressed = decompress_data(data_bits) @@ -86,4 +108,4 @@ if __name__ == "__main__": - compress(sys.argv[1], sys.argv[2])+ compress(sys.argv[1], sys.argv[2])
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: if not 0 <= octet <= 255: raise ValueError(f"Invalid IPv4 octet {octet}") # noqa: EM102 decimal_ipv4 = (decimal_ipv4 << 8) + int(octet) return decimal_ipv4 def alt_ipv4_to_decimal(ipv4_address: str) -> int: return int("0x" + "".join(f"{int(i):02x}" for i in ipv4_address.split(".")), 16) def decimal_to_ipv4(decimal_ipv4: int) -> str: if not (0 <= decimal_ipv4 <= 4294967295): raise ValueError("Invalid decimal IPv4 address") ip_parts = [] for _ in range(4): ip_parts.append(str(decimal_ipv4 & 255)) decimal_ipv4 >>= 8 return ".".join(reversed(ip_parts)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. + + >>> ipv4_to_decimal("192.168.0.1") + 3232235521 + >>> ipv4_to_decimal("10.0.0.255") + 167772415 + >>> ipv4_to_decimal("10.0.255") + Traceback (most recent call last): + ... + ValueError: Invalid IPv4 address format + >>> ipv4_to_decimal("10.0.0.256") + Traceback (most recent call last): + ... + ValueError: Invalid IPv4 octet 256 + """ octets = [int(octet) for octet in ipv4_address.split(".")] if len(octets) != 4: @@ -17,10 +39,34 @@ def alt_ipv4_to_decimal(ipv4_address: str) -> int: + """ + >>> alt_ipv4_to_decimal("192.168.0.1") + 3232235521 + >>> alt_ipv4_to_decimal("10.0.0.255") + 167772415 + """ return int("0x" + "".join(f"{int(i):02x}" for i in ipv4_address.split(".")), 16) def decimal_to_ipv4(decimal_ipv4: int) -> str: + """ + Convert a decimal representation of an IP address to its IPv4 format. + + Args: + decimal_ipv4: An integer representing the decimal IP address. + + Returns: + The IPv4 representation of the decimal IP address. + + >>> decimal_to_ipv4(3232235521) + '192.168.0.1' + >>> decimal_to_ipv4(167772415) + '10.0.0.255' + >>> decimal_to_ipv4(-1) + Traceback (most recent call last): + ... + ValueError: Invalid decimal IPv4 address + """ if not (0 <= decimal_ipv4 <= 4294967295): raise ValueError("Invalid decimal IPv4 address") @@ -36,4 +82,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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, "electronvolt": 1.602_176_634e-19, "britishthermalunit_it": 1_055.055_85, "footpound": 1.355_818, } def energy_conversion(from_type: str, to_type: str, value: float) -> float: if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: msg = ( f"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Valid values are: {', '.join(ENERGY_CONVERSION)}" ) raise ValueError(msg) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 project. +-> Use the function energy_conversion() for conversion of energy units. +-> Parameters : + -> from_type : From which type you want to convert + -> to_type : To which type you want to convert + -> value : the value which you want to convert + +REFERENCES : +-> Wikipedia reference: https://en.wikipedia.org/wiki/Units_of_energy +-> Wikipedia reference: https://en.wikipedia.org/wiki/Joule +-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilowatt-hour +-> Wikipedia reference: https://en.wikipedia.org/wiki/Newton-metre +-> Wikipedia reference: https://en.wikipedia.org/wiki/Calorie +-> Wikipedia reference: https://en.wikipedia.org/wiki/Electronvolt +-> Wikipedia reference: https://en.wikipedia.org/wiki/British_thermal_unit +-> Wikipedia reference: https://en.wikipedia.org/wiki/Foot-pound_(energy) +-> Unit converter reference: https://www.unitconverters.net/energy-converter.html +""" ENERGY_CONVERSION: dict[str, float] = { "joule": 1.0, @@ -17,6 +43,62 @@ def energy_conversion(from_type: str, to_type: str, value: float) -> float: + """ + Conversion of energy units. + >>> energy_conversion("joule", "joule", 1) + 1.0 + >>> energy_conversion("joule", "kilojoule", 1) + 0.001 + >>> energy_conversion("joule", "megajoule", 1) + 1e-06 + >>> energy_conversion("joule", "gigajoule", 1) + 1e-09 + >>> energy_conversion("joule", "wattsecond", 1) + 1.0 + >>> energy_conversion("joule", "watthour", 1) + 0.0002777777777777778 + >>> energy_conversion("joule", "kilowatthour", 1) + 2.7777777777777776e-07 + >>> energy_conversion("joule", "newtonmeter", 1) + 1.0 + >>> energy_conversion("joule", "calorie_nutr", 1) + 0.00023884589662749592 + >>> energy_conversion("joule", "kilocalorie_nutr", 1) + 2.388458966274959e-07 + >>> energy_conversion("joule", "electronvolt", 1) + 6.241509074460763e+18 + >>> energy_conversion("joule", "britishthermalunit_it", 1) + 0.0009478171226670134 + >>> energy_conversion("joule", "footpound", 1) + 0.7375621211696556 + >>> energy_conversion("joule", "megajoule", 1000) + 0.001 + >>> energy_conversion("calorie_nutr", "kilocalorie_nutr", 1000) + 1.0 + >>> energy_conversion("kilowatthour", "joule", 10) + 36000000.0 + >>> energy_conversion("britishthermalunit_it", "footpound", 1) + 778.1692306784539 + >>> energy_conversion("watthour", "joule", "a") # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for /: 'str' and 'float' + >>> energy_conversion("wrongunit", "joule", 1) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: Incorrect 'from_type' or 'to_type' value: 'wrongunit', 'joule' + Valid values are: joule, ... footpound + >>> energy_conversion("joule", "wrongunit", 1) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: Incorrect 'from_type' or 'to_type' value: 'joule', 'wrongunit' + Valid values are: joule, ... footpound + >>> energy_conversion("123", "abc", 1) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: Incorrect 'from_type' or 'to_type' value: '123', 'abc' + Valid values are: joule, ... footpound + """ if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: msg = ( f"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" @@ -29,4 +111,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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", "DEF", "GHI") for cs in ("123", "456", "789")] ) units = {s: [u for u in unitlist if s in u] for s in squares} peers = {s: {x for u in units[s] for x in u} - {s} for s in squares} def test(): assert len(squares) == 81 assert len(unitlist) == 27 assert all(len(units[s]) == 3 for s in squares) assert all(len(peers[s]) == 20 for s in squares) assert units["C2"] == [ ["A2", "B2", "C2", "D2", "E2", "F2", "G2", "H2", "I2"], ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"], ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"], ] # fmt: off assert peers["C2"] == { "A2", "B2", "D2", "E2", "F2", "G2", "H2", "I2", "C1", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "A1", "A3", "B1", "B3" } # fmt: on print("All tests pass.") def parse_grid(grid): ## To start, every square can be any digit; then assign values from the grid. values = dict.fromkeys(squares, digits) for s, d in grid_values(grid).items(): if d in digits and not assign(values, s, d): return False ## (Fail if we can't assign d to square s.) return values def grid_values(grid): chars = [c for c in grid if c in digits or c in "0."] assert len(chars) == 81 return dict(zip(squares, chars)) def assign(values, s, d): other_values = values[s].replace(d, "") if all(eliminate(values, s, d2) for d2 in other_values): return values else: return False def eliminate(values, s, d): if d not in values[s]: return values ## Already eliminated values[s] = values[s].replace(d, "") ## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers. if len(values[s]) == 0: return False ## Contradiction: removed last value elif len(values[s]) == 1: d2 = values[s] if not all(eliminate(values, s2, d2) for s2 in peers[s]): return False ## (2) If a unit u is reduced to only one place for a value d, then put it there. for u in units[s]: dplaces = [s for s in u if d in values[s]] if len(dplaces) == 0: return False ## Contradiction: no place for this value # d can only be in one place in unit; assign it there elif len(dplaces) == 1 and not assign(values, dplaces[0], d): return False return values def display(values): width = 1 + max(len(values[s]) for s in squares) line = "+".join(["-" * (width * 3)] * 3) for r in rows: print( "".join( values[r + c].center(width) + ("|" if c in "36" else "") for c in cols ) ) if r in "CF": print(line) print() def solve(grid): return search(parse_grid(grid)) def some(seq): for e in seq: if e: return e return False def search(values): if values is False: return False ## Failed earlier if all(len(values[s]) == 1 for s in squares): return values ## Solved! ## Chose the unfilled square s with the fewest possibilities _n, s = min((len(values[s]), s) for s in squares if len(values[s]) > 1) return some(search(assign(values.copy(), s, d)) for d in values[s]) def solve_all(grids, name="", showif=0.0): def time_solve(grid): start = time.monotonic() values = solve(grid) t = time.monotonic() - start ## Display puzzles that take long enough if showif is not None and t > showif: display(grid_values(grid)) if values: display(values) print(f"({t:.5f} seconds)\n") return (t, solved(values)) times, results = zip(*[time_solve(grid) for grid in grids]) if (n := len(grids)) > 1: print( "Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)." # noqa: UP031 % (sum(results), n, name, sum(times) / n, n / sum(times), max(times)) ) def solved(values): def unitsolved(unit): return {values[s] for s in unit} == set(digits) return values is not False and all(unitsolved(unit) for unit in unitlist) def from_file(filename, sep="\n"): with open(filename) as file: return file.read().strip().split(sep) def random_puzzle(assignments=17): values = dict.fromkeys(squares, digits) for s in shuffled(squares): if not assign(values, s, random.choice(values[s])): break ds = [values[s] for s in squares if len(values[s]) == 1] if len(ds) >= assignments and len(set(ds)) >= 8: return "".join(values[s] if len(values[s]) == 1 else "." for s in squares) return random_puzzle(assignments) ## Give up and make a new puzzle def shuffled(seq): seq = list(seq) random.shuffle(seq) return seq grid1 = ( "003020600900305001001806400008102900700000008006708200002609500800203009005010300" ) grid2 = ( "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......" ) hard1 = ( ".....6....59.....82....8....45........3........6..3.54...325..6.................." ) if __name__ == "__main__": test() # solve_all(from_file("easy50.txt", '========'), "easy", None) # solve_all(from_file("top95.txt"), "hard", None) # solve_all(from_file("hardest.txt"), "hardest", None) solve_all([random_puzzle() for _ in range(99)], "random", 100.0) for puzzle in (grid1, grid2): # , hard1): # Takes 22 sec to solve on my M1 Mac. display(parse_grid(puzzle)) start = time.monotonic() solve(puzzle) t = time.monotonic() - start print(f"Solved: {t:.5f} sec")
--- +++ @@ -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): + """ + Cross product of elements in A and elements in B. + + >>> cross('AB', '12') + ['A1', 'A2', 'B1', 'B2'] + >>> cross('ABC', '123') + ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'] + >>> cross('ABC', '1234') + ['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2', 'C3', 'C4'] + >>> cross('', '12') + [] + >>> cross('A', '') + [] + >>> cross('', '') + [] + """ return [a + b for a in items_a for b in items_b] @@ -21,6 +42,7 @@ def test(): + """A set of unit tests.""" assert len(squares) == 81 assert len(unitlist) == 27 assert all(len(units[s]) == 3 for s in squares) @@ -40,6 +62,10 @@ def parse_grid(grid): + """ + Convert grid to a dict of possible values, {square: digits}, or + return False if a contradiction is detected. + """ ## To start, every square can be any digit; then assign values from the grid. values = dict.fromkeys(squares, digits) for s, d in grid_values(grid).items(): @@ -49,12 +75,19 @@ def grid_values(grid): + """ + Convert grid into a dict of {square: char} with '0' or '.' for empties. + """ chars = [c for c in grid if c in digits or c in "0."] assert len(chars) == 81 return dict(zip(squares, chars)) def assign(values, s, d): + """ + Eliminate all the other values (except d) from values[s] and propagate. + Return values, except return False if a contradiction is detected. + """ other_values = values[s].replace(d, "") if all(eliminate(values, s, d2) for d2 in other_values): return values @@ -63,6 +96,10 @@ def eliminate(values, s, d): + """ + Eliminate d from values[s]; propagate when values or places <= 2. + Return values, except return False if a contradiction is detected. + """ if d not in values[s]: return values ## Already eliminated values[s] = values[s].replace(d, "") @@ -85,6 +122,9 @@ def display(values): + """ + Display these values as a 2-D grid. + """ width = 1 + max(len(values[s]) for s in squares) line = "+".join(["-" * (width * 3)] * 3) for r in rows: @@ -99,10 +139,14 @@ def solve(grid): + """ + Solve the grid. + """ return search(parse_grid(grid)) def some(seq): + """Return some element of seq that is true.""" for e in seq: if e: return e @@ -110,6 +154,9 @@ def search(values): + """ + Using depth-first search and propagation, try all possible values. + """ if values is False: return False ## Failed earlier if all(len(values[s]) == 1 for s in squares): @@ -120,6 +167,11 @@ def solve_all(grids, name="", showif=0.0): + """ + Attempt to solve a sequence of grids. Report results. + When showif is a number of seconds, display puzzles that take longer. + When showif is None, don't display any puzzles. + """ def time_solve(grid): start = time.monotonic() @@ -142,6 +194,9 @@ def solved(values): + """ + A puzzle is solved if each unit is a permutation of the digits 1 to 9. + """ def unitsolved(unit): return {values[s] for s in unit} == set(digits) @@ -150,11 +205,17 @@ def from_file(filename, sep="\n"): + "Parse a file into a list of strings, separated by sep." with open(filename) as file: return file.read().strip().split(sep) def random_puzzle(assignments=17): + """ + Make a random puzzle with N or more assignments. Restart on contradictions. + Note the resulting puzzle is not guaranteed to be solvable, but empirically + about 99.8% of them are solvable. Some have multiple solutions. + """ values = dict.fromkeys(squares, digits) for s in shuffled(squares): if not assign(values, s, random.choice(values[s])): @@ -166,6 +227,9 @@ def shuffled(seq): + """ + Return a randomly shuffled copy of the input sequence. + """ seq = list(seq) random.shuffle(seq) return seq @@ -192,4 +256,4 @@ start = time.monotonic() solve(puzzle) t = time.monotonic() - start - print(f"Solved: {t:.5f} sec")+ print(f"Solved: {t:.5f} sec")
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 __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: response: list[Letter | TreeNode] = list(letters) while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda x: x.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: if isinstance(root, Letter): root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
--- +++ @@ -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,10 @@ def build_tree(letters: list[Letter]) -> Letter | TreeNode: + """ + Run through the list of Letters and build the min heap + for the Huffman Tree. + """ response: list[Letter | TreeNode] = list(letters) while len(response) > 1: left = response.pop(0) @@ -44,6 +52,10 @@ def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: + """ + Recursively traverse the Huffman Tree to set each + Letter's bitstring dictionary, and return the list of Letters + """ if isinstance(root, Letter): root.bitstring[root.letter] = bitstring return [root] @@ -55,6 +67,11 @@ def huffman(file_path: str) -> None: + """ + Parse the file, build the tree, then run through the file + again, using the letters dictionary to find and print out the + bitstring for each letter. + """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { @@ -72,4 +89,4 @@ if __name__ == "__main__": # pass the file path to the huffman function - huffman(sys.argv[1])+ huffman(sys.argv[1])
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_search(self, node: Node | None, path_sum: int) -> None: if node is None: return if path_sum == self.target: self.paths += 1 if node.left: self.depth_first_search(node.left, path_sum + node.left.value) if node.right: self.depth_first_search(node.right, path_sum + node.right.value) def path_sum(self, node: Node | None, target: int | None = None) -> int: if node is None: return 0 if target is not None: self.target = target self.depth_first_search(node, node.value) self.path_sum(node.left) self.path_sum(node.right) return self.paths if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 has value variable and pointers to Nodes to its left and right. + """ def __init__(self, value: int) -> None: self.value = value @@ -11,6 +22,55 @@ class BinaryTreePathSum: + r""" + The below tree looks like this + 10 + / \ + 5 -3 + / \ \ + 3 2 11 + / \ \ + 3 -2 1 + + + >>> tree = Node(10) + >>> tree.left = Node(5) + >>> tree.right = Node(-3) + >>> tree.left.left = Node(3) + >>> tree.left.right = Node(2) + >>> tree.right.right = Node(11) + >>> tree.left.left.left = Node(3) + >>> tree.left.left.right = Node(-2) + >>> tree.left.right.right = Node(1) + + >>> BinaryTreePathSum().path_sum(tree, 8) + 3 + >>> BinaryTreePathSum().path_sum(tree, 7) + 2 + >>> tree.right.right = Node(10) + >>> BinaryTreePathSum().path_sum(tree, 8) + 2 + >>> BinaryTreePathSum().path_sum(None, 0) + 0 + >>> BinaryTreePathSum().path_sum(tree, 0) + 0 + + The second tree looks like this + 0 + / \ + 5 5 + + >>> tree2 = Node(0) + >>> tree2.left = Node(5) + >>> tree2.right = Node(5) + + >>> BinaryTreePathSum().path_sum(tree2, 5) + 4 + >>> BinaryTreePathSum().path_sum(tree2, -1) + 0 + >>> BinaryTreePathSum().path_sum(tree2, 0) + 1 + """ target: int @@ -45,4 +105,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: if unit_to not in speed_chart or unit_from not in speed_chart_inverse: msg = ( f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" f"Valid values are: {', '.join(speed_chart_inverse)}" ) raise ValueError(msg) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 @@ def convert_speed(speed: float, unit_from: str, unit_to: str) -> float: + """ + Convert speed from one unit to another using the speed_chart above. + + "km/h": 1.0, + "m/s": 3.6, + "mph": 1.609344, + "knot": 1.852, + + >>> convert_speed(100, "km/h", "m/s") + 27.778 + >>> convert_speed(100, "km/h", "mph") + 62.137 + >>> convert_speed(100, "km/h", "knot") + 53.996 + >>> convert_speed(100, "m/s", "km/h") + 360.0 + >>> convert_speed(100, "m/s", "mph") + 223.694 + >>> convert_speed(100, "m/s", "knot") + 194.384 + >>> convert_speed(100, "mph", "km/h") + 160.934 + >>> convert_speed(100, "mph", "m/s") + 44.704 + >>> convert_speed(100, "mph", "knot") + 86.898 + >>> convert_speed(100, "knot", "km/h") + 185.2 + >>> convert_speed(100, "knot", "m/s") + 51.444 + >>> convert_speed(100, "knot", "mph") + 115.078 + """ if unit_to not in speed_chart or unit_from not in speed_chart_inverse: msg = ( f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" @@ -27,4 +68,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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.101325), "psi": FromTo(0.068046, 14.6959), "inHg": FromTo(0.0334211, 29.9213), "torr": FromTo(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_factor * PRESSURE_CONVERSION[to_type].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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), - "megapascal": FromTo(9.86923, 0.101325), - "psi": FromTo(0.068046, 14.6959), - "inHg": FromTo(0.0334211, 29.9213), - "torr": FromTo(0.00131579, 760), -} - - -def pressure_conversion(value: float, from_type: str, to_type: str) -> float: - if from_type not in PRESSURE_CONVERSION: - raise ValueError( - f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" - + ", ".join(PRESSURE_CONVERSION) - ) - if to_type not in PRESSURE_CONVERSION: - raise ValueError( - f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" - + ", ".join(PRESSURE_CONVERSION) - ) - return ( - value - * PRESSURE_CONVERSION[from_type].from_factor - * PRESSURE_CONVERSION[to_type].to_factor - ) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +Conversion of pressure units. +Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), +inHg(in mercury column),torr,atm +USAGE : +-> Import this file into their respective project. +-> Use the function pressure_conversion() for conversion of pressure units. +-> Parameters : + -> value : The number of from units you want to convert + -> from_type : From which type you want to convert + -> to_type : To which type you want to convert +REFERENCES : +-> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit) +-> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch +-> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury +-> Wikipedia reference: https://en.wikipedia.org/wiki/Torr +-> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) +-> https://msestudent.com/what-are-the-units-of-pressure/ +-> https://www.unitconverters.net/pressure-converter.html +""" + +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.101325), + "psi": FromTo(0.068046, 14.6959), + "inHg": FromTo(0.0334211, 29.9213), + "torr": FromTo(0.00131579, 760), +} + + +def pressure_conversion(value: float, from_type: str, to_type: str) -> float: + """ + Conversion between pressure units. + >>> pressure_conversion(4, "atm", "pascal") + 405300 + >>> pressure_conversion(1, "pascal", "psi") + 0.00014401981999999998 + >>> pressure_conversion(1, "bar", "atm") + 0.986923 + >>> pressure_conversion(3, "kilopascal", "bar") + 0.029999991892499998 + >>> pressure_conversion(2, "megapascal", "psi") + 290.074434314 + >>> pressure_conversion(4, "psi", "torr") + 206.85984 + >>> pressure_conversion(1, "inHg", "atm") + 0.0334211 + >>> pressure_conversion(1, "torr", "psi") + 0.019336718261000002 + >>> pressure_conversion(4, "wrongUnit", "atm") + Traceback (most recent call last): + ... + ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: + atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr + """ + if from_type not in PRESSURE_CONVERSION: + raise ValueError( + f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + + ", ".join(PRESSURE_CONVERSION) + ) + if to_type not in PRESSURE_CONVERSION: + raise ValueError( + f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + + ", ".join(PRESSURE_CONVERSION) + ) + return ( + value + * PRESSURE_CONVERSION[from_type].from_factor + * PRESSURE_CONVERSION[to_type].to_factor + ) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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.data if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def is_full(self) -> bool: if not self or (not self.left and not self.right): return True if self.left and self.right: return self.left.is_full() and self.right.is_full() return False @dataclass class BinaryTree: root: Node def __iter__(self) -> Iterator[int]: return iter(self.root) def __len__(self) -> int: return len(self.root) @classmethod def small_tree(cls) -> BinaryTree: binary_tree = BinaryTree(Node(2)) binary_tree.root.left = Node(1) binary_tree.root.right = Node(3) return binary_tree @classmethod def medium_tree(cls) -> BinaryTree: binary_tree = BinaryTree(Node(4)) binary_tree.root.left = two = Node(2) two.left = Node(1) two.right = Node(3) binary_tree.root.right = five = Node(5) five.right = six = Node(6) six.right = Node(7) return binary_tree def depth(self) -> int: return self._depth(self.root) def _depth(self, node: Node | None) -> int: if not node: return 0 return 1 + max(self._depth(node.left), self._depth(node.right)) def is_full(self) -> bool: return self.root.is_full() if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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_tree = BinaryTree(Node(2)) binary_tree.root.left = Node(1) binary_tree.root.right = Node(3) @@ -47,6 +55,14 @@ @classmethod def medium_tree(cls) -> BinaryTree: + """ + Return a medium binary tree with 3 nodes. + >>> binary_tree = BinaryTree.medium_tree() + >>> len(binary_tree) + 7 + >>> list(binary_tree) + [1, 2, 3, 4, 5, 6, 7] + """ binary_tree = BinaryTree(Node(4)) binary_tree.root.left = two = Node(2) two.left = Node(1) @@ -57,6 +73,16 @@ return binary_tree def depth(self) -> int: + """ + Returns the depth of the tree + + >>> BinaryTree(Node(1)).depth() + 1 + >>> BinaryTree.small_tree().depth() + 2 + >>> BinaryTree.medium_tree().depth() + 4 + """ return self._depth(self.root) def _depth(self, node: Node | None) -> int: @@ -65,10 +91,20 @@ return 1 + max(self._depth(node.left), self._depth(node.right)) def is_full(self) -> bool: + """ + Returns True if the tree is full + + >>> BinaryTree(Node(1)).is_full() + True + >>> BinaryTree.small_tree().is_full() + True + >>> BinaryTree.medium_tree().is_full() + False + """ return self.root.is_full() if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 passed to the function") binary_digit = "" value = int(digit) for _ in range(3): binary_digit = str(value % 2) + binary_digit value //= 2 binary_number += binary_digit return binary_number if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: str) -> str: + """ + Convert an Octal number to Binary. + + >>> octal_to_binary("17") + '001111' + >>> octal_to_binary("7") + '111' + >>> octal_to_binary("Av") + Traceback (most recent call last): + ... + ValueError: Non-octal value was passed to the function + >>> octal_to_binary("@#") + Traceback (most recent call last): + ... + ValueError: Non-octal value was passed to the function + >>> octal_to_binary("") + Traceback (most recent call last): + ... + ValueError: Empty string was passed to the function + """ if not octal_number: raise ValueError("Empty string was passed to the function") @@ -23,4 +51,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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_size: int = 13, lookahead_buffer_size: int = 6) -> None: self.window_size = window_size self.lookahead_buffer_size = lookahead_buffer_size self.search_buffer_size = self.window_size - self.lookahead_buffer_size def compress(self, text: str) -> list[Token]: output = [] search_buffer = "" # while there are still characters in text to compress while text: # find the next encoding phrase # - triplet with offset, length, indicator (the next encoding character) token = self._find_encoding_token(text, search_buffer) # update the search buffer: # - add new characters from text into it # - check if size exceed the max search buffer size, if so, drop the # oldest elements search_buffer += text[: token.length + 1] if len(search_buffer) > self.search_buffer_size: search_buffer = search_buffer[-self.search_buffer_size :] # update the text text = text[token.length + 1 :] # append the token to output output.append(token) return output def decompress(self, tokens: list[Token]) -> str: output = "" for token in tokens: for _ in range(token.length): output += output[-token.offset] output += token.indicator return output def _find_encoding_token(self, text: str, search_buffer: str) -> Token: if not text: raise ValueError("We need some text to work with.") # Initialise result parameters to default values length, offset = 0, 0 if not search_buffer: return Token(offset, length, text[length]) for i, character in enumerate(search_buffer): found_offset = len(search_buffer) - i if character == text[0]: found_length = self._match_length_from_index(text, search_buffer, 0, i) # if the found length is bigger than the current or if it's equal, # which means it's offset is smaller: update offset and length if found_length >= length: offset, length = found_offset, found_length return Token(offset, length, text[length]) def _match_length_from_index( self, text: str, window: str, text_index: int, window_index: int ) -> int: if not text or text[text_index] != window[window_index]: return 0 return 1 + self._match_length_from_index( text, window + text[text_index], text_index + 1, window_index + 1 ) if __name__ == "__main__": from doctest import testmod testmod() # Initialize compressor class lz77_compressor = LZ77Compressor(window_size=13, lookahead_buffer_size=6) # Example TEXT = "cabracadabrarrarrad" compressed_text = lz77_compressor.compress(TEXT) print(lz77_compressor.compress("ababcbababaa")) decompressed_text = lz77_compressor.decompress(compressed_text) assert decompressed_text == TEXT, "The LZ77 algorithm returned the invalid result."
--- +++ @@ -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 sliding window we have: + - search buffer + - look ahead buffer +len(sliding_window) = len(search_buffer) + len(look_ahead_buffer) + +LZ77 manages a dictionary that uses triples composed of: + - Offset into search buffer, it's the distance between the start of a phrase and + the beginning of a file. + - Length of the match, it's the number of characters that make up a phrase. + - The indicator is represented by a character that is going to be encoded next. + +As a file is parsed, the dictionary is dynamically updated to reflect the compressed +data contents and size. + +Examples: +"cabracadabrarrarrad" <-> [(0, 0, 'c'), (0, 0, 'a'), (0, 0, 'b'), (0, 0, 'r'), + (3, 1, 'c'), (2, 1, 'd'), (7, 4, 'r'), (3, 5, 'd')] +"ababcbababaa" <-> [(0, 0, 'a'), (0, 0, 'b'), (2, 2, 'c'), (4, 3, 'a'), (2, 2, 'a')] +"aacaacabcabaaac" <-> [(0, 0, 'a'), (1, 1, 'c'), (3, 4, 'b'), (3, 3, 'a'), (1, 2, 'c')] + +Sources: +en.wikipedia.org/wiki/LZ77_and_LZ78 +""" from dataclasses import dataclass @@ -7,16 +36,30 @@ @dataclass class Token: + """ + Dataclass representing triplet called token consisting of length, offset + and indicator. This triplet is used during LZ77 compression. + """ offset: int length: int indicator: str def __repr__(self) -> str: + """ + >>> token = Token(1, 2, "c") + >>> repr(token) + '(1, 2, c)' + >>> str(token) + '(1, 2, c)' + """ return f"({self.offset}, {self.length}, {self.indicator})" class LZ77Compressor: + """ + Class containing compress and decompress methods using LZ77 compression algorithm. + """ def __init__(self, window_size: int = 13, lookahead_buffer_size: int = 6) -> None: self.window_size = window_size @@ -24,6 +67,21 @@ self.search_buffer_size = self.window_size - self.lookahead_buffer_size def compress(self, text: str) -> list[Token]: + """ + Compress the given string text using LZ77 compression algorithm. + + Args: + text: string to be compressed + + Returns: + output: the compressed text as a list of Tokens + + >>> lz77_compressor = LZ77Compressor() + >>> str(lz77_compressor.compress("ababcbababaa")) + '[(0, 0, a), (0, 0, b), (2, 2, c), (4, 3, a), (2, 2, a)]' + >>> str(lz77_compressor.compress("aacaacabcabaaac")) + '[(0, 0, a), (1, 1, c), (3, 4, b), (3, 3, a), (1, 2, c)]' + """ output = [] search_buffer = "" @@ -51,6 +109,28 @@ return output def decompress(self, tokens: list[Token]) -> str: + """ + Convert the list of tokens into an output string. + + Args: + tokens: list containing triplets (offset, length, char) + + Returns: + output: decompressed text + + Tests: + >>> lz77_compressor = LZ77Compressor() + >>> lz77_compressor.decompress([Token(0, 0, 'c'), Token(0, 0, 'a'), + ... Token(0, 0, 'b'), Token(0, 0, 'r'), Token(3, 1, 'c'), + ... Token(2, 1, 'd'), Token(7, 4, 'r'), Token(3, 5, 'd')]) + 'cabracadabrarrarrad' + >>> lz77_compressor.decompress([Token(0, 0, 'a'), Token(0, 0, 'b'), + ... Token(2, 2, 'c'), Token(4, 3, 'a'), Token(2, 2, 'a')]) + 'ababcbababaa' + >>> lz77_compressor.decompress([Token(0, 0, 'a'), Token(1, 1, 'c'), + ... Token(3, 4, 'b'), Token(3, 3, 'a'), Token(1, 2, 'c')]) + 'aacaacabcabaaac' + """ output = "" @@ -62,6 +142,23 @@ return output def _find_encoding_token(self, text: str, search_buffer: str) -> Token: + """Finds the encoding token for the first character in the text. + + Tests: + >>> lz77_compressor = LZ77Compressor() + >>> lz77_compressor._find_encoding_token("abrarrarrad", "abracad").offset + 7 + >>> lz77_compressor._find_encoding_token("adabrarrarrad", "cabrac").length + 1 + >>> lz77_compressor._find_encoding_token("abc", "xyz").offset + 0 + >>> lz77_compressor._find_encoding_token("", "xyz").offset + Traceback (most recent call last): + ... + ValueError: We need some text to work with. + >>> lz77_compressor._find_encoding_token("abc", "").offset + 0 + """ if not text: raise ValueError("We need some text to work with.") @@ -86,6 +183,26 @@ def _match_length_from_index( self, text: str, window: str, text_index: int, window_index: int ) -> int: + """Calculate the longest possible match of text and window characters from + text_index in text and window_index in window. + + Args: + text: _description_ + window: sliding window + text_index: index of character in text + window_index: index of character in sliding window + + Returns: + The maximum match between text and window, from given indexes. + + Tests: + >>> lz77_compressor = LZ77Compressor(13, 6) + >>> lz77_compressor._match_length_from_index("rarrad", "adabrar", 0, 4) + 5 + >>> lz77_compressor._match_length_from_index("adabrarrarrad", + ... "cabrac", 0, 1) + 1 + """ if not text or text[text_index] != window[window_index]: return 0 return 1 + self._match_length_from_index( @@ -105,4 +222,4 @@ compressed_text = lz77_compressor.compress(TEXT) print(lz77_compressor.compress("ababcbababaa")) decompressed_text = lz77_compressor.decompress(compressed_text) - assert decompressed_text == TEXT, "The LZ77 algorithm returned the invalid result."+ assert decompressed_text == TEXT, "The LZ77 algorithm returned the invalid result."
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, "M": 1000} total = 0 place = 0 while place < len(roman): if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def int_to_roman(number: int) -> str: result = [] for arabic, roman in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} - total = 0 - place = 0 - while place < len(roman): - if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): - total += vals[roman[place + 1]] - vals[roman[place]] - place += 2 - else: - total += vals[roman[place]] - place += 1 - return total - - -def int_to_roman(number: int) -> str: - result = [] - for arabic, roman in ROMAN: - (factor, number) = divmod(number, arabic) - result.append(roman * factor) - if number == 0: - break - return "".join(result) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+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: + """ + LeetCode No. 13 Roman to Integer + Given a roman numeral, convert it to an integer. + Input is guaranteed to be within the range from 1 to 3999. + https://en.wikipedia.org/wiki/Roman_numerals + >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} + >>> all(roman_to_int(key) == value for key, value in tests.items()) + True + """ + vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} + total = 0 + place = 0 + while place < len(roman): + if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): + total += vals[roman[place + 1]] - vals[roman[place]] + place += 2 + else: + total += vals[roman[place]] + place += 1 + return total + + +def int_to_roman(number: int) -> str: + """ + Given a integer, convert it to an roman numeral. + https://en.wikipedia.org/wiki/Roman_numerals + >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} + >>> all(int_to_roman(value) == key for key, value in tests.items()) + True + """ + result = [] + for arabic, roman in ROMAN: + (factor, number) = divmod(number, arabic) + result.append(roman * factor) + if number == 0: + break + return "".join(result) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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 = 20 kilo = 10 @unique 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 = -15 atto = -18 zepto = -21 yocto = -24 @classmethod def get_positive(cls) -> dict: return {unit.name: unit.value for unit in cls if unit.value > 0} @classmethod def get_negative(cls) -> dict: return {unit.name: unit.value for unit in cls if unit.value < 0} def add_si_prefix(value: float) -> str: prefixes = SIUnit.get_positive() if value > 0 else SIUnit.get_negative() for name_prefix, value_prefix in prefixes.items(): numerical_part = value / (10**value_prefix) if numerical_part > 1: return f"{numerical_part!s} {name_prefix}" return str(value) def add_binary_prefix(value: float) -> str: for prefix in BinaryUnit: numerical_part = value / (2**prefix.value) if numerical_part > 1: return f"{numerical_part!s} {prefix.name}" return str(value) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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://en.wikipedia.org/wiki/Binary_prefix +""" from __future__ import annotations @@ -45,14 +54,44 @@ @classmethod def get_positive(cls) -> dict: + """ + Returns a dictionary with only the elements of this enum + that has a positive value + >>> from itertools import islice + >>> positive = SIUnit.get_positive() + >>> inc = iter(positive.items()) + >>> dict(islice(inc, len(positive) // 2)) + {'yotta': 24, 'zetta': 21, 'exa': 18, 'peta': 15, 'tera': 12} + >>> dict(inc) + {'giga': 9, 'mega': 6, 'kilo': 3, 'hecto': 2, 'deca': 1} + """ return {unit.name: unit.value for unit in cls if unit.value > 0} @classmethod def get_negative(cls) -> dict: + """ + Returns a dictionary with only the elements of this enum + that has a negative value + @example + >>> from itertools import islice + >>> negative = SIUnit.get_negative() + >>> inc = iter(negative.items()) + >>> dict(islice(inc, len(negative) // 2)) + {'deci': -1, 'centi': -2, 'milli': -3, 'micro': -6, 'nano': -9} + >>> dict(inc) + {'pico': -12, 'femto': -15, 'atto': -18, 'zepto': -21, 'yocto': -24} + """ return {unit.name: unit.value for unit in cls if unit.value < 0} def add_si_prefix(value: float) -> str: + """ + Function that converts a number to his version with SI prefix + @input value (an integer) + @example: + >>> add_si_prefix(10000) + '10.0 kilo' + """ prefixes = SIUnit.get_positive() if value > 0 else SIUnit.get_negative() for name_prefix, value_prefix in prefixes.items(): numerical_part = value / (10**value_prefix) @@ -62,6 +101,13 @@ def add_binary_prefix(value: float) -> str: + """ + Function that converts a number to his version with Binary prefix + @input value (an integer) + @example: + >>> add_binary_prefix(65536) + '64.0 kilo' + """ for prefix in BinaryUnit: numerical_part = value / (2**prefix.value) if numerical_part > 1: @@ -72,4 +118,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 Exception("value should be between 0 and 1") chroma = value * saturation hue_section = hue / 60 second_largest_component = chroma * (1 - abs(hue_section % 2 - 1)) match_value = value - chroma if hue_section >= 0 and hue_section <= 1: red = round(255 * (chroma + match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (match_value)) elif hue_section > 1 and hue_section <= 2: red = round(255 * (second_largest_component + match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (match_value)) elif hue_section > 2 and hue_section <= 3: red = round(255 * (match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (second_largest_component + match_value)) elif hue_section > 3 and hue_section <= 4: red = round(255 * (match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (chroma + match_value)) elif hue_section > 4 and hue_section <= 5: red = round(255 * (second_largest_component + match_value)) green = round(255 * (match_value)) blue = round(255 * (chroma + match_value)) else: red = round(255 * (chroma + match_value)) green = round(255 * (match_value)) blue = round(255 * (second_largest_component + match_value)) return [red, green, blue] def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]: if red < 0 or red > 255: raise Exception("red should be between 0 and 255") if green < 0 or green > 255: raise Exception("green should be between 0 and 255") if blue < 0 or blue > 255: raise Exception("blue should be between 0 and 255") float_red = red / 255 float_green = green / 255 float_blue = blue / 255 value = max(float_red, float_green, float_blue) chroma = value - min(float_red, float_green, float_blue) saturation = 0 if value == 0 else chroma / value if chroma == 0: hue = 0.0 elif value == float_red: hue = 60 * (0 + (float_green - float_blue) / chroma) elif value == float_green: hue = 60 * (2 + (float_blue - float_red) / chroma) else: hue = 60 * (4 + (float_red - float_green) / chroma) hue = (hue + 360) % 360 return [hue, saturation, value] def approximately_equal_hsv(hsv_1: list[float], hsv_2: list[float]) -> bool: check_hue = abs(hsv_1[0] - hsv_2[0]) < 0.2 check_saturation = abs(hsv_1[1] - hsv_2[1]) < 0.002 check_value = abs(hsv_1[2] - hsv_2[2]) < 0.002 return check_hue and check_saturation and check_value
--- +++ @@ -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 representation models how colors appear under +light. In it, colors are represented using three components: hue, saturation and +(brightness-)value. This file provides functions for converting colors from one +representation to the other. + +(description adapted from https://en.wikipedia.org/wiki/RGB_color_model and +https://en.wikipedia.org/wiki/HSL_and_HSV). +""" def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]: + """ + Conversion from the HSV-representation to the RGB-representation. + Expected RGB-values taken from + https://www.rapidtables.com/convert/color/hsv-to-rgb.html + + >>> hsv_to_rgb(0, 0, 0) + [0, 0, 0] + >>> hsv_to_rgb(0, 0, 1) + [255, 255, 255] + >>> hsv_to_rgb(0, 1, 1) + [255, 0, 0] + >>> hsv_to_rgb(60, 1, 1) + [255, 255, 0] + >>> hsv_to_rgb(120, 1, 1) + [0, 255, 0] + >>> hsv_to_rgb(240, 1, 1) + [0, 0, 255] + >>> hsv_to_rgb(300, 1, 1) + [255, 0, 255] + >>> hsv_to_rgb(180, 0.5, 0.5) + [64, 128, 128] + >>> hsv_to_rgb(234, 0.14, 0.88) + [193, 196, 224] + >>> hsv_to_rgb(330, 0.75, 0.5) + [128, 32, 80] + """ if hue < 0 or hue > 360: raise Exception("hue should be between 0 and 360") @@ -44,6 +82,33 @@ def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]: + """ + Conversion from the RGB-representation to the HSV-representation. + The tested values are the reverse values from the hsv_to_rgb-doctests. + Function "approximately_equal_hsv" is needed because of small deviations due to + rounding for the RGB-values. + + >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 0), [0, 0, 0]) + True + >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 255), [0, 0, 1]) + True + >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 0), [0, 1, 1]) + True + >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 0), [60, 1, 1]) + True + >>> approximately_equal_hsv(rgb_to_hsv(0, 255, 0), [120, 1, 1]) + True + >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 255), [240, 1, 1]) + True + >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 255), [300, 1, 1]) + True + >>> approximately_equal_hsv(rgb_to_hsv(64, 128, 128), [180, 0.5, 0.5]) + True + >>> approximately_equal_hsv(rgb_to_hsv(193, 196, 224), [234, 0.14, 0.88]) + True + >>> approximately_equal_hsv(rgb_to_hsv(128, 32, 80), [330, 0.75, 0.5]) + True + """ if red < 0 or red > 255: raise Exception("red should be between 0 and 255") @@ -75,8 +140,20 @@ def approximately_equal_hsv(hsv_1: list[float], hsv_2: list[float]) -> bool: + """ + Utility-function to check that two hsv-colors are approximately equal + + >>> approximately_equal_hsv([0, 0, 0], [0, 0, 0]) + True + >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.500001, 0.30001]) + True + >>> approximately_equal_hsv([0, 0, 0], [1, 0, 0]) + False + >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.6, 0.30001]) + False + """ check_hue = abs(hsv_1[0] - hsv_2[0]) < 0.2 check_saturation = abs(hsv_1[1] - hsv_2[1]) < 0.002 check_value = abs(hsv_1[2] - hsv_2[2]) < 0.002 - return check_hue and check_saturation and check_value+ return check_hue and check_saturation and check_value
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: Any) -> None: self.data.append(data) self.tail = self.tail + 1 def pop(self) -> Any: ret = self.data[self.head] self.head = self.head + 1 return ret def count(self) -> int: return self.tail - self.head def print_queue(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail]) class MyNode: def __init__(self, data: Any) -> None: self.data = data self.left: MyNode | None = None self.right: MyNode | None = None self.height: int = 1 def get_data(self) -> Any: return self.data def get_left(self) -> MyNode | None: return self.left def get_right(self) -> MyNode | None: return self.right def get_height(self) -> int: return self.height def set_data(self, data: Any) -> None: self.data = data def set_left(self, node: MyNode | None) -> None: self.left = node def set_right(self, node: MyNode | None) -> None: self.right = node def set_height(self, height: int) -> None: self.height = height def get_height(node: MyNode | None) -> int: if node is None: return 0 return node.get_height() def my_max(a: int, b: int) -> int: if a > b: return a return b def right_rotation(node: MyNode) -> MyNode: print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None node.set_left(ret.get_right()) ret.set_right(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def left_rotation(node: MyNode) -> MyNode: print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None node.set_right(ret.get_left()) ret.set_left(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def lr_rotation(node: MyNode) -> MyNode: left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) return right_rotation(node) def rl_rotation(node: MyNode) -> MyNode: right_child = node.get_right() assert right_child is not None node.set_right(right_rotation(right_child)) return left_rotation(node) def insert_node(node: MyNode | None, data: Any) -> MyNode | None: if node is None: return MyNode(data) if data < node.get_data(): node.set_left(insert_node(node.get_left(), data)) if ( get_height(node.get_left()) - get_height(node.get_right()) == 2 ): # an unbalance detected left_child = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child node = right_rotation(node) else: node = lr_rotation(node) else: node.set_right(insert_node(node.get_right(), data)) if get_height(node.get_right()) - get_height(node.get_left()) == 2: right_child = node.get_right() assert right_child is not None if data < right_child.get_data(): node = rl_rotation(node) else: node = left_rotation(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) return node def get_right_most(root: MyNode) -> Any: while True: right_child = root.get_right() if right_child is None: break root = right_child return root.get_data() def get_left_most(root: MyNode) -> Any: while True: left_child = root.get_left() if left_child is None: break root = left_child return root.get_data() def del_node(root: MyNode, data: Any) -> MyNode | None: left_child = root.get_left() right_child = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: temp_data = get_left_most(right_child) root.set_data(temp_data) root.set_right(del_node(right_child, temp_data)) elif left_child is not None: root = left_child elif right_child is not None: root = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data") return root else: root.set_left(del_node(left_child, data)) # root.get_data() < data elif right_child is None: return root else: root.set_right(del_node(right_child, data)) # Re-fetch left_child and right_child references left_child = root.get_left() right_child = root.get_right() if get_height(right_child) - get_height(left_child) == 2: assert right_child is not None if get_height(right_child.get_right()) > get_height(right_child.get_left()): root = left_rotation(root) else: root = rl_rotation(root) elif get_height(right_child) - get_height(left_child) == -2: assert left_child is not None if get_height(left_child.get_left()) > get_height(left_child.get_right()): root = right_rotation(root) else: root = lr_rotation(root) height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1 root.set_height(height) return root class AVLtree: def __init__(self) -> None: self.root: MyNode | None = None def get_height(self) -> int: return get_height(self.root) def insert(self, data: Any) -> None: print("insert:" + str(data)) self.root = insert_node(self.root, data) def del_node(self, data: Any) -> None: print("delete:" + str(data)) if self.root is None: print("Tree is empty!") return self.root = del_node(self.root, data) def __str__( self, ) -> str: # a level traversale, gives a more intuitive look on the tree output = "" q = MyQueue() q.push(self.root) layer = self.get_height() if layer == 0: return output cnt = 0 while not q.is_empty(): node = q.pop() space = " " * int(math.pow(2, layer - 1)) output += space if node is None: output += "*" q.push(None) q.push(None) else: output += str(node.get_data()) q.push(node.get_left()) q.push(node.get_right()) output += space cnt = cnt + 1 for i in range(100): if cnt == math.pow(2, i) - 1: layer = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _test() -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() t = AVLtree() lst = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
--- +++ @@ -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""" + A B + / \ / \ + B C Bl A + / \ --> / / \ + Bl Br UB Br C + / + UB + UB = unbalanced node + """ print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None @@ -91,6 +108,9 @@ def left_rotation(node: MyNode) -> MyNode: + """ + a mirror symmetry rotation of the left_rotation + """ print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None @@ -104,6 +124,16 @@ def lr_rotation(node: MyNode) -> MyNode: + r""" + A A Br + / \ / \ / \ + B C LR Br C RR B A + / \ --> / \ --> / / \ + Bl Br B UB Bl UB C + \ / + UB Bl + RR = right_rotation LR = left_rotation + """ left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) @@ -213,6 +243,38 @@ class AVLtree: + """ + An AVL tree doctest + Examples: + >>> t = AVLtree() + >>> t.insert(4) + insert:4 + >>> print(str(t).replace(" \\n","\\n")) + 4 + ************************************* + >>> t.insert(2) + insert:2 + >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) + 4 + 2 * + ************************************* + >>> t.insert(3) + insert:3 + right rotation node: 2 + left rotation node: 4 + >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) + 3 + 2 4 + ************************************* + >>> t.get_height() + 2 + >>> t.del_node(3) + delete:3 + >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) + 4 + 2 * + ************************************* + """ def __init__(self) -> None: self.root: MyNode | None = None @@ -284,4 +346,4 @@ random.shuffle(lst) for i in lst: t.del_node(i) - print(str(t))+ print(str(t))
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: rows = len(array) cols = len(array[0]) if rows == 0 or cols == 0: raise ValueError("no items in array") if index < 0 or index >= rows * cols: raise ValueError("index out of range") return array[index // cols][index % cols] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 the iterator in a loop. +Examples: +list(Index2DArrayIterator(matrix)) +set(Index2DArrayIterator(matrix)) +tuple(Index2DArrayIterator(matrix)) +sum(Index2DArrayIterator(matrix)) +-5 in Index2DArrayIterator(matrix) + +2. index_2d_array_in_1d(array: list[int], index: int) -> int +This function allows you to provide a 2D array and a 0-indexed 1D integer index, +and retrieves the integer value at that index. + +Python doctests can be run using this command: +python3 -m doctest -v index_2d_array_in_1d.py +""" from collections.abc import Iterator from dataclasses import dataclass @@ -8,11 +29,64 @@ matrix: list[list[int]] def __iter__(self) -> Iterator[int]: + """ + >>> tuple(Index2DArrayIterator([[5], [-523], [-1], [34], [0]])) + (5, -523, -1, 34, 0) + >>> tuple(Index2DArrayIterator([[5, -523, -1], [34, 0]])) + (5, -523, -1, 34, 0) + >>> tuple(Index2DArrayIterator([[5, -523, -1, 34, 0]])) + (5, -523, -1, 34, 0) + >>> t = Index2DArrayIterator([[5, 2, 25], [23, 14, 5], [324, -1, 0]]) + >>> tuple(t) + (5, 2, 25, 23, 14, 5, 324, -1, 0) + >>> list(t) + [5, 2, 25, 23, 14, 5, 324, -1, 0] + >>> sorted(t) + [-1, 0, 2, 5, 5, 14, 23, 25, 324] + >>> tuple(t)[3] + 23 + >>> sum(t) + 397 + >>> -1 in t + True + >>> t = iter(Index2DArrayIterator([[5], [-523], [-1], [34], [0]])) + >>> next(t) + 5 + >>> next(t) + -523 + """ for row in self.matrix: yield from row def index_2d_array_in_1d(array: list[list[int]], index: int) -> int: + """ + Retrieves the value of the one-dimensional index from a two-dimensional array. + + Args: + array: A 2D array of integers where all rows are the same size and all + columns are the same size. + index: A 1D index. + + Returns: + int: The 0-indexed value of the 1D index in the array. + + Examples: + >>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 5) + 5 + >>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], -1) + Traceback (most recent call last): + ... + ValueError: index out of range + >>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 12) + Traceback (most recent call last): + ... + ValueError: index out of range + >>> index_2d_array_in_1d([[]], 0) + Traceback (most recent call last): + ... + ValueError: no items in array + """ rows = len(array) cols = len(array[0]) @@ -28,4 +102,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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(arr) self.arr = sorted(arr) # The input list self.n = len(arr) # The length of the input list self.compress_coordinates() def compress_coordinates(self) -> None: key = 0 for val in self.arr: if val not in self.coordinate_map: self.coordinate_map[val] = key self.reverse_map[key] = val key += 1 def compress(self, original: float | str) -> int: return self.coordinate_map.get(original, -1) def decompress(self, num: int) -> int | float | str: return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1 if __name__ == "__main__": from doctest import testmod testmod() arr: list[int | float | str] = [100, 10, 52, 83] cc = CoordinateCompressor(arr) for original in arr: compressed = cc.compress(original) decompressed = cc.decompress(compressed) print(f"Original: {decompressed}, Compressed: {compressed}")
--- +++ @@ -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 list of values. + + Mapping: + In addition to compression and decompression, this class maintains a mapping + between original values and their compressed counterparts using two data + structures: a dictionary `coordinate_map` and a list `reverse_map`: + - `coordinate_map`: A dictionary that maps original values to their compressed + coordinates. Keys are original values, and values are compressed coordinates. + - `reverse_map`: A list used for reverse mapping, where each index corresponds + to a compressed coordinate, and the value at that index is the original value. + + Example of mapping: + Original: 10, Compressed: 0 + Original: 52, Compressed: 1 + Original: 83, Compressed: 2 + Original: 100, Compressed: 3 + + This mapping allows for efficient compression and decompression of values within + the list. + """ def __init__(self, arr: list[int | float | str]) -> None: + """ + Initialize the CoordinateCompressor with a list. + + Args: + arr: The list of values to be compressed. + + >>> arr = [100, 10, 52, 83] + >>> cc = CoordinateCompressor(arr) + >>> cc.compress(100) + 3 + >>> cc.compress(52) + 1 + >>> cc.decompress(1) + 52 + """ # A dictionary to store compressed coordinates self.coordinate_map: dict[int | float | str, int] = {} @@ -15,6 +58,20 @@ self.compress_coordinates() def compress_coordinates(self) -> None: + """ + Compress the coordinates in the input list. + + >>> arr = [100, 10, 52, 83] + >>> cc = CoordinateCompressor(arr) + >>> cc.coordinate_map[83] + 2 + >>> cc.coordinate_map[80] # Value not in the original list + Traceback (most recent call last): + ... + KeyError: 80 + >>> cc.reverse_map[2] + 83 + """ key = 0 for val in self.arr: if val not in self.coordinate_map: @@ -23,9 +80,41 @@ key += 1 def compress(self, original: float | str) -> int: + """ + Compress a single value. + + Args: + original: The value to compress. + + Returns: + The compressed integer, or -1 if not found in the original list. + + >>> arr = [100, 10, 52, 83] + >>> cc = CoordinateCompressor(arr) + >>> cc.compress(100) + 3 + >>> cc.compress(7) # Value not in the original list + -1 + """ return self.coordinate_map.get(original, -1) def decompress(self, num: int) -> int | float | str: + """ + Decompress a single integer. + + Args: + num: The compressed integer to decompress. + + Returns: + The original value. + + >>> arr = [100, 10, 52, 83] + >>> cc = CoordinateCompressor(arr) + >>> cc.decompress(0) + 10 + >>> cc.decompress(5) # Compressed coordinate out of range + -1 + """ return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1 @@ -40,4 +129,4 @@ for original in arr: compressed = cc.compress(original) decompressed = cc.decompress(compressed) - print(f"Original: {decompressed}, Compressed: {compressed}")+ print(f"Original: {decompressed}, Compressed: {compressed}")
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] def get_sum(self, start: int, end: int) -> int: if not self.prefix_sum: raise ValueError("The array is empty.") if start < 0 or end >= len(self.prefix_sum) or start > end: raise ValueError("Invalid range specified.") if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def contains_sum(self, target_sum: int) -> bool: sums = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(sum_item) return False if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: int) -> int: + """ + The function returns the sum of array from the start to the end indexes. + Runtime : O(1) + Space: O(1) + + >>> PrefixSum([1,2,3]).get_sum(0, 2) + 6 + >>> PrefixSum([1,2,3]).get_sum(1, 2) + 5 + >>> PrefixSum([1,2,3]).get_sum(2, 2) + 3 + >>> PrefixSum([]).get_sum(0, 0) + Traceback (most recent call last): + ... + ValueError: The array is empty. + >>> PrefixSum([1,2,3]).get_sum(-1, 2) + Traceback (most recent call last): + ... + ValueError: Invalid range specified. + >>> PrefixSum([1,2,3]).get_sum(2, 3) + Traceback (most recent call last): + ... + ValueError: Invalid range specified. + >>> PrefixSum([1,2,3]).get_sum(2, 1) + Traceback (most recent call last): + ... + ValueError: Invalid range specified. + """ if not self.prefix_sum: raise ValueError("The array is empty.") @@ -24,6 +59,26 @@ return self.prefix_sum[end] - self.prefix_sum[start - 1] def contains_sum(self, target_sum: int) -> bool: + """ + The function returns True if array contains the target_sum, + False otherwise. + + Runtime : O(n) + Space: O(n) + + >>> PrefixSum([1,2,3]).contains_sum(6) + True + >>> PrefixSum([1,2,3]).contains_sum(5) + True + >>> PrefixSum([1,2,3]).contains_sum(3) + True + >>> PrefixSum([1,2,3]).contains_sum(4) + False + >>> PrefixSum([1,2,3]).contains_sum(7) + False + >>> PrefixSum([1,-2,3]).contains_sum(2) + True + """ sums = {0} for sum_item in self.prefix_sum: @@ -38,4 +93,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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, moles: float, temperature: float) -> float: return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. + Volume is taken in litres. + + Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration + Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration + + >>> molarity_to_normality(2, 3.1, 0.31) + 20 + >>> molarity_to_normality(4, 11.4, 5.7) + 8 + """ return round(float(moles / volume) * nfactor) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: + """ + Convert moles to pressure. + Ideal gas laws are used. + Temperature is taken in kelvin. + Volume is taken in litres. + Pressure has atm as SI unit. + + Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws + Wikipedia reference: https://en.wikipedia.org/wiki/Pressure + Wikipedia reference: https://en.wikipedia.org/wiki/Temperature + + >>> moles_to_pressure(0.82, 3, 300) + 90 + >>> moles_to_pressure(8.2, 5, 200) + 10 + """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: + """ + Convert moles to volume. + Ideal gas laws are used. + Temperature is taken in kelvin. + Volume is taken in litres. + Pressure has atm as SI unit. + + Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws + Wikipedia reference: https://en.wikipedia.org/wiki/Pressure + Wikipedia reference: https://en.wikipedia.org/wiki/Temperature + + >>> moles_to_volume(0.82, 3, 300) + 90 + >>> moles_to_volume(8.2, 5, 200) + 10 + """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: + """ + Convert pressure and volume to temperature. + Ideal gas laws are used. + Temperature is taken in kelvin. + Volume is taken in litres. + Pressure has atm as SI unit. + + Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws + Wikipedia reference: https://en.wikipedia.org/wiki/Pressure + Wikipedia reference: https://en.wikipedia.org/wiki/Temperature + + >>> pressure_and_volume_to_temperature(0.82, 1, 2) + 20 + >>> pressure_and_volume_to_temperature(8.2, 5, 3) + 60 + """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: msg = f"root {root} is not present in the binary_tree" raise ValueError(msg) binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
--- +++ @@ -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: [4,5], 3: [6,7], 7: [8,9]}, 1) + {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]} + >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1) + {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]} + >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) + Traceback (most recent call last): + ... + ValueError: root 5 is not present in the binary_tree + >>> binary_tree_mirror({}, 5) + Traceback (most recent call last): + ... + ValueError: binary tree cannot be empty + """ if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: @@ -24,4 +42,4 @@ binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) - print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")+ print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
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, # Approximate value for a month in seconds "years": 31557600.0, # Approximate value for a year in seconds } time_chart_inverse: dict[str, float] = { key: 1 / value for key, value in time_chart.items() } def convert_time(time_value: float, unit_from: str, unit_to: str) -> float: if not isinstance(time_value, (int, float)) or time_value < 0: msg = "'time_value' must be a non-negative number." raise ValueError(msg) unit_from = unit_from.lower() unit_to = unit_to.lower() if unit_from not in time_chart or unit_to not in time_chart: invalid_unit = unit_from if unit_from not in time_chart else unit_to msg = f"Invalid unit {invalid_unit} is not in {', '.join(time_chart)}." raise ValueError(msg) return round( time_value * time_chart[unit_from] * time_chart_inverse[unit_to], 3, ) if __name__ == "__main__": import doctest doctest.testmod() print(f"{convert_time(3600,'seconds', 'hours') = :,}") print(f"{convert_time(360, 'days', 'months') = :,}") print(f"{convert_time(360, 'months', 'years') = :,}") print(f"{convert_time(1, 'years', 'seconds') = :,}")
--- +++ @@ -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 atom. + +https://en.wikipedia.org/wiki/Unit_of_time +""" time_chart: dict[str, float] = { "seconds": 1.0, @@ -15,6 +23,42 @@ def convert_time(time_value: float, unit_from: str, unit_to: str) -> float: + """ + Convert time from one unit to another using the time_chart above. + + >>> convert_time(3600, "seconds", "hours") + 1.0 + >>> convert_time(3500, "Seconds", "Hours") + 0.972 + >>> convert_time(1, "DaYs", "hours") + 24.0 + >>> convert_time(120, "minutes", "SeCoNdS") + 7200.0 + >>> convert_time(2, "WEEKS", "days") + 14.0 + >>> convert_time(0.5, "hours", "MINUTES") + 30.0 + >>> convert_time(-3600, "seconds", "hours") + Traceback (most recent call last): + ... + ValueError: 'time_value' must be a non-negative number. + >>> convert_time("Hello", "hours", "minutes") + Traceback (most recent call last): + ... + ValueError: 'time_value' must be a non-negative number. + >>> convert_time([0, 1, 2], "weeks", "days") + Traceback (most recent call last): + ... + ValueError: 'time_value' must be a non-negative number. + >>> convert_time(1, "cool", "century") # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: Invalid unit cool is not in seconds, minutes, hours, days, weeks, ... + >>> convert_time(1, "seconds", "hot") # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: Invalid unit hot is not in seconds, minutes, hours, days, weeks, ... + """ if not isinstance(time_value, (int, float)) or time_value < 0: msg = "'time_value' must be a non-negative number." raise ValueError(msg) @@ -39,4 +83,4 @@ print(f"{convert_time(3600,'seconds', 'hours') = :,}") print(f"{convert_time(360, 'days', 'months') = :,}") print(f"{convert_time(360, 'months', 'years') = :,}") - print(f"{convert_time(1, 'years', 'seconds') = :,}")+ print(f"{convert_time(1, 'years', 'seconds') = :,}")
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 foot": FromTo(0.028, 35.3147), "cup": FromTo(0.000236588, 4226.75), } def volume_conversion(value: float, from_type: str, to_type: str) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) return ( value * METRIC_CONVERSION[from_type].from_factor * METRIC_CONVERSION[to_type].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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": FromTo(0.76455, 1.30795), - "cubic foot": FromTo(0.028, 35.3147), - "cup": FromTo(0.000236588, 4226.75), -} - - -def volume_conversion(value: float, from_type: str, to_type: str) -> float: - if from_type not in METRIC_CONVERSION: - raise ValueError( - f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" - + ", ".join(METRIC_CONVERSION) - ) - if to_type not in METRIC_CONVERSION: - raise ValueError( - f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" - + ", ".join(METRIC_CONVERSION) - ) - return ( - value - * METRIC_CONVERSION[from_type].from_factor - * METRIC_CONVERSION[to_type].to_factor - ) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +Conversion of volume units. +Available Units:- Cubic metre,Litre,KiloLitre,Gallon,Cubic yard,Cubic foot,cup +USAGE : +-> Import this file into their respective project. +-> Use the function length_conversion() for conversion of volume units. +-> Parameters : + -> value : The number of from units you want to convert + -> from_type : From which type you want to convert + -> to_type : To which type you want to convert +REFERENCES : +-> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_metre +-> Wikipedia reference: https://en.wikipedia.org/wiki/Litre +-> Wikipedia reference: https://en.wiktionary.org/wiki/kilolitre +-> Wikipedia reference: https://en.wikipedia.org/wiki/Gallon +-> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_yard +-> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_foot +-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit) +""" + +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 foot": FromTo(0.028, 35.3147), + "cup": FromTo(0.000236588, 4226.75), +} + + +def volume_conversion(value: float, from_type: str, to_type: str) -> float: + """ + Conversion between volume units. + >>> volume_conversion(4, "cubic meter", "litre") + 4000 + >>> volume_conversion(1, "litre", "gallon") + 0.264172 + >>> volume_conversion(1, "kilolitre", "cubic meter") + 1 + >>> volume_conversion(3, "gallon", "cubic yard") + 0.017814279 + >>> volume_conversion(2, "cubic yard", "litre") + 1529.1 + >>> volume_conversion(4, "cubic foot", "cup") + 473.396 + >>> volume_conversion(1, "cup", "kilolitre") + 0.000236588 + >>> volume_conversion(4, "wrongUnit", "litre") + Traceback (most recent call last): + ... + ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: + cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup + """ + if from_type not in METRIC_CONVERSION: + raise ValueError( + f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + + ", ".join(METRIC_CONVERSION) + ) + if to_type not in METRIC_CONVERSION: + raise ValueError( + f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + + ", ".join(METRIC_CONVERSION) + ) + return ( + value + * METRIC_CONVERSION[from_type].from_factor + * METRIC_CONVERSION[to_type].to_factor + ) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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 self.data if self.right: yield from self.right @property def is_sorted(self) -> bool: if self.left and (self.data < self.left.data or not self.left.is_sorted): return False return not ( self.right and (self.data > self.right.data or not self.right.is_sorted) ) if __name__ == "__main__": import doctest doctest.testmod() tree = Node(data=2.1, left=Node(data=2.0), right=Node(data=2.2)) print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.") assert tree.right tree.right.data = 2.0 print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.") tree.right.data = 2.1 print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.")
--- +++ @@ -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 greater than the node's key. +- Both the left and right subtrees must also be binary search trees. + +In effect, a binary tree is a valid BST if its nodes are sorted in ascending order. +leetcode: https://leetcode.com/problems/validate-binary-search-tree/ + +If n is the number of nodes in the tree then: +Runtime: O(n) +Space: O(1) +""" from __future__ import annotations @@ -12,6 +27,17 @@ right: Node | None = None def __iter__(self) -> Iterator[float]: + """ + >>> root = Node(data=2.1) + >>> list(root) + [2.1] + >>> root.left=Node(data=2.0) + >>> list(root) + [2.0, 2.1] + >>> root.right=Node(data=2.2) + >>> list(root) + [2.0, 2.1, 2.2] + """ if self.left: yield from self.left yield self.data @@ -20,6 +46,38 @@ @property def is_sorted(self) -> bool: + """ + >>> Node(data='abc').is_sorted + True + >>> Node(data=2, + ... left=Node(data=1.999), + ... right=Node(data=3)).is_sorted + True + >>> Node(data=0, + ... left=Node(data=0), + ... right=Node(data=0)).is_sorted + True + >>> Node(data=0, + ... left=Node(data=-11), + ... right=Node(data=3)).is_sorted + True + >>> Node(data=5, + ... left=Node(data=1), + ... right=Node(data=4, left=Node(data=3))).is_sorted + False + >>> Node(data='a', + ... left=Node(data=1), + ... right=Node(data=4, left=Node(data=3))).is_sorted + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'str' and 'int' + >>> Node(data=2, + ... left=Node([]), + ... right=Node(data=4, left=Node(data=3))).is_sorted + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'int' and 'list' + """ if self.left and (self.data < self.left.data or not self.left.is_sorted): return False return not ( @@ -37,4 +95,4 @@ tree.right.data = 2.0 print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.") tree.right.data = 2.1 - print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.")+ print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.")
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__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 integers or nested +arrays. The product sum is obtained by adding all elements and multiplying by their +respective depths. + +For example, in the array [x, y], the product sum is (x + y). In the array [x, [y, z]], +the product sum is x + 2 * (y + z). In the array [x, [y, [z]]], +the product sum is x + 2 * (y + 3z). + +Example Input: +[5, 2, [-7, 1], 3, [6, [-13, 8], 4]] +Output: 12 + +""" def product_sum(arr: list[int | list], depth: int) -> int: + """ + Recursively calculates the product sum of an array. + + The product sum of an array is defined as the sum of its elements multiplied by + their respective depths. If an element is a list, its product sum is calculated + recursively by multiplying the sum of its elements with its depth plus one. + + Args: + arr: The array of integers and nested lists. + depth: The current depth level. + + Returns: + int: The product sum of the array. + + Examples: + >>> product_sum([1, 2, 3], 1) + 6 + >>> product_sum([-1, 2, [-3, 4]], 2) + 8 + >>> product_sum([1, 2, 3], -1) + -6 + >>> product_sum([1, 2, 3], 0) + 0 + >>> product_sum([1, 2, 3], 7) + 42 + >>> product_sum((1, 2, 3), 7) + 42 + >>> product_sum({1, 2, 3}, 7) + 42 + >>> product_sum([1, -1], 1) + 0 + >>> product_sum([1, -2], 1) + -1 + >>> product_sum([-3.5, [1, [0.5]]], 1) + 1.5 + + """ total_sum = 0 for ele in arr: total_sum += product_sum(ele, depth + 1) if isinstance(ele, list) else ele @@ -8,10 +65,34 @@ def product_sum_array(array: list[int | list]) -> int: + """ + Calculates the product sum of an array. + + Args: + array (List[Union[int, List]]): The array of integers and nested lists. + + Returns: + int: The product sum of the array. + + Examples: + >>> product_sum_array([1, 2, 3]) + 6 + >>> product_sum_array([1, [2, 3]]) + 11 + >>> product_sum_array([1, [2, [3, 4]]]) + 47 + >>> product_sum_array([0]) + 0 + >>> product_sum_array([-3.5, [1, [0.5]]]) + 1.5 + >>> product_sum_array([1, -2]) + -1 + + """ return product_sum(array, 1) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 equilibrium index (if any) or -1 if no equilibrium index exists. + +The equilibrium index of an array is an index such that the sum of +elements at lower indexes is equal to the sum of elements at higher indexes. + + + +Example Input: +arr = [-7, 1, 5, 2, -4, 3, 0] +Output: 3 + +""" def equilibrium_index(arr: list[int]) -> int: + """ + Find the equilibrium index of an array. + + Args: + arr (list[int]): The input array of integers. + + Returns: + int: The equilibrium index or -1 if no equilibrium index exists. + + Examples: + >>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0]) + 3 + >>> equilibrium_index([1, 2, 3, 4, 5]) + -1 + >>> equilibrium_index([1, 1, 1, 1, 1]) + 2 + >>> equilibrium_index([2, 4, 6, 8, 10, 3]) + -1 + """ total_sum = sum(arr) left_sum = 0 @@ -16,4 +55,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: list[int], position: int) -> int: if not arr: return -1 if not isinstance(position, int): raise ValueError("The position should be an integer") if not 1 <= position <= len(arr): raise ValueError("Invalid value of 'position'") low, high = 0, len(arr) - 1 while low <= high: if low > len(arr) - 1 or high < 0: return -1 pivot_index = partition(arr, low, high) if pivot_index == position - 1: return arr[pivot_index] elif pivot_index > position - 1: high = pivot_index - 1 else: low = pivot_index + 1 return -1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 rearranges the elements in the input list 'elements' such that + all elements greater than or equal to the chosen pivot are on the right side + of the pivot, and all elements smaller than the pivot are on the left side. + + Args: + arr: The list to be partitioned + low: The lower index of the list + high: The higher index of the list + + Returns: + int: The index of pivot element after partitioning + + Examples: + >>> partition([3, 1, 4, 5, 9, 2, 6, 5, 3, 5], 0, 9) + 4 + >>> partition([7, 1, 4, 5, 9, 2, 6, 5, 8], 0, 8) + 1 + >>> partition(['apple', 'cherry', 'date', 'banana'], 0, 3) + 2 + >>> partition([3.1, 1.2, 5.6, 4.7], 0, 3) + 1 + """ pivot = arr[high] i = low - 1 for j in range(low, high): @@ -12,6 +42,55 @@ def kth_largest_element(arr: list[int], position: int) -> int: + """ + Finds the kth largest element in a list. + Should deliver similar results to: + ```python + def kth_largest_element(arr, position): + return sorted(arr)[-position] + ``` + + Args: + nums: The list of numbers. + k: The position of the desired kth largest element. + + Returns: + int: The kth largest element. + + Examples: + >>> kth_largest_element([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 3) + 5 + >>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], 1) + 9 + >>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], -2) + Traceback (most recent call last): + ... + ValueError: Invalid value of 'position' + >>> kth_largest_element([9, 1, 3, 6, 7, 9, 8, 4, 2, 4, 9], 110) + Traceback (most recent call last): + ... + ValueError: Invalid value of 'position' + >>> kth_largest_element([1, 2, 4, 3, 5, 9, 7, 6, 5, 9, 3], 0) + Traceback (most recent call last): + ... + ValueError: Invalid value of 'position' + >>> kth_largest_element(['apple', 'cherry', 'date', 'banana'], 2) + 'cherry' + >>> kth_largest_element([3.1, 1.2, 5.6, 4.7,7.9,5,0], 2) + 5.6 + >>> kth_largest_element([-2, -5, -4, -1], 1) + -1 + >>> kth_largest_element([], 1) + -1 + >>> kth_largest_element([3.1, 1.2, 5.6, 4.7, 7.9, 5, 0], 1.5) + Traceback (most recent call last): + ... + ValueError: The position should be an integer + >>> kth_largest_element((4, 6, 1, 2), 4) + Traceback (most recent call last): + ... + TypeError: 'tuple' object does not support item assignment + """ if not arr: return -1 if not isinstance(position, int): @@ -35,4 +114,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 | None) -> int: if root is None: return 0 # Validation def count_nodes(node: TreeNode | None) -> int: if node is None: return 0 return count_nodes(node.left) + count_nodes(node.right) + 1 def count_coins(node: TreeNode | None) -> int: if node is None: return 0 return count_coins(node.left) + count_coins(node.right) + node.data if count_nodes(root) != count_coins(root): raise ValueError("The nodes number should be same as the number of coins") # Main calculation def get_distrib(node: TreeNode | None) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0, 1) left_distrib_moves, left_distrib_excess = get_distrib(node.left) right_distrib_moves, right_distrib_excess = get_distrib(node.right) coins_to_left = 1 - left_distrib_excess coins_to_right = 1 - right_distrib_excess result_moves = ( left_distrib_moves + right_distrib_moves + abs(coins_to_left) + abs(coins_to_right) ) result_excess = node.data - coins_to_left - coins_to_right return CoinsDistribResult(result_moves, result_excess) return get_distrib(root)[0] if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 another. A move may be from parent to child, or from child to parent. + +Return the minimum number of moves required to make every node have exactly one coin. + +Example 1: + + 3 + / \ + 0 0 + +Result: 2 + +Example 2: + + 0 + / \ + 3 0 + +Result 3 + +leetcode: https://leetcode.com/problems/distribute-coins-in-binary-tree/ + +Implementation notes: +User depth-first search approach. + +Let n is the number of nodes in tree +Runtime: O(n) +Space: O(1) +""" from __future__ import annotations @@ -18,18 +56,44 @@ def distribute_coins(root: TreeNode | None) -> int: + """ + >>> distribute_coins(TreeNode(3, TreeNode(0), TreeNode(0))) + 2 + >>> distribute_coins(TreeNode(0, TreeNode(3), TreeNode(0))) + 3 + >>> distribute_coins(TreeNode(0, TreeNode(0), TreeNode(3))) + 3 + >>> distribute_coins(None) + 0 + >>> distribute_coins(TreeNode(0, TreeNode(0), TreeNode(0))) + Traceback (most recent call last): + ... + ValueError: The nodes number should be same as the number of coins + >>> distribute_coins(TreeNode(0, TreeNode(1), TreeNode(1))) + Traceback (most recent call last): + ... + ValueError: The nodes number should be same as the number of coins + """ if root is None: return 0 # Validation def count_nodes(node: TreeNode | None) -> int: + """ + >>> count_nodes(None) + 0 + """ if node is None: return 0 return count_nodes(node.left) + count_nodes(node.right) + 1 def count_coins(node: TreeNode | None) -> int: + """ + >>> count_coins(None) + 0 + """ if node is None: return 0 @@ -40,6 +104,10 @@ # Main calculation def get_distrib(node: TreeNode | None) -> CoinsDistribResult: + """ + >>> get_distrib(None) + namedtuple("CoinsDistribResult", "0 2") + """ if node is None: return CoinsDistribResult(0, 1) @@ -66,4 +134,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 return encoded def run_length_decode(encoded: list) -> str: return "".join(char * length for char, length in encoded) if __name__ == "__main__": from doctest import testmod testmod(name="run_length_encode", verbose=True) testmod(name="run_length_decode", verbose=True)
--- +++ @@ -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)] + >>> run_length_encode("AAADDDDDDFFFCCCAAVVVV") + [('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)] + """ encoded = [] count = 1 @@ -16,6 +27,17 @@ def run_length_decode(encoded: list) -> str: + """ + Performs Run Length Decoding + >>> run_length_decode([('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)]) + 'AAAABBBCCDAA' + >>> run_length_decode([('A', 1)]) + 'A' + >>> run_length_decode([('A', 2)]) + 'AA' + >>> run_length_decode([('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)]) + 'AAADDDDDDFFFCCCAAVVVV' + """ return "".join(char * length for char, length in encoded) @@ -23,4 +45,4 @@ from doctest import testmod testmod(name="run_length_encode", verbose=True) - testmod(name="run_length_decode", verbose=True)+ testmod(name="run_length_decode", verbose=True)
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 in range(len(s))] def bwt_transform(s: str) -> BWTTransformDict: if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
--- +++ @@ -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 has runs +of repeated characters by techniques such as move-to-front transform and +run-length encoding. More importantly, the transformation is reversible, +without needing to store any additional data except the position of the first +original character. The BWT is thus a "free" method of improving the efficiency +of text compression algorithms, costing only some extra computation. +""" from __future__ import annotations @@ -10,6 +22,29 @@ def all_rotations(s: str) -> list[str]: + """ + :param s: The string that will be rotated len(s) times. + :return: A list with the rotations. + :raises TypeError: If s is not an instance of str. + Examples: + + >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE + ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', + 'A|^BANAN', '|^BANANA'] + >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE + ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', + 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', + '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', + 'aa_asa_da_cas'] + >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE + ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', + 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', + 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] + >>> all_rotations(5) + Traceback (most recent call last): + ... + TypeError: The parameter s type must be str. + """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") @@ -17,6 +52,29 @@ def bwt_transform(s: str) -> BWTTransformDict: + """ + :param s: The string that will be used at bwt algorithm + :return: the string composed of the last char of each row of the ordered + rotations and the index of the original string at ordered rotations list + :raises TypeError: If the s parameter type is not str + :raises ValueError: If the s parameter is empty + Examples: + + >>> bwt_transform("^BANANA") + {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} + >>> bwt_transform("a_asa_da_casa") + {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} + >>> bwt_transform("panamabanana") + {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} + >>> bwt_transform(4) + Traceback (most recent call last): + ... + TypeError: The parameter s type must be str. + >>> bwt_transform('') + Traceback (most recent call last): + ... + ValueError: The parameter s must not be empty. + """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: @@ -33,6 +91,51 @@ def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: + """ + :param bwt_string: The string returned from bwt algorithm execution + :param idx_original_string: A 0-based index of the string that was used to + generate bwt_string at ordered rotations list + :return: The string used to generate bwt_string when bwt was executed + :raises TypeError: If the bwt_string parameter type is not str + :raises ValueError: If the bwt_string parameter is empty + :raises TypeError: If the idx_original_string type is not int or if not + possible to cast it to int + :raises ValueError: If the idx_original_string value is lower than 0 or + greater than len(bwt_string) - 1 + + >>> reverse_bwt("BNN^AAA", 6) + '^BANANA' + >>> reverse_bwt("aaaadss_c__aa", 3) + 'a_asa_da_casa' + >>> reverse_bwt("mnpbnnaaaaaa", 11) + 'panamabanana' + >>> reverse_bwt(4, 11) + Traceback (most recent call last): + ... + TypeError: The parameter bwt_string type must be str. + >>> reverse_bwt("", 11) + Traceback (most recent call last): + ... + ValueError: The parameter bwt_string must not be empty. + >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + TypeError: The parameter idx_original_string type must be int or passive + of cast to int. + >>> reverse_bwt("mnpbnnaaaaaa", -1) + Traceback (most recent call last): + ... + ValueError: The parameter idx_original_string must not be lower than 0. + >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + ValueError: The parameter idx_original_string must be lower than + len(bwt_string). + >>> reverse_bwt("mnpbnnaaaaaa", 11.0) + 'panamabanana' + >>> reverse_bwt("mnpbnnaaaaaa", 11.4) + 'panamabanana' + """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: @@ -71,4 +174,4 @@ print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" - )+ )
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 # Initialize the final output array with blank. output_arr = [] # Set the initial element as arr[i]. for index, item in enumerate(arr[:-2]): # to store second elements that can complement the final sum. set_initialize = set() # current sum needed for reaching the target sum current_sum = target_sum - item # Traverse the subarray arr[i+1:]. for other_item in arr[index + 1 :]: # required value for the second element required_value = current_sum - other_item # Verify if the desired value exists in the set. if required_value in set_initialize: # finding triplet elements combination. combination_array = sorted([item, other_item, required_value]) if combination_array not in output_arr: output_arr.append(combination_array) # Include the current element in the set # for subsequent complement verification. set_initialize.add(other_item) # Return all the triplet combinations. return output_arr if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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: + >>> find_triplets_with_0_sum([-1, 0, 1, 2, -1, -4]) + [[-1, -1, 2], [-1, 0, 1]] + >>> find_triplets_with_0_sum([]) + [] + >>> find_triplets_with_0_sum([0, 0, 0]) + [[0, 0, 0]] + >>> find_triplets_with_0_sum([1, 2, 3, 0, -1, -2, -3]) + [[-3, 0, 3], [-3, 1, 2], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]] + """ return [ list(x) for x in sorted({abc for abc in combinations(sorted(nums), 3) if not sum(abc)}) @@ -9,6 +25,29 @@ def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]: + """ + Function for finding the triplets with a given sum in the array using hashing. + + 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: + >>> find_triplets_with_0_sum_hashing([-1, 0, 1, 2, -1, -4]) + [[-1, 0, 1], [-1, -1, 2]] + >>> find_triplets_with_0_sum_hashing([]) + [] + >>> find_triplets_with_0_sum_hashing([0, 0, 0]) + [[0, 0, 0]] + >>> find_triplets_with_0_sum_hashing([1, 2, 3, 0, -1, -2, -3]) + [[-1, 0, 1], [-3, 1, 2], [-2, 0, 2], [-2, -1, 3], [-3, 0, 3]] + + Time complexity: O(N^2) + Auxiliary Space: O(N) + + """ target_sum = 0 # Initialize the final output array with blank. @@ -45,4 +84,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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.extend(permutations) nums.append(n) return result def permute_backtrack(nums: list[int]) -> list[list[int]]: def backtrack(start: int) -> None: if start == len(nums) - 1: output.append(nums[:]) else: for i in range(start, len(nums)): nums[start], nums[i] = nums[i], nums[start] backtrack(start + 1) nums[start], nums[i] = nums[i], nums[start] # backtrack output: list[list[int]] = [] backtrack(0) return output if __name__ == "__main__": import doctest result = permute_backtrack([1, 2, 3]) print(result) doctest.testmod()
--- +++ @@ -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 [[]] @@ -13,6 +19,12 @@ def permute_backtrack(nums: list[int]) -> list[list[int]]: + """ + Return all permutations of the given list. + + >>> permute_backtrack([1, 2, 3]) + [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]] + """ def backtrack(start: int) -> None: if start == len(nums) - 1: @@ -33,4 +45,4 @@ result = permute_backtrack([1, 2, 3]) print(result) - doctest.testmod()+ doctest.testmod()
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 & (index + 1)) - 1 def update(self, index: int, value: int) -> None: self.arr[index] = value while index < self.size: current_left_border = self.get_prev(index) + 1 if current_left_border == index: self.tree[index] = value else: self.tree[index] = max(value, current_left_border, index) index = self.get_next(index) def query(self, left: int, right: int) -> int: right -= 1 # Because of right is exclusive result = 0 while left <= right: current_left = self.get_prev(right) if left <= current_left: result = max(result, self.tree[right]) right = current_left else: result = max(result, self.arr[right]) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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) + >>> ft.update(2, 20) + >>> ft.query(0, 5) + 20 + >>> ft.update(4, 10) + >>> ft.query(2, 5) + 20 + >>> ft.query(1, 5) + 20 + >>> ft.update(2, 0) + >>> ft.query(0, 5) + 10 + >>> ft = MaxFenwickTree(10000) + >>> ft.update(255, 30) + >>> ft.query(0, 10000) + 30 + >>> ft = MaxFenwickTree(6) + >>> ft.update(5, 1) + >>> ft.query(5, 6) + 1 + >>> ft = MaxFenwickTree(6) + >>> ft.update(0, 1000) + >>> ft.query(0, 1) + 1000 + """ def __init__(self, size: int) -> None: + """ + Create empty Maximum Fenwick Tree with specified size + + Parameters: + size: size of Array + + Returns: + None + """ self.size = size self.arr = [0] * size self.tree = [0] * size @staticmethod def get_next(index: int) -> int: + """ + Get next index in O(1) + """ return index | (index + 1) @staticmethod def get_prev(index: int) -> int: + """ + Get previous index in O(1) + """ return (index & (index + 1)) - 1 def update(self, index: int, value: int) -> None: + """ + Set index to value in O(lg^2 N) + + Parameters: + index: index to update + value: value to set + + Returns: + None + """ self.arr[index] = value while index < self.size: current_left_border = self.get_prev(index) + 1 @@ -24,6 +85,16 @@ index = self.get_next(index) def query(self, left: int, right: int) -> int: + """ + Answer the query of maximum range [l, r) in O(lg^2 N) + + Parameters: + left: left index of query range (inclusive) + right: right index of query range (exclusive) + + Returns: + Maximum value of range [left, right) + """ right -= 1 # Because of right is exclusive result = 0 while left <= right: @@ -40,4 +111,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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] start += 1 end -= 1 reverse(0, n - 1) reverse(0, steps - 1) reverse(steps, n - 1) return arr if __name__ == "__main__": examples = [ ([1, 2, 3, 4, 5], 2), ([1, 2, 3, 4, 5], -2), ([1, 2, 3, 4, 5], 7), ([], 3), ] for arr, steps in examples: rotated = rotate_array(arr.copy(), steps) print(f"Rotate {arr} by {steps}: {rotated}")
--- +++ @@ -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: + List[int]: Rotated list. + + Examples: + >>> rotate_array([1, 2, 3, 4, 5], 2) + [4, 5, 1, 2, 3] + >>> rotate_array([1, 2, 3, 4, 5], -2) + [3, 4, 5, 1, 2] + >>> rotate_array([1, 2, 3, 4, 5], 7) + [4, 5, 1, 2, 3] + >>> rotate_array([], 3) + [] + """ n = len(arr) if n == 0: @@ -10,6 +30,30 @@ steps += n def reverse(start: int, end: int) -> None: + """ + Reverses a portion of the list in place from index start to end. + + Parameters: + start (int): Starting index of the portion to reverse. + end (int): Ending index of the portion to reverse. + + Returns: + None + + Examples: + >>> example = [1, 2, 3, 4, 5] + >>> def reverse_test(arr, start, end): + ... while start < end: + ... arr[start], arr[end] = arr[end], arr[start] + ... start += 1 + ... end -= 1 + >>> reverse_test(example, 0, 2) + >>> example + [3, 2, 1, 4, 5] + >>> reverse_test(example, 2, 4) + >>> example + [3, 2, 5, 4, 1] + """ while start < end: arr[start], arr[end] = arr[end], arr[start] @@ -33,4 +77,4 @@ for arr, steps in examples: rotated = rotate_array(arr.copy(), steps) - print(f"Rotate {arr} by {steps}: {rotated}")+ print(f"Rotate {arr} by {steps}: {rotated}")
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 except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict[str, str], curr_string: str, index: int, last_match_id: str ) -> None: lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key, value in lexicon.items(): lexicon[curr_key] = f"0{value}" lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path: str, destination_path: str) -> None: data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
--- +++ @@ -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 them as a long string + """ result = "" try: with open(file_path, "rb") as binary_file: @@ -21,6 +28,9 @@ def add_key_to_lexicon( lexicon: dict[str, str], curr_string: str, index: int, last_match_id: str ) -> None: + """ + Adds new strings (curr_string + "0", curr_string + "1") to the lexicon + """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id @@ -32,6 +42,10 @@ def compress_data(data_bits: str) -> str: + """ + Compresses given data_bits using Lempel-Ziv-Welch compression algorithm + and returns the result as a string + """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) @@ -58,6 +72,10 @@ def add_file_length(source_path: str, compressed: str) -> str: + """ + Adds given file's length in front (using Elias gamma coding) of the compressed + string + """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) @@ -66,6 +84,10 @@ def write_file_binary(file_path: str, to_write: str) -> None: + """ + Writes given to_write string (should only consist of 0's and 1's) as bytes in the + file + """ byte_length = 8 try: with open(file_path, "wb") as opened_file: @@ -89,6 +111,10 @@ def compress(source_path: str, destination_path: str) -> None: + """ + Reads source file, compresses it and writes the compressed result in destination + file + """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) @@ -96,4 +122,4 @@ if __name__ == "__main__": - compress(sys.argv[1], sys.argv[2])+ compress(sys.argv[1], sys.argv[2])
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 self.data if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) @property def is_sum_node(self) -> bool: if not self.left and not self.right: return True # leaf nodes are considered sum nodes left_sum = sum(self.left) if self.left else 0 right_sum = sum(self.right) if self.right else 0 return all( ( self.data == left_sum + right_sum, self.left.is_sum_node if self.left else True, self.right.is_sum_node if self.right else True, ) ) @dataclass class BinaryTree: root: Node def __iter__(self) -> Iterator[int]: return iter(self.root) def __len__(self) -> int: return len(self.root) def __str__(self) -> str: return str(list(self)) @property def is_sum_tree(self) -> bool: return self.root.is_sum_node @classmethod def build_a_tree(cls) -> BinaryTree: tree = BinaryTree(Node(11)) root = tree.root root.left = Node(2) root.right = Node(29) root.left.left = Node(1) root.left.right = Node(7) root.right.left = Node(15) root.right.right = Node(40) root.right.right.left = Node(35) return tree @classmethod def build_a_sum_tree(cls) -> BinaryTree: tree = BinaryTree(Node(26)) root = tree.root root.left = Node(10) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(6) root.right.right = Node(3) return tree if __name__ == "__main__": from doctest import testmod testmod() tree = BinaryTree.build_a_tree() print(f"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.") tree = BinaryTree.build_a_sum_tree() print(f"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.")
--- +++ @@ -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 = None def __iter__(self) -> Iterator[int]: + """ + >>> root = Node(2) + >>> list(root) + [2] + >>> root.left = Node(1) + >>> tuple(root) + (1, 2) + """ if self.left: yield from self.left yield self.data @@ -19,10 +32,29 @@ yield from self.right def __len__(self) -> int: + """ + >>> root = Node(2) + >>> len(root) + 1 + >>> root.left = Node(1) + >>> len(root) + 2 + """ return sum(1 for _ in self) @property def is_sum_node(self) -> bool: + """ + >>> root = Node(3) + >>> root.is_sum_node + True + >>> root.left = Node(1) + >>> root.is_sum_node + False + >>> root.right = Node(2) + >>> root.is_sum_node + True + """ if not self.left and not self.right: return True # leaf nodes are considered sum nodes left_sum = sum(self.left) if self.left else 0 @@ -41,20 +73,52 @@ root: Node def __iter__(self) -> Iterator[int]: + """ + >>> list(BinaryTree.build_a_tree()) + [1, 2, 7, 11, 15, 29, 35, 40] + """ return iter(self.root) def __len__(self) -> int: + """ + >>> len(BinaryTree.build_a_tree()) + 8 + """ return len(self.root) def __str__(self) -> str: + """ + Returns a string representation of the inorder traversal of the binary tree. + + >>> str(list(BinaryTree.build_a_tree())) + '[1, 2, 7, 11, 15, 29, 35, 40]' + """ return str(list(self)) @property def is_sum_tree(self) -> bool: + """ + >>> BinaryTree.build_a_tree().is_sum_tree + False + >>> BinaryTree.build_a_sum_tree().is_sum_tree + True + """ return self.root.is_sum_node @classmethod def build_a_tree(cls) -> BinaryTree: + r""" + Create a binary tree with the specified structure: + 11 + / \ + 2 29 + / \ / \ + 1 7 15 40 + \ + 35 + >>> list(BinaryTree.build_a_tree()) + [1, 2, 7, 11, 15, 29, 35, 40] + """ tree = BinaryTree(Node(11)) root = tree.root root.left = Node(2) @@ -68,6 +132,16 @@ @classmethod def build_a_sum_tree(cls) -> BinaryTree: + r""" + Create a binary tree with the specified structure: + 26 + / \ + 10 3 + / \ \ + 4 6 3 + >>> list(BinaryTree.build_a_sum_tree()) + [4, 10, 6, 26, 3, 3] + """ tree = BinaryTree(Node(26)) root = tree.root root.left = Node(10) @@ -85,4 +159,4 @@ tree = BinaryTree.build_a_tree() print(f"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.") tree = BinaryTree.build_a_sum_tree() - print(f"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.")+ print(f"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.")
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 ** j) of number_list, starting from index i. # smallest power of 2 subset length that fully covers number_list row = int(log2(length)) + 1 sparse_table = [[0 for i in range(length)] for j in range(row)] # minimum of subset of length 1 is that value itself for i, value in enumerate(number_list): sparse_table[0][i] = value j = 1 # compute the minimum value for all intervals with size (2 ** j) while (1 << j) <= length: i = 0 # while subset starting from i still have at least (2 ** j) elements while (i + (1 << j) - 1) < length: # split range [i, i + 2 ** j] and find minimum of 2 halves sparse_table[j][i] = min( sparse_table[j - 1][i + (1 << (j - 1))], sparse_table[j - 1][i] ) i += 1 j += 1 return sparse_table def query(sparse_table: list[list[int]], left_bound: int, right_bound: int) -> int: if left_bound < 0 or right_bound >= len(sparse_table[0]): raise IndexError("list index out of range") # highest subset length of power of 2 that is within range [left_bound, right_bound] j = int(log2(right_bound - left_bound + 1)) # minimum of 2 overlapping smaller subsets: # [left_bound, left_bound + 2 ** j - 1] and [right_bound - 2 ** j + 1, right_bound] return min(sparse_table[j][right_bound - (1 << j) + 1], sparse_table[j][left_bound]) if __name__ == "__main__": from doctest import testmod testmod() print(f"{query(build_sparse_table([3, 1, 9]), 2, 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 number list. + +Overall time complexity: O(nlogn) +Overall space complexity: O(nlogn) + +Wikipedia link: https://en.wikipedia.org/wiki/Range_minimum_query +""" from math import log2 def build_sparse_table(number_list: list[int]) -> list[list[int]]: + """ + Precompute range minimum queries with power of two length and store the precomputed + values in a table. + + >>> build_sparse_table([8, 1, 0, 3, 4, 9, 3]) + [[8, 1, 0, 3, 4, 9, 3], [1, 0, 0, 3, 4, 3, 0], [0, 0, 0, 3, 0, 0, 0]] + >>> build_sparse_table([3, 1, 9]) + [[3, 1, 9], [1, 1, 0]] + >>> build_sparse_table([]) + Traceback (most recent call last): + ... + ValueError: empty number list not allowed + """ if not number_list: raise ValueError("empty number list not allowed") @@ -34,6 +59,24 @@ def query(sparse_table: list[list[int]], left_bound: int, right_bound: int) -> int: + """ + >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 4) + 0 + >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 4, 6) + 3 + >>> query(build_sparse_table([3, 1, 9]), 2, 2) + 9 + >>> query(build_sparse_table([3, 1, 9]), 0, 1) + 1 + >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 11) + Traceback (most recent call last): + ... + IndexError: list index out of range + >>> query(build_sparse_table([]), 0, 0) + Traceback (most recent call last): + ... + ValueError: empty number list not allowed + """ if left_bound < 0 or right_bound >= len(sparse_table[0]): raise IndexError("list index out of range") @@ -49,4 +92,4 @@ from doctest import testmod testmod() - print(f"{query(build_sparse_table([3, 1, 9]), 2, 2) = }")+ print(f"{query(build_sparse_table([3, 1, 9]), 2, 2) = }")
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_with_sum(arr: list, req_sum: int) -> int: + """ + Return the no. of pairs with sum "sum" + >>> pairs_with_sum([1, 5, 7, 1], 6) + 2 + >>> pairs_with_sum([1, 1, 1, 1, 1, 1, 1, 1], 2) + 28 + >>> pairs_with_sum([1, 7, 6, 2, 5, 4, 3, 1, 9, 8], 7) + 4 + """ return len([1 for a, b in combinations(arr, 2) if a + b == req_sum]) if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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): return idx * 2 def right(self, idx): return idx * 2 + 1 def build(self, idx, left, right): if left == right: self.st[idx] = self.A[left] else: mid = (left + right) // 2 self.build(self.left(idx), left, mid) self.build(self.right(idx), mid + 1, right) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) def update(self, a, b, val): return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val) def update_recursive(self, idx, left, right, a, b, val): if right < a or left > b: return True if left == right: self.st[idx] = val return True mid = (left + right) // 2 self.update_recursive(self.left(idx), left, mid, a, b, val) self.update_recursive(self.right(idx), mid + 1, right, a, b, val) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) return True def query(self, a, b): return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1) def query_recursive(self, idx, left, right, a, b): if right < a or left > b: return -math.inf if left >= a and right <= b: return self.st[idx] mid = (left + right) // 2 q1 = self.query_recursive(self.left(idx), left, mid, a, b) q2 = self.query_recursive(self.right(idx), mid + 1, right, a, b) return max(q1, q2) def show_data(self): show_list = [] for i in range(1, self.N + 1): show_list += [self.query(i, i)] print(show_list) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] N = 15 segt = SegmentTree(A) print(segt.query(4, 6)) print(segt.query(7, 11)) print(segt.query(7, 12)) segt.update(1, 3, 111) print(segt.query(1, 15)) segt.update(7, 8, 235) segt.show_data()
--- +++ @@ -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 + """ return idx * 2 def right(self, idx): + """ + Returns the right child index for a given index in a binary tree. + + >>> s = SegmentTree([1, 2, 3]) + >>> s.right(1) + 3 + >>> s.right(2) + 5 + """ return idx * 2 + 1 def build(self, idx, left, right): @@ -27,9 +45,21 @@ self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) def update(self, a, b, val): + """ + Update the values in the segment tree in the range [a,b] with the given value. + + >>> s = SegmentTree([1, 2, 3, 4, 5]) + >>> s.update(2, 4, 10) + True + >>> s.query(1, 5) + 10 + """ return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val) def update_recursive(self, idx, left, right, a, b, val): + """ + update(1, 1, N, a, b, v) for update val v to [a,b] + """ if right < a or left > b: return True if left == right: @@ -42,9 +72,21 @@ return True def query(self, a, b): + """ + Query the maximum value in the range [a,b]. + + >>> s = SegmentTree([1, 2, 3, 4, 5]) + >>> s.query(1, 3) + 3 + >>> s.query(1, 5) + 5 + """ return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1) def query_recursive(self, idx, left, right, a, b): + """ + query(1, 1, N, a, b) for query max of [a,b] + """ if right < a or left > b: return -math.inf if left >= a and right <= b: @@ -71,4 +113,4 @@ segt.update(1, 3, 111) print(segt.query(1, 15)) segt.update(7, 8, 235) - segt.show_data()+ segt.show_data()
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 number of elements is odd return float(merged[total // 2]) # then return the middle element # If the total number of elements is even, calculate # the average of the two middle elements as the median. middle1 = merged[total // 2 - 1] middle2 = merged[total // 2] return (float(middle1) + float(middle2)) / 2.0 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: + The median of the two arrays. + + Examples: + >>> find_median_sorted_arrays([1, 3], [2]) + 2.0 + + >>> find_median_sorted_arrays([1, 2], [3, 4]) + 2.5 + + >>> find_median_sorted_arrays([0, 0], [0, 0]) + 0.0 + + >>> find_median_sorted_arrays([], []) + Traceback (most recent call last): + ... + ValueError: Both input arrays are empty. + + >>> find_median_sorted_arrays([], [1]) + 1.0 + + >>> find_median_sorted_arrays([-1000], [1000]) + 0.0 + + >>> find_median_sorted_arrays([-1.1, -2.2], [-3.3, -4.4]) + -2.75 + """ if not nums1 and not nums2: raise ValueError("Both input arrays are empty.") @@ -21,4 +58,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 def __iter__(self) -> Iterator[int]: yield from self.left or [] yield self.value yield from self.right or [] def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({f"{self.value}": (self.left, self.right)}, indent=1) @property def is_right(self) -> bool: return bool(self.parent and self is self.parent.right) @dataclass class BinarySearchTree: root: Node | None = None def __bool__(self) -> bool: return bool(self.root) def __iter__(self) -> Iterator[int]: yield from self.root or [] def __str__(self) -> str: return str(self.root) def __reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if node.is_right: # If it is the right child node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def empty(self) -> bool: return not self.root def __insert(self, value) -> None: new_node = Node(value) # create a new Node if self.empty(): # if Tree is empty self.root = new_node # set its root else: # Tree is not empty parent_node = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: parent_node.left = new_node # We insert the new node in a leaf break else: parent_node = parent_node.left elif parent_node.right is None: parent_node.right = new_node break else: parent_node = parent_node.right new_node.parent = parent_node def insert(self, *values) -> Self: for value in values: self.__insert(value) return self def search(self, value) -> Node | None: if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") else: node = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: node = node.left if value < node.value else node.right return node def get_max(self, node: Node | None = None) -> Node | None: if node is None: if self.root is None: return None node = self.root if not self.empty(): while node.right is not None: node = node.right return node def get_min(self, node: Node | None = None) -> Node | None: if node is None: node = self.root if self.root is None: return None if not self.empty(): node = self.root while node.left is not None: node = node.left return node def remove(self, value: int) -> None: # Look for the node with that label node = self.search(value) if node is None: msg = f"Value {value} not found" raise ValueError(msg) if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(node, None) elif node.left is None: # Has only right children self.__reassign_nodes(node, node.right) elif node.right is None: # Has only left children self.__reassign_nodes(node, node.left) else: predecessor = self.get_max( node.left ) # Gets the max value of the left branch self.remove(predecessor.value) # type: ignore[union-attr] node.value = ( predecessor.value # type: ignore[union-attr] ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node: Node | None) -> Iterable: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right) def traversal_tree(self, traversal_function=None) -> Any: if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root) def inorder(self, arr: list, node: Node | None) -> None: if node: self.inorder(arr, node.left) arr.append(node.value) self.inorder(arr, node.right) def find_kth_smallest(self, k: int, node: Node) -> int: arr: list[int] = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def inorder(curr_node: Node | None) -> list[Node]: node_list = [] if curr_node is not None: node_list = [*inorder(curr_node.left), curr_node, *inorder(curr_node.right)] return node_list def postorder(curr_node: Node | None) -> list[Node]: node_list = [] if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] return node_list if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
--- +++ @@ -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.traversal_tree())) +8 3 1 6 4 7 10 14 13 + +>>> tuple(i.value for i in t.traversal_tree(inorder)) +(1, 3, 4, 6, 7, 8, 10, 13, 14) +>>> tuple(t) +(1, 3, 4, 6, 7, 8, 10, 13, 14) +>>> t.find_kth_smallest(3, t.root) +4 +>>> tuple(t)[3-1] +4 + +>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder))) +1 4 7 6 3 13 14 10 8 +>>> t.remove(20) +Traceback (most recent call last): + ... +ValueError: Value 20 not found +>>> BinarySearchTree().search(6) +Traceback (most recent call last): + ... +IndexError: Warning: Tree is empty! please use another. + +Other example: + +>>> testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7) +>>> t = BinarySearchTree() +>>> for i in testlist: +... t.insert(i) # doctest: +ELLIPSIS +BinarySearchTree(root=8) +BinarySearchTree(root={'8': (3, None)}) +BinarySearchTree(root={'8': ({'3': (None, 6)}, None)}) +BinarySearchTree(root={'8': ({'3': (1, 6)}, None)}) +BinarySearchTree(root={'8': ({'3': (1, 6)}, 10)}) +BinarySearchTree(root={'8': ({'3': (1, 6)}, {'10': (None, 14)})}) +BinarySearchTree(root={'8': ({'3': (1, 6)}, {'10': (None, {'14': (13, None)})})}) +BinarySearchTree(root={'8': ({'3': (1, {'6': (4, None)})}, {'10': (None, {'14': ... +BinarySearchTree(root={'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, ... + +Prints all the elements of the list in order traversal +>>> print(t) +{'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, None)})})} + +Test existence +>>> t.search(6) is not None +True +>>> 6 in t +True +>>> t.search(-1) is not None +False +>>> -1 in t +False + +>>> t.search(6).is_right +True +>>> t.search(1).is_right +False + +>>> t.get_max().value +14 +>>> max(t) +14 +>>> t.get_min().value +1 +>>> min(t) +1 +>>> t.empty() +False +>>> not t +False +>>> for i in testlist: +... t.remove(i) +>>> t.empty() +True +>>> not t +True +""" from __future__ import annotations @@ -14,6 +104,12 @@ parent: Node | None = None # Added in order to delete a node easier def __iter__(self) -> Iterator[int]: + """ + >>> list(Node(0)) + [0] + >>> list(Node(0, Node(-1), Node(1), None)) + [-1, 0, 1] + """ yield from self.left or [] yield self.value yield from self.right or [] @@ -41,6 +137,9 @@ yield from self.root or [] def __str__(self) -> str: + """ + Return a string of all the Nodes using in order traversal + """ return str(self.root) def __reassign_nodes(self, node: Node, new_children: Node | None) -> None: @@ -55,9 +154,23 @@ self.root = new_children def empty(self) -> bool: + """ + Returns True if the tree does not have any element(s). + False if the tree has element(s). + + >>> BinarySearchTree().empty() + True + >>> BinarySearchTree().insert(1).empty() + False + >>> BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7).empty() + False + """ return not self.root def __insert(self, value) -> None: + """ + Insert a new node in Binary Search Tree with value label + """ new_node = Node(value) # create a new Node if self.empty(): # if Tree is empty self.root = new_node # set its root @@ -85,6 +198,29 @@ return self def search(self, value) -> Node | None: + """ + >>> tree = BinarySearchTree().insert(10, 20, 30, 40, 50) + >>> tree.search(10) + {'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})} + >>> tree.search(20) + {'20': (None, {'30': (None, {'40': (None, 50)})})} + >>> tree.search(30) + {'30': (None, {'40': (None, 50)})} + >>> tree.search(40) + {'40': (None, 50)} + >>> tree.search(50) + 50 + >>> tree.search(5) is None # element not present + True + >>> tree.search(0) is None # element not present + True + >>> tree.search(-5) is None # element not present + True + >>> BinarySearchTree().search(10) + Traceback (most recent call last): + ... + IndexError: Warning: Tree is empty! please use another. + """ if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") @@ -96,6 +232,18 @@ return node def get_max(self, node: Node | None = None) -> Node | None: + """ + We go deep on the right branch + + >>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_max() + 50 + >>> BinarySearchTree().insert(-5, -1, 0.1, -0.3, -4.5).get_max() + {'0.1': (-0.3, None)} + >>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_max() + {'78.3': ({'30': (1, 74.0)}, None)} + >>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_max() + {'783': ({'30': (1, 740)}, None)} + """ if node is None: if self.root is None: return None @@ -107,6 +255,18 @@ return node def get_min(self, node: Node | None = None) -> Node | None: + """ + We go deep on the left branch + + >>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_min() + {'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})} + >>> BinarySearchTree().insert(-5, -1, 0, -0.3, -4.5).get_min() + {'-5': (None, {'-1': (-4.5, {'0': (-0.3, None)})})} + >>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_min() + {'1': (None, {'78.3': ({'30': (1, 74.0)}, None)})} + >>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_min() + {'1': (None, {'783': ({'30': (1, 740)}, None)})} + """ if node is None: node = self.root if self.root is None: @@ -146,24 +306,34 @@ yield from self.preorder_traverse(node.right) def traversal_tree(self, traversal_function=None) -> Any: + """ + This function traversal the tree. + You can pass a function to traversal the tree as needed by client code + """ if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root) def inorder(self, arr: list, node: Node | None) -> None: + """Perform an inorder traversal and append values of the nodes to + a list named arr""" if node: self.inorder(arr, node.left) arr.append(node.value) self.inorder(arr, node.right) def find_kth_smallest(self, k: int, node: Node) -> int: + """Return the kth smallest element in a binary search tree""" arr: list[int] = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def inorder(curr_node: Node | None) -> list[Node]: + """ + inorder (left, self, right) + """ node_list = [] if curr_node is not None: node_list = [*inorder(curr_node.left), curr_node, *inorder(curr_node.right)] @@ -171,6 +341,9 @@ def postorder(curr_node: Node | None) -> list[Node]: + """ + postOrder (left, right, self) + """ node_list = [] if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] @@ -180,4 +353,4 @@ if __name__ == "__main__": import doctest - doctest.testmod(verbose=True)+ doctest.testmod(verbose=True)
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 class BinarySearchTree: def __init__(self) -> None: self.root: Node | None = None def empty(self) -> None: self.root = None def is_empty(self) -> bool: return self.root is None def put(self, label: int) -> None: self.root = self._put(self.root, label) def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node: if node is None: node = Node(label, parent) elif label < node.label: node.left = self._put(node.left, label, node) elif label > node.label: node.right = self._put(node.right, label, node) else: msg = f"Node with label {label} already exists" raise ValueError(msg) return node def search(self, label: int) -> Node: return self._search(self.root, label) def _search(self, node: Node | None, label: int) -> Node: if node is None: msg = f"Node with label {label} does not exist" raise ValueError(msg) elif label < node.label: node = self._search(node.left, label) elif label > node.label: node = self._search(node.right, label) return node def remove(self, label: int) -> None: node = self.search(label) if node.right and node.left: lowest_node = self._get_lowest_node(node.right) lowest_node.left = node.left lowest_node.right = node.right node.left.parent = lowest_node if node.right: node.right.parent = lowest_node self._reassign_nodes(node, lowest_node) elif not node.right and node.left: self._reassign_nodes(node, node.left) elif node.right and not node.left: self._reassign_nodes(node, node.right) else: self._reassign_nodes(node, None) def _reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children: new_children.parent = node.parent if node.parent: if node.parent.right == node: node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def _get_lowest_node(self, node: Node) -> Node: if node.left: lowest_node = self._get_lowest_node(node.left) else: lowest_node = node self._reassign_nodes(node, node.right) return lowest_node def exists(self, label: int) -> bool: try: self.search(label) return True except ValueError: return False def get_max_label(self) -> int: if self.root is None: raise ValueError("Binary search tree is empty") node = self.root while node.right is not None: node = node.right return node.label def get_min_label(self) -> int: if self.root is None: raise ValueError("Binary search tree is empty") node = self.root while node.left is not None: node = node.left return node.label def inorder_traversal(self) -> Iterator[Node]: return self._inorder_traversal(self.root) def _inorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield from self._inorder_traversal(node.left) yield node yield from self._inorder_traversal(node.right) def preorder_traversal(self) -> Iterator[Node]: return self._preorder_traversal(self.root) def _preorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield node yield from self._preorder_traversal(node.left) yield from self._preorder_traversal(node.right) class BinarySearchTreeTest(unittest.TestCase): @staticmethod def _get_binary_search_tree() -> BinarySearchTree: t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) return t def test_put(self) -> None: t = BinarySearchTree() assert t.is_empty() t.put(8) r""" 8 """ assert t.root is not None assert t.root.parent is None assert t.root.label == 8 t.put(10) r""" 8 \ 10 """ assert t.root.right is not None assert t.root.right.parent == t.root assert t.root.right.label == 10 t.put(3) r""" 8 / \ 3 10 """ assert t.root.left is not None assert t.root.left.parent == t.root assert t.root.left.label == 3 t.put(6) r""" 8 / \ 3 10 \ 6 """ assert t.root.left.right is not None assert t.root.left.right.parent == t.root.left assert t.root.left.right.label == 6 t.put(1) r""" 8 / \ 3 10 / \ 1 6 """ assert t.root.left.left is not None assert t.root.left.left.parent == t.root.left assert t.root.left.left.label == 1 with pytest.raises(ValueError): t.put(1) def test_search(self) -> None: t = self._get_binary_search_tree() node = t.search(6) assert node.label == 6 node = t.search(13) assert node.label == 13 with pytest.raises(ValueError): t.search(2) def test_remove(self) -> None: t = self._get_binary_search_tree() t.remove(13) r""" 8 / \ 3 10 / \ \ 1 6 14 / \ 4 7 \ 5 """ assert t.root is not None assert t.root.right is not None assert t.root.right.right is not None assert t.root.right.right.right is None assert t.root.right.right.left is None t.remove(7) r""" 8 / \ 3 10 / \ \ 1 6 14 / 4 \ 5 """ assert t.root.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is None assert t.root.left.right.left.label == 4 t.remove(6) r""" 8 / \ 3 10 / \ \ 1 4 14 \ 5 """ assert t.root.left.left is not None assert t.root.left.right.right is not None assert t.root.left.left.label == 1 assert t.root.left.right.label == 4 assert t.root.left.right.right.label == 5 assert t.root.left.right.left is None assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(3) r""" 8 / \ 4 10 / \ \ 1 5 14 """ assert t.root is not None assert t.root.left.label == 4 assert t.root.left.right.label == 5 assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(4) r""" 8 / \ 5 10 / \ 1 14 """ assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.label == 5 assert t.root.left.right is None assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left def test_remove_2(self) -> None: t = self._get_binary_search_tree() t.remove(3) r""" 8 / \ 4 10 / \ \ 1 6 14 / \ / 5 7 13 """ assert t.root is not None assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is not None assert t.root.left.label == 4 assert t.root.left.right.label == 6 assert t.root.left.left.label == 1 assert t.root.left.right.right.label == 7 assert t.root.left.right.left.label == 5 assert t.root.left.parent == t.root assert t.root.left.right.parent == t.root.left assert t.root.left.left.parent == t.root.left assert t.root.left.right.left.parent == t.root.left.right def test_empty(self) -> None: t = self._get_binary_search_tree() t.empty() assert t.root is None def test_is_empty(self) -> None: t = self._get_binary_search_tree() assert not t.is_empty() t.empty() assert t.is_empty() def test_exists(self) -> None: t = self._get_binary_search_tree() assert t.exists(6) assert not t.exists(-1) def test_get_max_label(self) -> None: t = self._get_binary_search_tree() assert t.get_max_label() == 14 t.empty() with pytest.raises(ValueError): t.get_max_label() def test_get_min_label(self) -> None: t = self._get_binary_search_tree() assert t.get_min_label() == 1 t.empty() with pytest.raises(ValueError): t.get_min_label() def test_inorder_traversal(self) -> None: t = self._get_binary_search_tree() inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] assert inorder_traversal_nodes == [1, 3, 4, 5, 6, 7, 8, 10, 13, 14] def test_preorder_traversal(self) -> None: t = self._get_binary_search_tree() preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] assert preorder_traversal_nodes == [8, 3, 1, 6, 4, 5, 7, 10, 14, 13] def binary_search_tree_example() -> None: t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) print( """ 8 / \\ 3 10 / \\ \\ 1 6 14 / \\ / 4 7 13 \\ 5 """ ) print("Label 6 exists:", t.exists(6)) print("Label 13 exists:", t.exists(13)) print("Label -1 exists:", t.exists(-1)) print("Label 12 exists:", t.exists(12)) # Prints all the elements of the list in inorder traversal inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) # Delete elements print("\nDeleting elements 13, 10, 8, 3, 6, 14") print( """ 4 / \\ 1 7 \\ 5 """ ) t.remove(13) t.remove(10) t.remove(8) t.remove(3) t.remove(6) t.remove(14) # Prints all the elements of the list in inorder traversal after delete inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal after delete:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal after delete preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal after delete:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) if __name__ == "__main__": binary_search_tree_example()
--- +++ @@ -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 | None = None def empty(self) -> None: + """ + Empties the tree + + >>> t = BinarySearchTree() + >>> assert t.root is None + >>> t.put(8) + >>> assert t.root is not None + """ self.root = None def is_empty(self) -> bool: + """ + Checks if the tree is empty + + >>> t = BinarySearchTree() + >>> t.is_empty() + True + >>> t.put(8) + >>> t.is_empty() + False + """ return self.root is None def put(self, label: int) -> None: + """ + Put a new node in the tree + + >>> t = BinarySearchTree() + >>> t.put(8) + >>> assert t.root.parent is None + >>> assert t.root.label == 8 + + >>> t.put(10) + >>> assert t.root.right.parent == t.root + >>> assert t.root.right.label == 10 + + >>> t.put(3) + >>> assert t.root.left.parent == t.root + >>> assert t.root.left.label == 3 + """ self.root = self._put(self.root, label) def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node: @@ -42,6 +85,20 @@ return node def search(self, label: int) -> Node: + """ + Searches a node in the tree + + >>> t = BinarySearchTree() + >>> t.put(8) + >>> t.put(10) + >>> node = t.search(8) + >>> assert node.label == 8 + + >>> node = t.search(3) + Traceback (most recent call last): + ... + ValueError: Node with label 3 does not exist + """ return self._search(self.root, label) def _search(self, node: Node | None, label: int) -> Node: @@ -56,6 +113,20 @@ return node def remove(self, label: int) -> None: + """ + Removes a node in the tree + + >>> t = BinarySearchTree() + >>> t.put(8) + >>> t.put(10) + >>> t.remove(8) + >>> assert t.root.label == 10 + + >>> t.remove(3) + Traceback (most recent call last): + ... + ValueError: Node with label 3 does not exist + """ node = self.search(label) if node.right and node.left: lowest_node = self._get_lowest_node(node.right) @@ -94,6 +165,18 @@ return lowest_node def exists(self, label: int) -> bool: + """ + Checks if a node exists in the tree + + >>> t = BinarySearchTree() + >>> t.put(8) + >>> t.put(10) + >>> t.exists(8) + True + + >>> t.exists(3) + False + """ try: self.search(label) return True @@ -101,6 +184,20 @@ return False def get_max_label(self) -> int: + """ + Gets the max label inserted in the tree + + >>> t = BinarySearchTree() + >>> t.get_max_label() + Traceback (most recent call last): + ... + ValueError: Binary search tree is empty + + >>> t.put(8) + >>> t.put(10) + >>> t.get_max_label() + 10 + """ if self.root is None: raise ValueError("Binary search tree is empty") @@ -111,6 +208,20 @@ return node.label def get_min_label(self) -> int: + """ + Gets the min label inserted in the tree + + >>> t = BinarySearchTree() + >>> t.get_min_label() + Traceback (most recent call last): + ... + ValueError: Binary search tree is empty + + >>> t.put(8) + >>> t.put(10) + >>> t.get_min_label() + 8 + """ if self.root is None: raise ValueError("Binary search tree is empty") @@ -121,6 +232,19 @@ return node.label def inorder_traversal(self) -> Iterator[Node]: + """ + Return the inorder traversal of the tree + + >>> t = BinarySearchTree() + >>> [i.label for i in t.inorder_traversal()] + [] + + >>> t.put(8) + >>> t.put(10) + >>> t.put(9) + >>> [i.label for i in t.inorder_traversal()] + [8, 9, 10] + """ return self._inorder_traversal(self.root) def _inorder_traversal(self, node: Node | None) -> Iterator[Node]: @@ -130,6 +254,19 @@ yield from self._inorder_traversal(node.right) def preorder_traversal(self) -> Iterator[Node]: + """ + Return the preorder traversal of the tree + + >>> t = BinarySearchTree() + >>> [i.label for i in t.preorder_traversal()] + [] + + >>> t.put(8) + >>> t.put(10) + >>> t.put(9) + >>> [i.label for i in t.preorder_traversal()] + [8, 10, 9] + """ return self._preorder_traversal(self.root) def _preorder_traversal(self, node: Node | None) -> Iterator[Node]: @@ -142,6 +279,17 @@ class BinarySearchTreeTest(unittest.TestCase): @staticmethod def _get_binary_search_tree() -> BinarySearchTree: + r""" + 8 + / \ + 3 10 + / \ \ + 1 6 14 + / \ / + 4 7 13 + \ + 5 + """ t = BinarySearchTree() t.put(8) t.put(3) @@ -396,6 +544,26 @@ def binary_search_tree_example() -> None: + r""" + Example + 8 + / \ + 3 10 + / \ \ + 1 6 14 + / \ / + 4 7 13 + \ + 5 + + Example After Deletion + 4 + / \ + 1 7 + \ + 5 + + """ t = BinarySearchTree() t.put(8) @@ -470,4 +638,4 @@ if __name__ == "__main__": - binary_search_tree_example()+ binary_search_tree_example()
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: self.tree = tree def depth_first_search(self, node: Node | None) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left) + self.depth_first_search(node.right) ) def __iter__(self) -> Iterator[int]: yield self.depth_first_search(self.tree) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 __init__(self, tree: Node) -> None: - self.tree = tree - - def depth_first_search(self, node: Node | None) -> int: - if node is None: - return 0 - return node.value + ( - self.depth_first_search(node.left) + self.depth_first_search(node.right) - ) - - def __iter__(self) -> Iterator[int]: - yield self.depth_first_search(self.tree) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +Sum of all nodes in a binary tree. + +Python implementation: + O(n) time complexity - Recurses through :meth:`depth_first_search` + with each element. + O(n) space complexity - At any point in time maximum number of stack + frames that could be in memory is `n` +""" + +from __future__ import annotations + +from collections.abc import Iterator + + +class Node: + """ + A Node has a value variable and pointers to Nodes to its left and right. + """ + + def __init__(self, value: int) -> None: + self.value = value + self.left: Node | None = None + self.right: Node | None = None + + +class BinaryTreeNodeSum: + r""" + The below tree looks like this + 10 + / \ + 5 -3 + / / \ + 12 8 0 + + >>> tree = Node(10) + >>> sum(BinaryTreeNodeSum(tree)) + 10 + + >>> tree.left = Node(5) + >>> sum(BinaryTreeNodeSum(tree)) + 15 + + >>> tree.right = Node(-3) + >>> sum(BinaryTreeNodeSum(tree)) + 12 + + >>> tree.left.left = Node(12) + >>> sum(BinaryTreeNodeSum(tree)) + 24 + + >>> tree.right.left = Node(8) + >>> tree.right.right = Node(0) + >>> sum(BinaryTreeNodeSum(tree)) + 32 + """ + + def __init__(self, tree: Node) -> None: + self.tree = tree + + def depth_first_search(self, node: Node | None) -> int: + if node is None: + return 0 + return node.value + ( + self.depth_first_search(node.left) + self.depth_first_search(node.right) + ) + + def __iter__(self) -> Iterator[int]: + yield self.depth_first_search(self.tree) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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 = find_set(x), find_set(y) if x == y: return elif x.rank > y.rank: y.parent = x else: x.parent = y if x.rank == y.rank: y.rank += 1 def find_set(x: Node) -> Node: if x != x.parent: x.parent = find_set(x.parent) return x.parent def find_python_set(node: Node) -> set: sets = ({0, 1, 2}, {3, 4, 5}) for s in sets: if node.data in s: return s msg = f"{node.data} is not in {sets}" raise ValueError(msg) def test_disjoint_set() -> None: vertex = [Node(i) for i in range(6)] for v in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0 in vertex: for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else: assert find_set(node0) == find_set(node1) if __name__ == "__main__": test_disjoint_set()
--- +++ @@ -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 union_set(x: Node, y: Node) -> None: - x, y = find_set(x), find_set(y) - if x == y: - return - - elif x.rank > y.rank: - y.parent = x - else: - x.parent = y - if x.rank == y.rank: - y.rank += 1 - - -def find_set(x: Node) -> Node: - if x != x.parent: - x.parent = find_set(x.parent) - return x.parent - - -def find_python_set(node: Node) -> set: - sets = ({0, 1, 2}, {3, 4, 5}) - for s in sets: - if node.data in s: - return s - msg = f"{node.data} is not in {sets}" - raise ValueError(msg) - - -def test_disjoint_set() -> None: - vertex = [Node(i) for i in range(6)] - for v in vertex: - make_set(v) - - union_set(vertex[0], vertex[1]) - union_set(vertex[1], vertex[2]) - union_set(vertex[3], vertex[4]) - union_set(vertex[3], vertex[5]) - - for node0 in vertex: - for node1 in vertex: - if find_python_set(node0).isdisjoint(find_python_set(node1)): - assert find_set(node0) != find_set(node1) - else: - assert find_set(node0) == find_set(node1) - - -if __name__ == "__main__": - test_disjoint_set()+""" +Disjoint set. +Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure +""" + + +class Node: + def __init__(self, data: int) -> None: + self.data = data + self.rank: int + self.parent: Node + + +def make_set(x: Node) -> None: + """ + Make x as a set. + """ + # 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: + """ + Union of two sets. + set with bigger rank should be parent, so that the + disjoint set tree will be more flat. + """ + x, y = find_set(x), find_set(y) + if x == y: + return + + elif x.rank > y.rank: + y.parent = x + else: + x.parent = y + if x.rank == y.rank: + y.rank += 1 + + +def find_set(x: Node) -> Node: + """ + Return the parent of x + """ + if x != x.parent: + x.parent = find_set(x.parent) + return x.parent + + +def find_python_set(node: Node) -> set: + """ + Return a Python Standard Library set that contains i. + """ + sets = ({0, 1, 2}, {3, 4, 5}) + for s in sets: + if node.data in s: + return s + msg = f"{node.data} is not in {sets}" + raise ValueError(msg) + + +def test_disjoint_set() -> None: + """ + >>> test_disjoint_set() + """ + vertex = [Node(i) for i in range(6)] + for v in vertex: + make_set(v) + + union_set(vertex[0], vertex[1]) + union_set(vertex[1], vertex[2]) + union_set(vertex[3], vertex[4]) + union_set(vertex[3], vertex[5]) + + for node0 in vertex: + for node1 in vertex: + if find_python_set(node0).isdisjoint(find_python_set(node1)): + assert find_set(node0) != find_set(node1) + else: + assert find_set(node0) == find_set(node1) + + +if __name__ == "__main__": + test_disjoint_set()
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: raise ValueError("Either arr or size must be specified") def init(self, arr: list[int]) -> None: self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): j = self.next_(i) if j < self.size: self.tree[j] += self.tree[i] def get_array(self) -> list[int]: arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def next_(index: int) -> int: return index + (index & (-index)) @staticmethod def prev(index: int) -> int: return index - (index & (-index)) def add(self, index: int, value: int) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value index = self.next_(index) def update(self, index: int, value: int) -> None: self.add(index, value - self.get(index)) def prefix(self, right: int) -> int: if right == 0: return 0 result = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] right = self.prev(right) return result def query(self, left: int, right: int) -> int: return self.prefix(right) - self.prefix(left) def get(self, index: int) -> int: return self.query(index, index + 1) def rank_query(self, value: int) -> int: value -= self.tree[0] if value < 0: return -1 j = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 i = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: + arr (list): list of elements to initialize the tree with (optional) + size (int): size of the Fenwick tree (if arr is None) + """ if arr is None and size is not None: self.size = size @@ -14,6 +26,23 @@ raise ValueError("Either arr or size must be specified") def init(self, arr: list[int]) -> None: + """ + Initialize the Fenwick tree with arr in O(N) + + Parameters: + arr (list): list of elements to initialize the tree with + + Returns: + None + + >>> a = [1, 2, 3, 4, 5] + >>> f1 = FenwickTree(a) + >>> f2 = FenwickTree(size=len(a)) + >>> for index, value in enumerate(a): + ... f2.add(index, value) + >>> f1.tree == f2.tree + True + """ self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): @@ -22,6 +51,17 @@ self.tree[j] += self.tree[i] def get_array(self) -> list[int]: + """ + Get the Normal Array of the Fenwick tree in O(N) + + Returns: + list: Normal Array of the Fenwick tree + + >>> a = [i for i in range(128)] + >>> f = FenwickTree(a) + >>> f.get_array() == a + True + """ arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) @@ -38,6 +78,25 @@ return index - (index & (-index)) def add(self, index: int, value: int) -> None: + """ + Add a value to index in O(lg N) + + Parameters: + index (int): index to add value to + value (int): value to add to index + + Returns: + None + + >>> f = FenwickTree([1, 2, 3, 4, 5]) + >>> f.add(0, 1) + >>> f.add(1, 2) + >>> f.add(2, 3) + >>> f.add(3, 4) + >>> f.add(4, 5) + >>> f.get_array() + [2, 4, 6, 8, 10] + """ if index == 0: self.tree[0] += value return @@ -46,9 +105,45 @@ index = self.next_(index) def update(self, index: int, value: int) -> None: + """ + Set the value of index in O(lg N) + + Parameters: + index (int): index to set value to + value (int): value to set in index + + Returns: + None + + >>> f = FenwickTree([5, 4, 3, 2, 1]) + >>> f.update(0, 1) + >>> f.update(1, 2) + >>> f.update(2, 3) + >>> f.update(3, 4) + >>> f.update(4, 5) + >>> f.get_array() + [1, 2, 3, 4, 5] + """ self.add(index, value - self.get(index)) def prefix(self, right: int) -> int: + """ + Prefix sum of all elements in [0, right) in O(lg N) + + Parameters: + right (int): right bound of the query (exclusive) + + Returns: + int: sum of all elements in [0, right) + + >>> a = [i for i in range(128)] + >>> f = FenwickTree(a) + >>> res = True + >>> for i in range(len(a)): + ... res = res and f.prefix(i) == sum(a[:i]) + >>> res + True + """ if right == 0: return 0 result = self.tree[0] @@ -59,12 +154,75 @@ return result def query(self, left: int, right: int) -> int: + """ + Query the sum of all elements in [left, right) in O(lg N) + + Parameters: + left (int): left bound of the query (inclusive) + right (int): right bound of the query (exclusive) + + Returns: + int: sum of all elements in [left, right) + + >>> a = [i for i in range(128)] + >>> f = FenwickTree(a) + >>> res = True + >>> for i in range(len(a)): + ... for j in range(i + 1, len(a)): + ... res = res and f.query(i, j) == sum(a[i:j]) + >>> res + True + """ return self.prefix(right) - self.prefix(left) def get(self, index: int) -> int: + """ + Get value at index in O(lg N) + + Parameters: + index (int): index to get the value + + Returns: + int: Value of element at index + + >>> a = [i for i in range(128)] + >>> f = FenwickTree(a) + >>> res = True + >>> for i in range(len(a)): + ... res = res and f.get(i) == a[i] + >>> res + True + """ return self.query(index, index + 1) def rank_query(self, value: int) -> int: + """ + Find the largest index with prefix(i) <= value in O(lg N) + NOTE: Requires that all values are non-negative! + + Parameters: + value (int): value to find the largest index of + + Returns: + -1: if value is smaller than all elements in prefix sum + int: largest index with prefix(i) <= value + + >>> f = FenwickTree([1, 2, 0, 3, 0, 5]) + >>> f.rank_query(0) + -1 + >>> f.rank_query(2) + 0 + >>> f.rank_query(1) + 0 + >>> f.rank_query(3) + 2 + >>> f.rank_query(5) + 2 + >>> f.rank_query(6) + 4 + >>> f.rank_query(11) + 5 + """ value -= self.tree[0] if value < 0: return -1 @@ -86,4 +244,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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))) def binary_tree_right_side_view(root: TreeNode) -> list[int]: def depth_first_search( root: TreeNode | None, depth: int, right_view: list[int] ) -> None: if not root: return if depth == len(right_view): right_view.append(root.val) depth_first_search(root.right, depth + 1, right_view) depth_first_search(root.left, depth + 1, right_view) right_view: list = [] if not root: return right_view depth_first_search(root, 0, right_view) return right_view def binary_tree_left_side_view(root: TreeNode) -> list[int]: def depth_first_search( root: TreeNode | None, depth: int, left_view: list[int] ) -> None: if not root: return if depth == len(left_view): left_view.append(root.val) depth_first_search(root.left, depth + 1, left_view) depth_first_search(root.right, depth + 1, left_view) left_view: list = [] if not root: return left_view depth_first_search(root, 0, left_view) return left_view def binary_tree_top_side_view(root: TreeNode) -> list[int]: def breadth_first_search(root: TreeNode, top_view: list[int]) -> None: queue = [(root, 0)] lookup = defaultdict(list) while queue: first = queue.pop(0) node, hd = first lookup[hd].append(node.val) if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1)) for pair in sorted(lookup.items(), key=lambda each: each[0]): top_view.append(pair[1][0]) top_view: list = [] if not root: return top_view breadth_first_search(root, top_view) return top_view def binary_tree_bottom_side_view(root: TreeNode) -> list[int]: from collections import defaultdict def breadth_first_search(root: TreeNode, bottom_view: list[int]) -> None: queue = [(root, 0)] lookup = defaultdict(list) while queue: first = queue.pop(0) node, hd = first lookup[hd].append(node.val) if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1)) for pair in sorted(lookup.items(), key=lambda each: each[0]): bottom_view.append(pair[1][-1]) bottom_view: list = [] if not root: return bottom_view breadth_first_search(root, bottom_view) return bottom_view if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: + """ + >>> make_tree().val + 3 + """ return TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7))) def binary_tree_right_side_view(root: TreeNode) -> list[int]: + r""" + Function returns the right side view of binary tree. + + 3 <- 3 + / \ + 9 20 <- 20 + / \ + 15 7 <- 7 + + >>> binary_tree_right_side_view(make_tree()) + [3, 20, 7] + >>> binary_tree_right_side_view(None) + [] + """ def depth_first_search( root: TreeNode | None, depth: int, right_view: list[int] ) -> None: + """ + A depth first search preorder traversal to append the values at + right side of tree. + """ if not root: return @@ -39,10 +68,28 @@ def binary_tree_left_side_view(root: TreeNode) -> list[int]: + r""" + Function returns the left side view of binary tree. + + 3 -> 3 + / \ + 9 -> 9 20 + / \ + 15 -> 15 7 + + >>> binary_tree_left_side_view(make_tree()) + [3, 9, 15] + >>> binary_tree_left_side_view(None) + [] + """ def depth_first_search( root: TreeNode | None, depth: int, left_view: list[int] ) -> None: + """ + A depth first search preorder traversal to append the values + at left side of tree. + """ if not root: return @@ -61,8 +108,29 @@ def binary_tree_top_side_view(root: TreeNode) -> list[int]: + r""" + Function returns the top side view of binary tree. + + 9 3 20 7 + ⬇ ⬇ ⬇ ⬇ + + 3 + / \ + 9 20 + / \ + 15 7 + + >>> binary_tree_top_side_view(make_tree()) + [9, 3, 20, 7] + >>> binary_tree_top_side_view(None) + [] + """ def breadth_first_search(root: TreeNode, top_view: list[int]) -> None: + """ + A breadth first search traversal with defaultdict ds to append + the values of tree from top view + """ queue = [(root, 0)] lookup = defaultdict(list) @@ -89,9 +157,29 @@ def binary_tree_bottom_side_view(root: TreeNode) -> list[int]: + r""" + Function returns the bottom side view of binary tree + + 3 + / \ + 9 20 + / \ + 15 7 + ↑ ↑ ↑ ↑ + 9 15 20 7 + + >>> binary_tree_bottom_side_view(make_tree()) + [9, 15, 20, 7] + >>> binary_tree_bottom_side_view(None) + [] + """ from collections import defaultdict def breadth_first_search(root: TreeNode, bottom_view: list[int]) -> None: + """ + A breadth first search traversal with defaultdict ds to append + the values of tree from bottom view + """ queue = [(root, 0)] lookup = defaultdict(list) @@ -119,4 +207,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) return tree def preorder(root: Node | None) -> Generator[int]: if not root: return yield root.data yield from preorder(root.left) yield from preorder(root.right) def postorder(root: Node | None) -> Generator[int]: if not root: return yield from postorder(root.left) yield from postorder(root.right) yield root.data def inorder(root: Node | None) -> Generator[int]: if not root: return yield from inorder(root.left) yield root.data yield from inorder(root.right) def reverse_inorder(root: Node | None) -> Generator[int]: if not root: return yield from reverse_inorder(root.right) yield root.data yield from reverse_inorder(root.left) def height(root: Node | None) -> int: return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order(root: Node | None) -> Generator[int]: if root is None: return process_queue = deque([root]) while process_queue: node = process_queue.popleft() yield node.data if node.left: process_queue.append(node.left) if node.right: process_queue.append(node.right) def get_nodes_from_left_to_right(root: Node | None, level: int) -> Generator[int]: def populate_output(root: Node | None, level: int) -> Generator[int]: if not root: return if level == 1: yield root.data elif level > 1: yield from populate_output(root.left, level - 1) yield from populate_output(root.right, level - 1) yield from populate_output(root, level) def get_nodes_from_right_to_left(root: Node | None, level: int) -> Generator[int]: def populate_output(root: Node | None, level: int) -> Generator[int]: if not root: return if level == 1: yield root.data elif level > 1: yield from populate_output(root.right, level - 1) yield from populate_output(root.left, level - 1) yield from populate_output(root, level) def zigzag(root: Node | None) -> Generator[int]: if root is None: return flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if not flag: yield from get_nodes_from_left_to_right(root, h) flag = 1 else: yield from get_nodes_from_right_to_left(root, h) flag = 0 def main() -> None: # Main function for testing. # Create binary tree. root = make_tree() # All Traversals of the binary are as follows: print(f"In-order Traversal: {list(inorder(root))}") print(f"Reverse In-order Traversal: {list(reverse_inorder(root))}") print(f"Pre-order Traversal: {list(preorder(root))}") print(f"Post-order Traversal: {list(postorder(root))}", "\n") print(f"Height of Tree: {height(root)}", "\n") print("Complete Level Order Traversal: ") print(f"{list(level_order(root))} \n") print("Level-wise order Traversal: ") for level in range(1, height(root) + 1): print(f"Level {level}:", list(get_nodes_from_left_to_right(root, level=level))) print("\nZigZag order Traversal: ") print(f"{list(zigzag(root))}") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 = None - - -def make_tree() -> Node | None: - tree = Node(1) - tree.left = Node(2) - tree.right = Node(3) - tree.left.left = Node(4) - tree.left.right = Node(5) - return tree - - -def preorder(root: Node | None) -> Generator[int]: - if not root: - return - yield root.data - yield from preorder(root.left) - yield from preorder(root.right) - - -def postorder(root: Node | None) -> Generator[int]: - if not root: - return - yield from postorder(root.left) - yield from postorder(root.right) - yield root.data - - -def inorder(root: Node | None) -> Generator[int]: - if not root: - return - yield from inorder(root.left) - yield root.data - yield from inorder(root.right) - - -def reverse_inorder(root: Node | None) -> Generator[int]: - if not root: - return - yield from reverse_inorder(root.right) - yield root.data - yield from reverse_inorder(root.left) - - -def height(root: Node | None) -> int: - return (max(height(root.left), height(root.right)) + 1) if root else 0 - - -def level_order(root: Node | None) -> Generator[int]: - - if root is None: - return - - process_queue = deque([root]) - - while process_queue: - node = process_queue.popleft() - yield node.data - - if node.left: - process_queue.append(node.left) - if node.right: - process_queue.append(node.right) - - -def get_nodes_from_left_to_right(root: Node | None, level: int) -> Generator[int]: - - def populate_output(root: Node | None, level: int) -> Generator[int]: - if not root: - return - if level == 1: - yield root.data - elif level > 1: - yield from populate_output(root.left, level - 1) - yield from populate_output(root.right, level - 1) - - yield from populate_output(root, level) - - -def get_nodes_from_right_to_left(root: Node | None, level: int) -> Generator[int]: - - def populate_output(root: Node | None, level: int) -> Generator[int]: - if not root: - return - if level == 1: - yield root.data - elif level > 1: - yield from populate_output(root.right, level - 1) - yield from populate_output(root.left, level - 1) - - yield from populate_output(root, level) - - -def zigzag(root: Node | None) -> Generator[int]: - if root is None: - return - - flag = 0 - height_tree = height(root) - - for h in range(1, height_tree + 1): - if not flag: - yield from get_nodes_from_left_to_right(root, h) - flag = 1 - else: - yield from get_nodes_from_right_to_left(root, h) - flag = 0 - - -def main() -> None: # Main function for testing. - # Create binary tree. - root = make_tree() - - # All Traversals of the binary are as follows: - print(f"In-order Traversal: {list(inorder(root))}") - print(f"Reverse In-order Traversal: {list(reverse_inorder(root))}") - print(f"Pre-order Traversal: {list(preorder(root))}") - print(f"Post-order Traversal: {list(postorder(root))}", "\n") - - print(f"Height of Tree: {height(root)}", "\n") - - print("Complete Level Order Traversal: ") - print(f"{list(level_order(root))} \n") - - print("Level-wise order Traversal: ") - - for level in range(1, height(root) + 1): - print(f"Level {level}:", list(get_nodes_from_left_to_right(root, level=level))) - - print("\nZigZag order Traversal: ") - print(f"{list(zigzag(root))}") - - -if __name__ == "__main__": - import doctest - - doctest.testmod() - main()+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: + r""" + The below tree + 1 + / \ + 2 3 + / \ + 4 5 + """ + tree = Node(1) + tree.left = Node(2) + tree.right = Node(3) + tree.left.left = Node(4) + tree.left.right = Node(5) + return tree + + +def preorder(root: Node | None) -> Generator[int]: + """ + Pre-order traversal visits root node, left subtree, right subtree. + >>> list(preorder(make_tree())) + [1, 2, 4, 5, 3] + """ + if not root: + return + yield root.data + yield from preorder(root.left) + yield from preorder(root.right) + + +def postorder(root: Node | None) -> Generator[int]: + """ + Post-order traversal visits left subtree, right subtree, root node. + >>> list(postorder(make_tree())) + [4, 5, 2, 3, 1] + """ + if not root: + return + yield from postorder(root.left) + yield from postorder(root.right) + yield root.data + + +def inorder(root: Node | None) -> Generator[int]: + """ + In-order traversal visits left subtree, root node, right subtree. + >>> list(inorder(make_tree())) + [4, 2, 5, 1, 3] + """ + if not root: + return + yield from inorder(root.left) + yield root.data + yield from inorder(root.right) + + +def reverse_inorder(root: Node | None) -> Generator[int]: + """ + Reverse in-order traversal visits right subtree, root node, left subtree. + >>> list(reverse_inorder(make_tree())) + [3, 1, 5, 2, 4] + """ + if not root: + return + yield from reverse_inorder(root.right) + yield root.data + yield from reverse_inorder(root.left) + + +def height(root: Node | None) -> int: + """ + Recursive function for calculating the height of the binary tree. + >>> height(None) + 0 + >>> height(make_tree()) + 3 + """ + return (max(height(root.left), height(root.right)) + 1) if root else 0 + + +def level_order(root: Node | None) -> Generator[int]: + """ + Returns a list of nodes value from a whole binary tree in Level Order Traverse. + Level Order traverse: Visit nodes of the tree level-by-level. + >>> list(level_order(make_tree())) + [1, 2, 3, 4, 5] + """ + + if root is None: + return + + process_queue = deque([root]) + + while process_queue: + node = process_queue.popleft() + yield node.data + + if node.left: + process_queue.append(node.left) + if node.right: + process_queue.append(node.right) + + +def get_nodes_from_left_to_right(root: Node | None, level: int) -> Generator[int]: + """ + Returns a list of nodes value from a particular level: + Left to right direction of the binary tree. + >>> list(get_nodes_from_left_to_right(make_tree(), 1)) + [1] + >>> list(get_nodes_from_left_to_right(make_tree(), 2)) + [2, 3] + """ + + def populate_output(root: Node | None, level: int) -> Generator[int]: + if not root: + return + if level == 1: + yield root.data + elif level > 1: + yield from populate_output(root.left, level - 1) + yield from populate_output(root.right, level - 1) + + yield from populate_output(root, level) + + +def get_nodes_from_right_to_left(root: Node | None, level: int) -> Generator[int]: + """ + Returns a list of nodes value from a particular level: + Right to left direction of the binary tree. + >>> list(get_nodes_from_right_to_left(make_tree(), 1)) + [1] + >>> list(get_nodes_from_right_to_left(make_tree(), 2)) + [3, 2] + """ + + def populate_output(root: Node | None, level: int) -> Generator[int]: + if not root: + return + if level == 1: + yield root.data + elif level > 1: + yield from populate_output(root.right, level - 1) + yield from populate_output(root.left, level - 1) + + yield from populate_output(root, level) + + +def zigzag(root: Node | None) -> Generator[int]: + """ + ZigZag traverse: + Returns a list of nodes value from left to right and right to left, alternatively. + >>> list(zigzag(make_tree())) + [1, 3, 2, 4, 5] + """ + if root is None: + return + + flag = 0 + height_tree = height(root) + + for h in range(1, height_tree + 1): + if not flag: + yield from get_nodes_from_left_to_right(root, h) + flag = 1 + else: + yield from get_nodes_from_right_to_left(root, h) + flag = 0 + + +def main() -> None: # Main function for testing. + # Create binary tree. + root = make_tree() + + # All Traversals of the binary are as follows: + print(f"In-order Traversal: {list(inorder(root))}") + print(f"Reverse In-order Traversal: {list(reverse_inorder(root))}") + print(f"Pre-order Traversal: {list(preorder(root))}") + print(f"Post-order Traversal: {list(postorder(root))}", "\n") + + print(f"Height of Tree: {height(root)}", "\n") + + print("Complete Level Order Traversal: ") + print(f"{list(level_order(root))} \n") + + print("Level-wise order Traversal: ") + + for level in range(1, height(root) + 1): + print(f"Level {level}:", list(get_nodes_from_left_to_right(root, level=level))) + + print("\nZigZag order Traversal: ") + print(f"{list(zigzag(root))}") + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + main()
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 return max(left_depth, right_depth) + 1 def diameter(self) -> int: left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return left_depth + right_depth + 1 if __name__ == "__main__": from doctest import testmod testmod() root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) r""" Constructed binary tree is 1 / \ 2 3 / \ 4 5 """ print(f"{root.diameter() = }") # 4 print(f"{root.left.diameter() = }") # 3 print(f"{root.right.diameter() = }") # 1
--- +++ @@ -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.depth() + 1 + >>> root.left = Node(2) + >>> root.depth() + 2 + >>> root.left.depth() + 1 + >>> root.right = Node(3) + >>> root.depth() + 2 + """ left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return max(left_depth, right_depth) + 1 def diameter(self) -> int: + """ + >>> root = Node(1) + >>> root.diameter() + 1 + >>> root.left = Node(2) + >>> root.diameter() + 2 + >>> root.left.diameter() + 1 + >>> root.right = Node(3) + >>> root.diameter() + 3 + """ left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return left_depth + right_depth + 1 @@ -40,4 +70,4 @@ """ print(f"{root.diameter() = }") # 4 print(f"{root.left.diameter() = }") # 3 - print(f"{root.right.diameter() = }") # 1+ print(f"{root.right.diameter() = }") # 1
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 = BinaryTreeNode(new_value) return node # binary search tree is not empty, # so we will insert it into the tree # if new_value is less than value of data in node, # add it to left subtree and proceed recursively if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: # if new_value is greater than value of data in node, # add it to right subtree and proceed recursively node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return if node: inorder_array = inorder(node.left_child) inorder_array = [*inorder_array, node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: # main function root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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) -> None: self.data = data @@ -9,6 +15,17 @@ def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: + """ + If the binary search tree is empty, make a new node and declare it as root. + >>> node_a = BinaryTreeNode(12345) + >>> node_b = insert(node_a, 67890) + >>> node_a.left_child == node_b.left_child + True + >>> node_a.right_child == node_b.right_child + True + >>> node_a.data == node_b.data + True + """ if node is None: node = BinaryTreeNode(new_value) return node @@ -27,6 +44,10 @@ def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return + """ + >>> inorder(make_tree()) + [6, 10, 14, 15, 20, 25, 60] + """ if node: inorder_array = inorder(node.left_child) inorder_array = [*inorder_array, node.data] @@ -58,4 +79,4 @@ import doctest doctest.testmod() - main()+ main()
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) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right.right = TreeNode(6) return root def flatten(root: TreeNode | None) -> None: if not root: return # Flatten the left subtree flatten(root.left) # Save the right subtree right_subtree = root.right # Make the left subtree the new right subtree root.right = root.left root.left = None # Find the end of the new right subtree current = root while current.right: current = current.right # Append the original right subtree to the end current.right = right_subtree # Flatten the updated right subtree flatten(right_subtree) def display_linked_list(root: TreeNode | None) -> None: current = root while current: if current.right is None: print(current.data, end="") break print(current.data, end=" ") current = current.right if __name__ == "__main__": print("Flattened Linked List:") root = build_tree() flatten(root) display_linked_list(root)
--- +++ @@ -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 flattened linked list. +https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list + +Author: Arunkumar A +Date: 04/09/2023 +""" from __future__ import annotations class TreeNode: + """ + A TreeNode has data variable and pointers to TreeNode objects + for its left and right children. + """ def __init__(self, data: int) -> None: self.data = data @@ -11,6 +27,27 @@ def build_tree() -> TreeNode: + """ + Build and return a sample binary tree. + + Returns: + TreeNode: The root of the binary tree. + + Examples: + >>> root = build_tree() + >>> root.data + 1 + >>> root.left.data + 2 + >>> root.right.data + 5 + >>> root.left.left.data + 3 + >>> root.left.right.data + 4 + >>> root.right.right.data + 6 + """ root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(5) @@ -21,6 +58,29 @@ def flatten(root: TreeNode | None) -> None: + """ + Flatten a binary tree into a linked list in-place, where the linked list is + represented using the right pointers of the tree nodes. + + Args: + root (TreeNode): The root of the binary tree to be flattened. + + Examples: + >>> root = TreeNode(1) + >>> root.left = TreeNode(2) + >>> root.right = TreeNode(5) + >>> root.left.left = TreeNode(3) + >>> root.left.right = TreeNode(4) + >>> root.right.right = TreeNode(6) + >>> flatten(root) + >>> root.data + 1 + >>> root.right.right is None + False + >>> root.right.right = TreeNode(3) + >>> root.right.right.right is None + True + """ if not root: return @@ -47,6 +107,22 @@ def display_linked_list(root: TreeNode | None) -> None: + """ + Display the flattened linked list. + + Args: + root (TreeNode | None): The root of the flattened linked list. + + Examples: + >>> root = TreeNode(1) + >>> root.right = TreeNode(2) + >>> root.right.right = TreeNode(3) + >>> display_linked_list(root) + 1 2 3 + >>> root = None + >>> display_linked_list(root) + + """ current = root while current: if current.right is None: @@ -60,4 +136,4 @@ print("Flattened Linked List:") root = build_tree() flatten(root) - display_linked_list(root)+ display_linked_list(root)
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 self.value if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def mirror(self) -> Node: self.left, self.right = self.right, self.left if self.left: self.left.mirror() if self.right: self.right.mirror() return self def make_tree_seven() -> Node: tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.right.left = Node(6) tree.right.right = Node(7) return tree def make_tree_nine() -> Node: tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.right.right = Node(6) tree.left.left.left = Node(7) tree.left.left.right = Node(8) tree.left.right.right = Node(9) return tree def main() -> None: trees = {"zero": Node(0), "seven": make_tree_seven(), "nine": make_tree_nine()} for name, tree in trees.items(): print(f" The {name} tree: {tuple(tree)}") # (0,) # (4, 2, 5, 1, 6, 3, 7) # (7, 4, 8, 2, 5, 9, 1, 3, 6) print(f"Mirror of {name} tree: {tuple(tree.mirror())}") # (0,) # (7, 3, 6, 1, 5, 2, 4) # (6, 3, 1, 9, 5, 2, 8, 4, 7) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 pointers to Nodes to its left and right. + """ value: int left: Node | None = None @@ -23,6 +31,20 @@ return sum(1 for _ in self) def mirror(self) -> Node: + """ + Mirror the binary tree rooted at this node by swapping left and right children. + + >>> tree = Node(0) + >>> list(tree) + [0] + >>> list(tree.mirror()) + [0] + >>> tree = Node(1, Node(0), Node(3, Node(2), Node(4, None, Node(5)))) + >>> tuple(tree) + (0, 1, 2, 3, 4, 5) + >>> tuple(tree.mirror()) + (5, 4, 3, 2, 1, 0) + """ self.left, self.right = self.right, self.left if self.left: self.left.mirror() @@ -32,6 +54,22 @@ def make_tree_seven() -> Node: + r""" + Return a binary tree with 7 nodes that looks like this: + :: + + 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 + + >>> tree_seven = make_tree_seven() + >>> len(tree_seven) + 7 + >>> list(tree_seven) + [4, 2, 5, 1, 6, 3, 7] + """ tree = Node(1) tree.left = Node(2) tree.right = Node(3) @@ -43,6 +81,24 @@ def make_tree_nine() -> Node: + r""" + Return a binary tree with 9 nodes that looks like this: + :: + + 1 + / \ + 2 3 + / \ \ + 4 5 6 + / \ \ + 7 8 9 + + >>> tree_nine = make_tree_nine() + >>> len(tree_nine) + 9 + >>> list(tree_nine) + [7, 4, 8, 2, 5, 9, 1, 3, 6] + """ tree = Node(1) tree.left = Node(2) tree.right = Node(3) @@ -56,6 +112,35 @@ def main() -> None: + r""" + Mirror binary trees with the given root and returns the root + + >>> tree = make_tree_nine() + >>> tuple(tree) + (7, 4, 8, 2, 5, 9, 1, 3, 6) + >>> tuple(tree.mirror()) + (6, 3, 1, 9, 5, 2, 8, 4, 7) + + nine_tree:: + + 1 + / \ + 2 3 + / \ \ + 4 5 6 + / \ \ + 7 8 9 + + The mirrored tree looks like this:: + + 1 + / \ + 3 2 + / / \ + 6 5 4 + / / \ + 9 8 7 + """ trees = {"zero": Node(0), "seven": make_tree_seven(), "nine": make_tree_nine()} for name, tree in trees.items(): print(f" The {name} tree: {tuple(tree)}") @@ -72,4 +157,4 @@ import doctest doctest.testmod() - main()+ main()
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 TypeError("Value must be an integer.") def __iter__(self) -> Iterator[TreeNode]: yield self yield from self.left or () yield from self.right or () def __len__(self) -> int: return sum(1 for _ in self) def __repr__(self) -> str: return f"{self.value},{self.left!r},{self.right!r}".replace("None", "null") @classmethod def five_tree(cls) -> TreeNode: root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.right.left = TreeNode(4) root.right.right = TreeNode(5) return root def deserialize(data: str) -> TreeNode | None: if not data: raise ValueError("Data cannot be empty.") # Split the serialized string by a comma to get node values nodes = data.split(",") def build_tree() -> TreeNode | None: # Get the next value from the list value = nodes.pop(0) if value == "null": return None node = TreeNode(int(value)) node.left = build_tree() # Recursively build left subtree node.right = build_tree() # Recursively build right subtree return node return build_tree() if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: TreeNode | None = None @@ -16,18 +24,57 @@ raise TypeError("Value must be an integer.") def __iter__(self) -> Iterator[TreeNode]: + """ + Iterate through the tree in preorder. + + Returns: + An iterator of the tree nodes. + + >>> list(TreeNode(1)) + [1,null,null] + >>> tuple(TreeNode(1, TreeNode(2), TreeNode(3))) + (1,2,null,null,3,null,null, 2,null,null, 3,null,null) + """ yield self yield from self.left or () yield from self.right or () def __len__(self) -> int: + """ + Count the number of nodes in the tree. + + Returns: + The number of nodes in the tree. + + >>> len(TreeNode(1)) + 1 + >>> len(TreeNode(1, TreeNode(2), TreeNode(3))) + 3 + """ return sum(1 for _ in self) def __repr__(self) -> str: + """ + Represent the tree as a string. + + Returns: + A string representation of the tree. + + >>> repr(TreeNode(1)) + '1,null,null' + >>> repr(TreeNode(1, TreeNode(2), TreeNode(3))) + '1,2,null,null,3,null,null' + >>> repr(TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))) + '1,2,null,null,3,4,null,null,5,null,null' + """ return f"{self.value},{self.left!r},{self.right!r}".replace("None", "null") @classmethod def five_tree(cls) -> TreeNode: + """ + >>> repr(TreeNode.five_tree()) + '1,2,null,null,3,4,null,null,5,null,null' + """ root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) @@ -37,6 +84,34 @@ def deserialize(data: str) -> TreeNode | None: + """ + Deserialize a string to a binary tree. + + Args: + data(str): The serialized string. + + Returns: + The root of the binary tree. + + >>> root = TreeNode.five_tree() + >>> serialzed_data = repr(root) + >>> deserialized = deserialize(serialzed_data) + >>> root == deserialized + True + >>> root is deserialized # two separate trees + False + >>> root.right.right.value = 6 + >>> root == deserialized + False + >>> serialzed_data = repr(root) + >>> deserialized = deserialize(serialzed_data) + >>> root == deserialized + True + >>> deserialize("") + Traceback (most recent call last): + ... + ValueError: Data cannot be empty. + """ if not data: raise ValueError("Data cannot be empty.") @@ -62,4 +137,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 def solver(node: TreeNode | None) -> tuple[bool, int, int, int]: nonlocal ans if not node: return True, INT_MAX, INT_MIN, 0 # Valid BST, min, max, sum is_left_valid, min_left, max_left, sum_left = solver(node.left) is_right_valid, min_right, max_right, sum_right = solver(node.right) if is_left_valid and is_right_valid and max_left < node.val < min_right: total_sum = sum_left + sum_right + node.val ans = max(ans, total_sum) return True, min(min_left, node.val), max(max_right, node.val), total_sum return False, -1, -1, -1 # Not a valid BST solver(root) return ans if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 found among all valid BST subtrees. + + >>> t1 = TreeNode(4) + >>> t1.left = TreeNode(3) + >>> t1.left.left = TreeNode(1) + >>> t1.left.right = TreeNode(2) + >>> print(max_sum_bst(t1)) + 2 + >>> t2 = TreeNode(-4) + >>> t2.left = TreeNode(-2) + >>> t2.right = TreeNode(-5) + >>> print(max_sum_bst(t2)) + 0 + >>> t3 = TreeNode(1) + >>> t3.left = TreeNode(4) + >>> t3.left.left = TreeNode(2) + >>> t3.left.right = TreeNode(4) + >>> t3.right = TreeNode(3) + >>> t3.right.left = TreeNode(2) + >>> t3.right.right = TreeNode(5) + >>> t3.right.right.left = TreeNode(4) + >>> t3.right.right.right = TreeNode(6) + >>> print(max_sum_bst(t3)) + 20 + """ ans: int = 0 def solver(node: TreeNode | None) -> tuple[bool, int, int, int]: + """ + Returns the maximum sum by making recursive calls + >>> t1 = TreeNode(1) + >>> print(solver(t1)) + 1 + """ nonlocal ans if not node: @@ -40,4 +75,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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_type for _ in range(self.N)] + arr self.fn = fnc self.build() def build(self) -> None: for p in range(self.N - 1, 0, -1): self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def update(self, p: int, v: T) -> None: p += self.N self.st[p] = v while p > 1: p = p // 2 self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def query(self, left: int, right: int) -> T | None: left, right = left + self.N, right + self.N res: T | None = None while left <= right: if left % 2 == 1: res = self.st[left] if res is None else self.fn(res, self.st[left]) if right % 2 == 0: res = self.st[right] if res is None else self.fn(res, self.st[right]) left, right = (left + 1) // 2, (right - 1) // 2 return res if __name__ == "__main__": from functools import reduce test_array = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] test_updates = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } min_segment_tree = SegmentTree(test_array, min) max_segment_tree = SegmentTree(test_array, max) sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b) def test_all_segments() -> None: for i in range(len(test_array)): for j in range(i, len(test_array)): min_range = reduce(min, test_array[i : j + 1]) max_range = reduce(max, test_array[i : j + 1]) sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1]) assert min_range == min_segment_tree.query(i, j) assert max_range == max_segment_tree.query(i, j) assert sum_range == sum_segment_tree.query(i, j) test_all_segments() for index, value in test_updates.items(): test_array[index] = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
--- +++ @@ -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.geeksforgeeks.org/segment-tree-efficient-implementation/ + +>>> SegmentTree([1, 2, 3], lambda a, b: a + b).query(0, 2) +6 +>>> SegmentTree([3, 1, 2], min).query(0, 2) +1 +>>> SegmentTree([2, 3, 1], max).query(0, 2) +3 +>>> st = SegmentTree([1, 5, 7, -1, 6], lambda a, b: a + b) +>>> st.update(1, -1) +>>> st.update(2, 3) +>>> st.query(1, 2) +2 +>>> st.query(1, 1) +-1 +>>> st.update(4, 1) +>>> st.query(3, 4) +0 +>>> st = SegmentTree([[1, 2, 3], [3, 2, 1], [1, 1, 1]], lambda a, b: [a[i] + b[i] for i +... in range(len(a))]) +>>> st.query(0, 1) +[4, 4, 4] +>>> st.query(1, 2) +[4, 3, 2] +>>> st.update(1, [-1, -1, -1]) +>>> st.query(1, 2) +[0, 0, 0] +>>> st.query(0, 2) +[1, 2, 3] +""" from __future__ import annotations @@ -9,6 +46,17 @@ class SegmentTree[T]: def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None: + """ + Segment Tree constructor, it works just with commutative combiner. + :param arr: list of elements for the segment tree + :param fnc: commutative function for combine two elements + + >>> SegmentTree(['a', 'b', 'c'], lambda a, b: f'{a}{b}').query(0, 2) + 'abc' + >>> SegmentTree([(1, 2), (2, 3), (3, 4)], + ... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2) + (6, 9) + """ any_type: Any | T = None self.N: int = len(arr) @@ -21,6 +69,18 @@ self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def update(self, p: int, v: T) -> None: + """ + Update an element in log(N) time + :param p: position to be update + :param v: new value + + >>> st = SegmentTree([3, 1, 2, 4], min) + >>> st.query(0, 3) + 1 + >>> st.update(2, -1) + >>> st.query(0, 3) + -1 + """ p += self.N self.st[p] = v while p > 1: @@ -28,6 +88,22 @@ self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def query(self, left: int, right: int) -> T | None: + """ + Get range query value in log(N) time + :param left: left element index + :param right: right element index + :return: element combined in the range [left, right] + + >>> st = SegmentTree([1, 2, 3, 4], lambda a, b: a + b) + >>> st.query(0, 2) + 6 + >>> st.query(1, 2) + 5 + >>> st.query(0, 3) + 10 + >>> st.query(2, 3) + 7 + """ left, right = left + self.N, right + self.N res: T | None = None @@ -65,6 +141,9 @@ sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b) def test_all_segments() -> None: + """ + Test all possible segments + """ for i in range(len(test_array)): for j in range(i, len(test_array)): min_range = reduce(min, test_array[i : j + 1]) @@ -81,4 +160,4 @@ min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) - test_all_segments()+ test_all_segments()
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 self.lazy = [0 for i in range(4 * size)] self.flag = [0 for i in range(4 * size)] # flag for lazy update def left(self, idx: int) -> int: return idx * 2 def right(self, idx: int) -> int: return idx * 2 + 1 def build( self, idx: int, left_element: int, right_element: int, a: list[int] ) -> None: if left_element == right_element: self.segment_tree[idx] = a[left_element - 1] else: mid = (left_element + right_element) // 2 self.build(self.left(idx), left_element, mid, a) self.build(self.right(idx), mid + 1, right_element, a) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: self.segment_tree[idx] = val if left_element != right_element: self.lazy[self.left(idx)] = val self.lazy[self.right(idx)] = val self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True return True mid = (left_element + right_element) // 2 self.update(self.left(idx), left_element, mid, a, b, val) self.update(self.right(idx), mid + 1, right_element, a, b, val) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) return True # query with O(lg n) def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> int | float: if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] mid = (left_element + right_element) // 2 q1 = self.query(self.left(idx), left_element, mid, a, b) q2 = self.query(self.right(idx), mid + 1, right_element, a, b) return max(q1, q2) def __str__(self) -> str: return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)]) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] size = 15 segt = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
--- +++ @@ -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) + 24 + """ return idx * 2 def right(self, idx: int) -> int: + """ + >>> segment_tree = SegmentTree(15) + >>> segment_tree.right(1) + 3 + >>> segment_tree.right(2) + 5 + >>> segment_tree.right(12) + 25 + """ return idx * 2 + 1 def build( @@ -34,6 +52,12 @@ def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: + """ + update with O(lg n) (Normal segment tree without lazy update will take O(nlg n) + for each update) + + update(1, 1, size, a, b, v) for update val v to [a,b] + """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False @@ -65,6 +89,18 @@ def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> int | float: + """ + query(1, 1, size, a, b) for query max of [a,b] + >>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] + >>> segment_tree = SegmentTree(15) + >>> segment_tree.build(1, 1, 15, A) + >>> segment_tree.query(1, 1, 15, 4, 6) + 7 + >>> segment_tree.query(1, 1, 15, 7, 11) + 14 + >>> segment_tree.query(1, 1, 15, 7, 12) + 15 + """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False @@ -97,4 +133,4 @@ segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) - print(segt)+ print(segt)
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_coefficient(n: int, k: int) -> int: result = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) k = min(k, n - k) # Calculate C(n,k) for i in range(k): result *= n - i result //= i + 1 return result def catalan_number(node_count: int) -> int: return binomial_coefficient(2 * node_count, node_count) // (node_count + 1) def factorial(n: int) -> int: if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result def binary_tree_count(node_count: int) -> int: return catalan_number(node_count) * factorial(node_count) if __name__ == "__main__": node_count = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( f"Given {node_count} nodes, there are {binary_tree_count(node_count)} " f"binary trees and {catalan_number(node_count)} binary search trees." )
--- +++ @@ -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.wikipedia.org/wiki/Catalan_number +""" """ Our Contribution: @@ -10,6 +18,17 @@ def binomial_coefficient(n: int, k: int) -> int: + """ + Since Here we Find the Binomial Coefficient: + https://en.wikipedia.org/wiki/Binomial_coefficient + C(n,k) = n! / k!(n-k)! + :param n: 2 times of Number of nodes + :param k: Number of nodes + :return: Integer Value + + >>> binomial_coefficient(4, 2) + 6 + """ result = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) k = min(k, n - k) @@ -21,10 +40,36 @@ def catalan_number(node_count: int) -> int: + """ + We can find Catalan number many ways but here we use Binomial Coefficient because it + does the job in O(n) + + return the Catalan number of n using 2nCn/(n+1). + :param n: number of nodes + :return: Catalan number of n nodes + + >>> catalan_number(5) + 42 + >>> catalan_number(6) + 132 + """ return binomial_coefficient(2 * node_count, node_count) // (node_count + 1) def factorial(n: int) -> int: + """ + Return the factorial of a number. + :param n: Number to find the Factorial of. + :return: Factorial of n. + + >>> import math + >>> all(factorial(i) == math.factorial(i) for i in range(10)) + True + >>> factorial(-5) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: factorial() not defined for negative values + """ if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 @@ -34,6 +79,16 @@ def binary_tree_count(node_count: int) -> int: + """ + Return the number of possible of binary trees. + :param n: number of nodes + :return: Number of possible binary trees + + >>> binary_tree_count(5) + 5040 + >>> binary_tree_count(6) + 95040 + """ return catalan_number(node_count) * factorial(node_count) @@ -44,4 +99,4 @@ print( f"Given {node_count} nodes, there are {binary_tree_count(node_count)} " f"binary trees and {catalan_number(node_count)} binary search trees." - )+ )
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 heap. self.size = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. self.key = key or (lambda x: x) def _parent(self, i: int) -> int | None: return int((i - 1) / 2) if i > 0 else None def _left(self, i: int) -> int | None: left = int(2 * i + 1) return left if 0 < left < self.size else None def _right(self, i: int) -> int | None: right = int(2 * i + 2) return right if 0 < right < self.size else None def _swap(self, i: int, j: int) -> None: # First update the indexes of the items in index map. self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. self.arr[i], self.arr[j] = self.arr[j], self.arr[i] def _cmp(self, i: int, j: int) -> bool: return self.arr[i][1] < self.arr[j][1] def _get_valid_parent(self, i: int) -> int: left = self._left(i) right = self._right(i) valid_parent = i if left is not None and not self._cmp(left, valid_parent): valid_parent = left if right is not None and not self._cmp(right, valid_parent): valid_parent = right return valid_parent def _heapify_up(self, index: int) -> None: parent = self._parent(index) while parent is not None and not self._cmp(index, parent): self._swap(index, parent) index, parent = parent, self._parent(parent) def _heapify_down(self, index: int) -> None: valid_parent = self._get_valid_parent(index) while valid_parent != index: self._swap(index, valid_parent) index, valid_parent = valid_parent, self._get_valid_parent(valid_parent) def update_item(self, item: int, item_value: int) -> None: if item not in self.pos_map: return index = self.pos_map[item] self.arr[index] = [item, self.key(item_value)] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(index) self._heapify_down(index) def delete_item(self, item: int) -> None: if item not in self.pos_map: return index = self.pos_map[item] del self.pos_map[item] self.arr[index] = self.arr[self.size - 1] self.pos_map[self.arr[self.size - 1][0]] = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(index) self._heapify_down(index) def insert_item(self, item: int, item_value: int) -> None: arr_len = len(self.arr) if arr_len == self.size: self.arr.append([item, self.key(item_value)]) else: self.arr[self.size] = [item, self.key(item_value)] self.pos_map[item] = self.size self.size += 1 self._heapify_up(self.size - 1) def get_top(self) -> tuple | None: return self.arr[0] if self.size else None def extract_top(self) -> tuple | None: top_item_tuple = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0]) return top_item_tuple def test_heap() -> None: if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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) def _parent(self, i: int) -> int | None: + """Returns parent index of given index if exists else None""" return int((i - 1) / 2) if i > 0 else None def _left(self, i: int) -> int | None: + """Returns left-child-index of given index if exists else None""" left = int(2 * i + 1) return left if 0 < left < self.size else None def _right(self, i: int) -> int | None: + """Returns right-child-index of given index if exists else None""" right = int(2 * i + 2) return right if 0 < right < self.size else None def _swap(self, i: int, j: int) -> None: + """Performs changes required for swapping two elements in the heap""" # First update the indexes of the items in index map. self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = ( self.pos_map[self.arr[j][0]], @@ -35,9 +43,14 @@ self.arr[i], self.arr[j] = self.arr[j], self.arr[i] def _cmp(self, i: int, j: int) -> bool: + """Compares the two items using default comparison""" return self.arr[i][1] < self.arr[j][1] def _get_valid_parent(self, i: int) -> int: + """ + Returns index of valid parent as per desired ordering among given index and + both it's children + """ left = self._left(i) right = self._right(i) valid_parent = i @@ -50,18 +63,21 @@ return valid_parent def _heapify_up(self, index: int) -> None: + """Fixes the heap in upward direction of given index""" parent = self._parent(index) while parent is not None and not self._cmp(index, parent): self._swap(index, parent) index, parent = parent, self._parent(parent) def _heapify_down(self, index: int) -> None: + """Fixes the heap in downward direction of given index""" valid_parent = self._get_valid_parent(index) while valid_parent != index: self._swap(index, valid_parent) index, valid_parent = valid_parent, self._get_valid_parent(valid_parent) def update_item(self, item: int, item_value: int) -> None: + """Updates given item value in heap if present""" if item not in self.pos_map: return index = self.pos_map[item] @@ -72,6 +88,7 @@ self._heapify_down(index) def delete_item(self, item: int) -> None: + """Deletes given item from heap if present""" if item not in self.pos_map: return index = self.pos_map[item] @@ -86,6 +103,7 @@ self._heapify_down(index) def insert_item(self, item: int, item_value: int) -> None: + """Inserts given item with given value in heap""" arr_len = len(self.arr) if arr_len == self.size: self.arr.append([item, self.key(item_value)]) @@ -96,9 +114,14 @@ self._heapify_up(self.size - 1) def get_top(self) -> tuple | None: + """Returns top item tuple (Calculated value, item) from heap if present""" return self.arr[0] if self.size else None def extract_top(self) -> tuple | None: + """ + Return top item tuple (Calculated value, item) from heap and removes it as well + if present + """ top_item_tuple = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0]) @@ -106,9 +129,46 @@ def test_heap() -> None: + """ + >>> h = Heap() # Max-heap + >>> h.insert_item(5, 34) + >>> h.insert_item(6, 31) + >>> h.insert_item(7, 37) + >>> h.get_top() + [7, 37] + >>> h.extract_top() + [7, 37] + >>> h.extract_top() + [5, 34] + >>> h.extract_top() + [6, 31] + >>> h = Heap(key=lambda x: -x) # Min heap + >>> h.insert_item(5, 34) + >>> h.insert_item(6, 31) + >>> h.insert_item(7, 37) + >>> h.get_top() + [6, -31] + >>> h.extract_top() + [6, -31] + >>> h.extract_top() + [5, -34] + >>> h.extract_top() + [7, -37] + >>> h.insert_item(8, 45) + >>> h.insert_item(9, 40) + >>> h.insert_item(10, 50) + >>> h.get_top() + [9, -40] + >>> h.update_item(10, 30) + >>> h.get_top() + [10, -30] + >>> h.delete_item(10) + >>> h.get_top() + [9, -40] + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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.key if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def floor_ceiling(root: Node | None, key: int) -> tuple[int | None, int | None]: floor_val = None ceiling_val = None while root: if root.key == key: floor_val = root.key ceiling_val = root.key break if key < root.key: ceiling_val = root.key root = root.left else: floor_val = root.key root = root.right return floor_val, ceiling_val if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 +""" from __future__ import annotations @@ -23,6 +34,35 @@ def floor_ceiling(root: Node | None, key: int) -> tuple[int | None, int | None]: + """ + Find the floor and ceiling values for a given key in a Binary Search Tree (BST). + + Args: + root: The root of the binary search tree. + key: The key for which to find the floor and ceiling. + + Returns: + A tuple containing the floor and ceiling values, respectively. + + Examples: + >>> root = Node(10) + >>> root.left = Node(5) + >>> root.right = Node(20) + >>> root.left.left = Node(3) + >>> root.left.right = Node(7) + >>> root.right.left = Node(15) + >>> root.right.right = Node(25) + >>> tuple(root) + (3, 5, 7, 10, 15, 20, 25) + >>> floor_ceiling(root, 8) + (7, 10) + >>> floor_ceiling(root, 14) + (10, 15) + >>> floor_ceiling(root, -1) + (None, 3) + >>> floor_ceiling(root, 30) + (25, None) + """ floor_val = None ceiling_val = None @@ -45,4 +85,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 pformat if self.left is None and self.right is None: return f"'{self.value}: {self.prior:.5}'" else: return pformat( {f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1 ) def __str__(self) -> str: value = str(self.value) + " " left = str(self.left or "") right = str(self.right or "") return value + left + right def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]: if root is None or root.value is None: # None tree is split into 2 Nones return None, None elif value < root.value: """ Right tree's root will be current node. Now we split(with the same value) current node's left son Left tree: left part of that split Right tree's left son: right part of that split """ left, root.left = split(root.left, value) return left, root else: """ Just symmetric to previous case """ root.right, right = split(root.right, value) return root, right def merge(left: Node | None, right: Node | None) -> Node | None: if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: """ Left will be root because it has more priority Now we need to merge left's right son and right tree """ left.right = merge(left.right, right) return left else: """ Symmetric as well """ right.left = merge(left, right.left) return right def insert(root: Node | None, value: int) -> Node | None: node = Node(value) left, right = split(root, value) return merge(merge(left, node), right) def erase(root: Node | None, value: int) -> Node | None: left, right = split(root, value - 1) _, right = split(right, value) return merge(left, right) def inorder(root: Node | None) -> None: if not root: # None return else: inorder(root.left) print(root.value, end=",") inorder(root.right) def interact_treap(root: Node | None, args: str) -> Node | None: for arg in args.split(): if arg[0] == "+": root = insert(root, int(arg[1:])) elif arg[0] == "-": root = erase(root, int(arg[1:])) else: print("Unknown command") return root def main() -> None: root = None print( "enter numbers to create a tree, + value to add value into treap, " "- value to erase all nodes with value. 'q' to quit. " ) args = input() while args != "q": root = interact_treap(root, args) print(root) args = input() print("good by!") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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]: + """ + We split current tree into 2 trees with value: + + Left tree contains all values less than split value. + Right tree contains all values greater or equal, than split value + """ if root is None or root.value is None: # None tree is split into 2 Nones return None, None elif value < root.value: @@ -49,6 +59,10 @@ def merge(left: Node | None, right: Node | None) -> Node | None: + """ + We merge 2 trees into one. + Note: all left tree's values must be less than all right tree's + """ if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: @@ -67,18 +81,35 @@ def insert(root: Node | None, value: int) -> Node | None: + """ + Insert element + + Split current tree with a value into left, right, + Insert new node into the middle + Merge left, node, right into root + """ node = Node(value) left, right = split(root, value) return merge(merge(left, node), right) def erase(root: Node | None, value: int) -> Node | None: + """ + Erase element + + Split all nodes with values less into left, + Split all nodes with values greater into right. + Merge left, right + """ left, right = split(root, value - 1) _, right = split(right, value) return merge(left, right) def inorder(root: Node | None) -> None: + """ + Just recursive print of a tree + """ if not root: # None return else: @@ -88,6 +119,29 @@ def interact_treap(root: Node | None, args: str) -> Node | None: + """ + Commands: + + value to add value into treap + - value to erase all nodes with value + + >>> root = interact_treap(None, "+1") + >>> inorder(root) + 1, + >>> root = interact_treap(root, "+3 +5 +17 +19 +2 +16 +4 +0") + >>> inorder(root) + 0,1,2,3,4,5,16,17,19, + >>> root = interact_treap(root, "+4 +4 +4") + >>> inorder(root) + 0,1,2,3,4,4,4,4,5,16,17,19, + >>> root = interact_treap(root, "-0") + >>> inorder(root) + 1,2,3,4,4,4,4,5,16,17,19, + >>> root = interact_treap(root, "-4") + >>> inorder(root) + 1,2,3,5,16,17,19, + >>> root = interact_treap(root, "=0") + Unknown command + """ for arg in args.split(): if arg[0] == "+": root = insert(root, int(arg[1:])) @@ -102,6 +156,7 @@ def main() -> None: + """After each command, program prints treap""" root = None print( "enter numbers to create a tree, + value to add value into treap, " @@ -121,4 +176,4 @@ import doctest doctest.testmod() - main()+ main()
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, ) -> None: self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> RedBlackTree: parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() elif self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None # The node is black elif child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) elif self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> bool: if self.color == 1 and 1 in (color(self.left), color(self.right)): return False if self.left and not self.left.check_coloring(): return False return not (self.right and not self.right.check_coloring()) def black_height(self) -> int | None: if self is None or self.left is None or self.right is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label: int) -> bool: return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) elif self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int | None: if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: if self.parent is None: return False return self.parent.left is self def is_right(self) -> bool: if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) return tree == right_rot def test_insertion_speed() -> bool: tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if any(i in tree for i in (5, -6, -10, 13)): # Found something not in there return False # Find all these things in there return all(i in tree for i in (11, 12, -8, 0)) def test_insert_delete() -> bool: tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False return list(tree.inorder_traverse()) == [-8, 0, 4, 8, 10, 11, 12] def test_floor_ceil() -> bool: tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) return not (tree.get_max() != 22 or tree.get_min() != -16) def test_tree_traversal() -> bool: tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0] def test_tree_chaining() -> bool: tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0] def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
--- +++ @@ -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, - right: RedBlackTree | None = None, - ) -> None: - self.label = label - self.parent = parent - self.left = left - self.right = right - self.color = color - - # Here are functions which are specific to red-black trees - - def rotate_left(self) -> RedBlackTree: - parent = self.parent - right = self.right - if right is None: - return self - self.right = right.left - if self.right: - self.right.parent = self - self.parent = right - right.left = self - if parent is not None: - if parent.left == self: - parent.left = right - else: - parent.right = right - right.parent = parent - return right - - def rotate_right(self) -> RedBlackTree: - if self.left is None: - return self - parent = self.parent - left = self.left - self.left = left.right - if self.left: - self.left.parent = self - self.parent = left - left.right = self - if parent is not None: - if parent.right is self: - parent.right = left - else: - parent.left = left - left.parent = parent - return left - - def insert(self, label: int) -> RedBlackTree: - if self.label is None: - # Only possible with an empty tree - self.label = label - return self - if self.label == label: - return self - elif self.label > label: - if self.left: - self.left.insert(label) - else: - self.left = RedBlackTree(label, 1, self) - self.left._insert_repair() - elif self.right: - self.right.insert(label) - else: - self.right = RedBlackTree(label, 1, self) - self.right._insert_repair() - return self.parent or self - - def _insert_repair(self) -> None: - if self.parent is None: - # This node is the root, so it just needs to be black - self.color = 0 - elif color(self.parent) == 0: - # If the parent is black, then it just needs to be red - self.color = 1 - else: - uncle = self.parent.sibling - if color(uncle) == 0: - if self.is_left() and self.parent.is_right(): - self.parent.rotate_right() - if self.right: - self.right._insert_repair() - elif self.is_right() and self.parent.is_left(): - self.parent.rotate_left() - if self.left: - self.left._insert_repair() - elif self.is_left(): - if self.grandparent: - self.grandparent.rotate_right() - self.parent.color = 0 - if self.parent.right: - self.parent.right.color = 1 - else: - if self.grandparent: - self.grandparent.rotate_left() - self.parent.color = 0 - if self.parent.left: - self.parent.left.color = 1 - else: - self.parent.color = 0 - if uncle and self.grandparent: - uncle.color = 0 - self.grandparent.color = 1 - self.grandparent._insert_repair() - - def remove(self, label: int) -> RedBlackTree: - if self.label == label: - if self.left and self.right: - # It's easier to balance a node with at most one child, - # so we replace this node with the greatest one less than - # it and remove that. - value = self.left.get_max() - if value is not None: - self.label = value - self.left.remove(value) - else: - # This node has at most one non-None child, so we don't - # need to replace - child = self.left or self.right - if self.color == 1: - # This node is red, and its child is black - # The only way this happens to a node with one child - # is if both children are None leaves. - # We can just remove this node and call it a day. - if self.parent: - if self.is_left(): - self.parent.left = None - else: - self.parent.right = None - # The node is black - elif child is None: - # This node and its child are black - if self.parent is None: - # The tree is now empty - return RedBlackTree(None) - else: - self._remove_repair() - if self.is_left(): - self.parent.left = None - else: - self.parent.right = None - self.parent = None - else: - # This node is black and its child is red - # Move the child node here and make it black - self.label = child.label - self.left = child.left - self.right = child.right - if self.left: - self.left.parent = self - if self.right: - self.right.parent = self - elif self.label is not None and self.label > label: - if self.left: - self.left.remove(label) - elif self.right: - self.right.remove(label) - return self.parent or self - - def _remove_repair(self) -> None: - if ( - self.parent is None - or self.sibling is None - or self.parent.sibling is None - or self.grandparent is None - ): - return - if color(self.sibling) == 1: - self.sibling.color = 0 - self.parent.color = 1 - if self.is_left(): - self.parent.rotate_left() - else: - self.parent.rotate_right() - if ( - color(self.parent) == 0 - and color(self.sibling) == 0 - and color(self.sibling.left) == 0 - and color(self.sibling.right) == 0 - ): - self.sibling.color = 1 - self.parent._remove_repair() - return - if ( - color(self.parent) == 1 - and color(self.sibling) == 0 - and color(self.sibling.left) == 0 - and color(self.sibling.right) == 0 - ): - self.sibling.color = 1 - self.parent.color = 0 - return - if ( - self.is_left() - and color(self.sibling) == 0 - and color(self.sibling.right) == 0 - and color(self.sibling.left) == 1 - ): - self.sibling.rotate_right() - self.sibling.color = 0 - if self.sibling.right: - self.sibling.right.color = 1 - if ( - self.is_right() - and color(self.sibling) == 0 - and color(self.sibling.right) == 1 - and color(self.sibling.left) == 0 - ): - self.sibling.rotate_left() - self.sibling.color = 0 - if self.sibling.left: - self.sibling.left.color = 1 - if ( - self.is_left() - and color(self.sibling) == 0 - and color(self.sibling.right) == 1 - ): - self.parent.rotate_left() - self.grandparent.color = self.parent.color - self.parent.color = 0 - self.parent.sibling.color = 0 - if ( - self.is_right() - and color(self.sibling) == 0 - and color(self.sibling.left) == 1 - ): - self.parent.rotate_right() - self.grandparent.color = self.parent.color - self.parent.color = 0 - self.parent.sibling.color = 0 - - def check_color_properties(self) -> bool: - # I assume property 1 to hold because there is nothing that can - # make the color be anything other than 0 or 1. - # Property 2 - if self.color: - # The root was red - print("Property 2") - return False - # Property 3 does not need to be checked, because None is assumed - # to be black and is all the leaves. - # Property 4 - if not self.check_coloring(): - print("Property 4") - return False - # Property 5 - if self.black_height() is None: - print("Property 5") - return False - # All properties were met - return True - - def check_coloring(self) -> bool: - if self.color == 1 and 1 in (color(self.left), color(self.right)): - return False - if self.left and not self.left.check_coloring(): - return False - return not (self.right and not self.right.check_coloring()) - - def black_height(self) -> int | None: - if self is None or self.left is None or self.right is None: - # If we're already at a leaf, there is no path - return 1 - left = RedBlackTree.black_height(self.left) - right = RedBlackTree.black_height(self.right) - if left is None or right is None: - # There are issues with coloring below children nodes - return None - if left != right: - # The two children have unequal depths - return None - # Return the black depth of children, plus one if this node is - # black - return left + (1 - self.color) - - # Here are functions which are general to all binary search trees - - def __contains__(self, label: int) -> bool: - return self.search(label) is not None - - def search(self, label: int) -> RedBlackTree | None: - if self.label == label: - return self - elif self.label is not None and label > self.label: - if self.right is None: - return None - else: - return self.right.search(label) - elif self.left is None: - return None - else: - return self.left.search(label) - - def floor(self, label: int) -> int | None: - if self.label == label: - return self.label - elif self.label is not None and self.label > label: - if self.left: - return self.left.floor(label) - else: - return None - else: - if self.right: - attempt = self.right.floor(label) - if attempt is not None: - return attempt - return self.label - - def ceil(self, label: int) -> int | None: - if self.label == label: - return self.label - elif self.label is not None and self.label < label: - if self.right: - return self.right.ceil(label) - else: - return None - else: - if self.left: - attempt = self.left.ceil(label) - if attempt is not None: - return attempt - return self.label - - def get_max(self) -> int | None: - if self.right: - # Go as far right as possible - return self.right.get_max() - else: - return self.label - - def get_min(self) -> int | None: - if self.left: - # Go as far left as possible - return self.left.get_min() - else: - return self.label - - @property - def grandparent(self) -> RedBlackTree | None: - if self.parent is None: - return None - else: - return self.parent.parent - - @property - def sibling(self) -> RedBlackTree | None: - if self.parent is None: - return None - elif self.parent.left is self: - return self.parent.right - else: - return self.parent.left - - def is_left(self) -> bool: - if self.parent is None: - return False - return self.parent.left is self - - def is_right(self) -> bool: - if self.parent is None: - return False - return self.parent.right is self - - def __bool__(self) -> bool: - return True - - def __len__(self) -> int: - ln = 1 - if self.left: - ln += len(self.left) - if self.right: - ln += len(self.right) - return ln - - def preorder_traverse(self) -> Iterator[int | None]: - yield self.label - if self.left: - yield from self.left.preorder_traverse() - if self.right: - yield from self.right.preorder_traverse() - - def inorder_traverse(self) -> Iterator[int | None]: - if self.left: - yield from self.left.inorder_traverse() - yield self.label - if self.right: - yield from self.right.inorder_traverse() - - def postorder_traverse(self) -> Iterator[int | None]: - if self.left: - yield from self.left.postorder_traverse() - if self.right: - yield from self.right.postorder_traverse() - yield self.label - - def __repr__(self) -> str: - from pprint import pformat - - if self.left is None and self.right is None: - return f"'{self.label} {(self.color and 'red') or 'blk'}'" - return pformat( - { - f"{self.label} {(self.color and 'red') or 'blk'}": ( - self.left, - self.right, - ) - }, - indent=1, - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, RedBlackTree): - return NotImplemented - if self.label == other.label: - return self.left == other.left and self.right == other.right - else: - return False - - -def color(node: RedBlackTree | None) -> int: - if node is None: - return 0 - else: - return node.color - - -""" -Code for testing the various -functions of the red-black tree. -""" - - -def test_rotations() -> bool: - # Make a tree to test on - tree = RedBlackTree(0) - tree.left = RedBlackTree(-10, parent=tree) - tree.right = RedBlackTree(10, parent=tree) - tree.left.left = RedBlackTree(-20, parent=tree.left) - tree.left.right = RedBlackTree(-5, parent=tree.left) - tree.right.left = RedBlackTree(5, parent=tree.right) - tree.right.right = RedBlackTree(20, parent=tree.right) - # Make the right rotation - left_rot = RedBlackTree(10) - left_rot.left = RedBlackTree(0, parent=left_rot) - left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) - left_rot.left.right = RedBlackTree(5, parent=left_rot.left) - left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) - left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) - left_rot.right = RedBlackTree(20, parent=left_rot) - tree = tree.rotate_left() - if tree != left_rot: - return False - tree = tree.rotate_right() - tree = tree.rotate_right() - # Make the left rotation - right_rot = RedBlackTree(-10) - right_rot.left = RedBlackTree(-20, parent=right_rot) - right_rot.right = RedBlackTree(0, parent=right_rot) - right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) - right_rot.right.right = RedBlackTree(10, parent=right_rot.right) - right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) - right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) - return tree == right_rot - - -def test_insertion_speed() -> bool: - tree = RedBlackTree(-1) - for i in range(300000): - tree = tree.insert(i) - return True - - -def test_insert() -> bool: - tree = RedBlackTree(0) - tree.insert(8) - tree.insert(-8) - tree.insert(4) - tree.insert(12) - tree.insert(10) - tree.insert(11) - ans = RedBlackTree(0, 0) - ans.left = RedBlackTree(-8, 0, ans) - ans.right = RedBlackTree(8, 1, ans) - ans.right.left = RedBlackTree(4, 0, ans.right) - ans.right.right = RedBlackTree(11, 0, ans.right) - ans.right.right.left = RedBlackTree(10, 1, ans.right.right) - ans.right.right.right = RedBlackTree(12, 1, ans.right.right) - return tree == ans - - -def test_insert_and_search() -> bool: - tree = RedBlackTree(0) - tree.insert(8) - tree.insert(-8) - tree.insert(4) - tree.insert(12) - tree.insert(10) - tree.insert(11) - if any(i in tree for i in (5, -6, -10, 13)): - # Found something not in there - return False - # Find all these things in there - return all(i in tree for i in (11, 12, -8, 0)) - - -def test_insert_delete() -> bool: - tree = RedBlackTree(0) - tree = tree.insert(-12) - tree = tree.insert(8) - tree = tree.insert(-8) - tree = tree.insert(15) - tree = tree.insert(4) - tree = tree.insert(12) - tree = tree.insert(10) - tree = tree.insert(9) - tree = tree.insert(11) - tree = tree.remove(15) - tree = tree.remove(-12) - tree = tree.remove(9) - if not tree.check_color_properties(): - return False - return list(tree.inorder_traverse()) == [-8, 0, 4, 8, 10, 11, 12] - - -def test_floor_ceil() -> bool: - tree = RedBlackTree(0) - tree.insert(-16) - tree.insert(16) - tree.insert(8) - tree.insert(24) - tree.insert(20) - tree.insert(22) - tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] - for val, floor, ceil in tuples: - if tree.floor(val) != floor or tree.ceil(val) != ceil: - return False - return True - - -def test_min_max() -> bool: - tree = RedBlackTree(0) - tree.insert(-16) - tree.insert(16) - tree.insert(8) - tree.insert(24) - tree.insert(20) - tree.insert(22) - return not (tree.get_max() != 22 or tree.get_min() != -16) - - -def test_tree_traversal() -> bool: - tree = RedBlackTree(0) - tree = tree.insert(-16) - tree.insert(16) - tree.insert(8) - tree.insert(24) - tree.insert(20) - tree.insert(22) - if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: - return False - if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: - return False - return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0] - - -def test_tree_chaining() -> bool: - tree = RedBlackTree(0) - tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) - if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: - return False - if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: - return False - return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0] - - -def print_results(msg: str, passes: bool) -> None: - print(str(msg), "works!" if passes else "doesn't work :(") - - -def pytests() -> None: - assert test_rotations() - assert test_insert() - assert test_insert_and_search() - assert test_insert_delete() - assert test_floor_ceil() - assert test_tree_traversal() - assert test_tree_chaining() - - -def main() -> None: - print_results("Rotating right and left", test_rotations()) - print_results("Inserting", test_insert()) - print_results("Searching", test_insert_and_search()) - print_results("Deleting", test_insert_delete()) - print_results("Floor and ceil", test_floor_ceil()) - print_results("Tree traversal", test_tree_traversal()) - print_results("Tree traversal", test_tree_chaining()) - print("Testing tree balancing...") - print("This should only be a few seconds.") - test_insertion_speed() - print("Done!") - - -if __name__ == "__main__": - main()+from __future__ import annotations + +from collections.abc import Iterator + + +class RedBlackTree: + """ + A Red-Black tree, which is a self-balancing BST (binary search + tree). + This tree has similar performance to AVL trees, but the balancing is + less strict, so it will perform faster for writing/deleting nodes + and slower for reading in the average case, though, because they're + both balanced binary search trees, both will get the same asymptotic + performance. + To read more about them, https://en.wikipedia.org/wiki/Red-black_tree + Unless otherwise specified, all asymptotic runtimes are specified in + terms of the size of the tree. + """ + + def __init__( + self, + label: int | None = None, + color: int = 0, + parent: RedBlackTree | None = None, + left: RedBlackTree | None = None, + right: RedBlackTree | None = None, + ) -> None: + """Initialize a new Red-Black Tree node with the given values: + label: The value associated with this node + color: 0 if black, 1 if red + parent: The parent to this node + left: This node's left child + right: This node's right child + """ + self.label = label + self.parent = parent + self.left = left + self.right = right + self.color = color + + # Here are functions which are specific to red-black trees + + def rotate_left(self) -> RedBlackTree: + """Rotate the subtree rooted at this node to the left and + returns the new root to this subtree. + Performing one rotation can be done in O(1). + """ + parent = self.parent + right = self.right + if right is None: + return self + self.right = right.left + if self.right: + self.right.parent = self + self.parent = right + right.left = self + if parent is not None: + if parent.left == self: + parent.left = right + else: + parent.right = right + right.parent = parent + return right + + def rotate_right(self) -> RedBlackTree: + """Rotate the subtree rooted at this node to the right and + returns the new root to this subtree. + Performing one rotation can be done in O(1). + """ + if self.left is None: + return self + parent = self.parent + left = self.left + self.left = left.right + if self.left: + self.left.parent = self + self.parent = left + left.right = self + if parent is not None: + if parent.right is self: + parent.right = left + else: + parent.left = left + left.parent = parent + return left + + def insert(self, label: int) -> RedBlackTree: + """Inserts label into the subtree rooted at self, performs any + rotations necessary to maintain balance, and then returns the + new root to this subtree (likely self). + This is guaranteed to run in O(log(n)) time. + """ + if self.label is None: + # Only possible with an empty tree + self.label = label + return self + if self.label == label: + return self + elif self.label > label: + if self.left: + self.left.insert(label) + else: + self.left = RedBlackTree(label, 1, self) + self.left._insert_repair() + elif self.right: + self.right.insert(label) + else: + self.right = RedBlackTree(label, 1, self) + self.right._insert_repair() + return self.parent or self + + def _insert_repair(self) -> None: + """Repair the coloring from inserting into a tree.""" + if self.parent is None: + # This node is the root, so it just needs to be black + self.color = 0 + elif color(self.parent) == 0: + # If the parent is black, then it just needs to be red + self.color = 1 + else: + uncle = self.parent.sibling + if color(uncle) == 0: + if self.is_left() and self.parent.is_right(): + self.parent.rotate_right() + if self.right: + self.right._insert_repair() + elif self.is_right() and self.parent.is_left(): + self.parent.rotate_left() + if self.left: + self.left._insert_repair() + elif self.is_left(): + if self.grandparent: + self.grandparent.rotate_right() + self.parent.color = 0 + if self.parent.right: + self.parent.right.color = 1 + else: + if self.grandparent: + self.grandparent.rotate_left() + self.parent.color = 0 + if self.parent.left: + self.parent.left.color = 1 + else: + self.parent.color = 0 + if uncle and self.grandparent: + uncle.color = 0 + self.grandparent.color = 1 + self.grandparent._insert_repair() + + def remove(self, label: int) -> RedBlackTree: + """Remove label from this tree.""" + if self.label == label: + if self.left and self.right: + # It's easier to balance a node with at most one child, + # so we replace this node with the greatest one less than + # it and remove that. + value = self.left.get_max() + if value is not None: + self.label = value + self.left.remove(value) + else: + # This node has at most one non-None child, so we don't + # need to replace + child = self.left or self.right + if self.color == 1: + # This node is red, and its child is black + # The only way this happens to a node with one child + # is if both children are None leaves. + # We can just remove this node and call it a day. + if self.parent: + if self.is_left(): + self.parent.left = None + else: + self.parent.right = None + # The node is black + elif child is None: + # This node and its child are black + if self.parent is None: + # The tree is now empty + return RedBlackTree(None) + else: + self._remove_repair() + if self.is_left(): + self.parent.left = None + else: + self.parent.right = None + self.parent = None + else: + # This node is black and its child is red + # Move the child node here and make it black + self.label = child.label + self.left = child.left + self.right = child.right + if self.left: + self.left.parent = self + if self.right: + self.right.parent = self + elif self.label is not None and self.label > label: + if self.left: + self.left.remove(label) + elif self.right: + self.right.remove(label) + return self.parent or self + + def _remove_repair(self) -> None: + """Repair the coloring of the tree that may have been messed up.""" + if ( + self.parent is None + or self.sibling is None + or self.parent.sibling is None + or self.grandparent is None + ): + return + if color(self.sibling) == 1: + self.sibling.color = 0 + self.parent.color = 1 + if self.is_left(): + self.parent.rotate_left() + else: + self.parent.rotate_right() + if ( + color(self.parent) == 0 + and color(self.sibling) == 0 + and color(self.sibling.left) == 0 + and color(self.sibling.right) == 0 + ): + self.sibling.color = 1 + self.parent._remove_repair() + return + if ( + color(self.parent) == 1 + and color(self.sibling) == 0 + and color(self.sibling.left) == 0 + and color(self.sibling.right) == 0 + ): + self.sibling.color = 1 + self.parent.color = 0 + return + if ( + self.is_left() + and color(self.sibling) == 0 + and color(self.sibling.right) == 0 + and color(self.sibling.left) == 1 + ): + self.sibling.rotate_right() + self.sibling.color = 0 + if self.sibling.right: + self.sibling.right.color = 1 + if ( + self.is_right() + and color(self.sibling) == 0 + and color(self.sibling.right) == 1 + and color(self.sibling.left) == 0 + ): + self.sibling.rotate_left() + self.sibling.color = 0 + if self.sibling.left: + self.sibling.left.color = 1 + if ( + self.is_left() + and color(self.sibling) == 0 + and color(self.sibling.right) == 1 + ): + self.parent.rotate_left() + self.grandparent.color = self.parent.color + self.parent.color = 0 + self.parent.sibling.color = 0 + if ( + self.is_right() + and color(self.sibling) == 0 + and color(self.sibling.left) == 1 + ): + self.parent.rotate_right() + self.grandparent.color = self.parent.color + self.parent.color = 0 + self.parent.sibling.color = 0 + + def check_color_properties(self) -> bool: + """Check the coloring of the tree, and return True iff the tree + is colored in a way which matches these five properties: + (wording stolen from wikipedia article) + 1. Each node is either red or black. + 2. The root node is black. + 3. All leaves are black. + 4. If a node is red, then both its children are black. + 5. Every path from any node to all of its descendent NIL nodes + has the same number of black nodes. + This function runs in O(n) time, because properties 4 and 5 take + that long to check. + """ + # I assume property 1 to hold because there is nothing that can + # make the color be anything other than 0 or 1. + # Property 2 + if self.color: + # The root was red + print("Property 2") + return False + # Property 3 does not need to be checked, because None is assumed + # to be black and is all the leaves. + # Property 4 + if not self.check_coloring(): + print("Property 4") + return False + # Property 5 + if self.black_height() is None: + print("Property 5") + return False + # All properties were met + return True + + def check_coloring(self) -> bool: + """A helper function to recursively check Property 4 of a + Red-Black Tree. See check_color_properties for more info. + """ + if self.color == 1 and 1 in (color(self.left), color(self.right)): + return False + if self.left and not self.left.check_coloring(): + return False + return not (self.right and not self.right.check_coloring()) + + def black_height(self) -> int | None: + """Returns the number of black nodes from this node to the + leaves of the tree, or None if there isn't one such value (the + tree is color incorrectly). + """ + if self is None or self.left is None or self.right is None: + # If we're already at a leaf, there is no path + return 1 + left = RedBlackTree.black_height(self.left) + right = RedBlackTree.black_height(self.right) + if left is None or right is None: + # There are issues with coloring below children nodes + return None + if left != right: + # The two children have unequal depths + return None + # Return the black depth of children, plus one if this node is + # black + return left + (1 - self.color) + + # Here are functions which are general to all binary search trees + + def __contains__(self, label: int) -> bool: + """Search through the tree for label, returning True iff it is + found somewhere in the tree. + Guaranteed to run in O(log(n)) time. + """ + return self.search(label) is not None + + def search(self, label: int) -> RedBlackTree | None: + """Search through the tree for label, returning its node if + it's found, and None otherwise. + This method is guaranteed to run in O(log(n)) time. + """ + if self.label == label: + return self + elif self.label is not None and label > self.label: + if self.right is None: + return None + else: + return self.right.search(label) + elif self.left is None: + return None + else: + return self.left.search(label) + + def floor(self, label: int) -> int | None: + """Returns the largest element in this tree which is at most label. + This method is guaranteed to run in O(log(n)) time.""" + if self.label == label: + return self.label + elif self.label is not None and self.label > label: + if self.left: + return self.left.floor(label) + else: + return None + else: + if self.right: + attempt = self.right.floor(label) + if attempt is not None: + return attempt + return self.label + + def ceil(self, label: int) -> int | None: + """Returns the smallest element in this tree which is at least label. + This method is guaranteed to run in O(log(n)) time. + """ + if self.label == label: + return self.label + elif self.label is not None and self.label < label: + if self.right: + return self.right.ceil(label) + else: + return None + else: + if self.left: + attempt = self.left.ceil(label) + if attempt is not None: + return attempt + return self.label + + def get_max(self) -> int | None: + """Returns the largest element in this tree. + This method is guaranteed to run in O(log(n)) time. + """ + if self.right: + # Go as far right as possible + return self.right.get_max() + else: + return self.label + + def get_min(self) -> int | None: + """Returns the smallest element in this tree. + This method is guaranteed to run in O(log(n)) time. + """ + if self.left: + # Go as far left as possible + return self.left.get_min() + else: + return self.label + + @property + def grandparent(self) -> RedBlackTree | None: + """Get the current node's grandparent, or None if it doesn't exist.""" + if self.parent is None: + return None + else: + return self.parent.parent + + @property + def sibling(self) -> RedBlackTree | None: + """Get the current node's sibling, or None if it doesn't exist.""" + if self.parent is None: + return None + elif self.parent.left is self: + return self.parent.right + else: + return self.parent.left + + def is_left(self) -> bool: + """Returns true iff this node is the left child of its parent.""" + if self.parent is None: + return False + return self.parent.left is self + + def is_right(self) -> bool: + """Returns true iff this node is the right child of its parent.""" + if self.parent is None: + return False + return self.parent.right is self + + def __bool__(self) -> bool: + return True + + def __len__(self) -> int: + """ + Return the number of nodes in this tree. + """ + ln = 1 + if self.left: + ln += len(self.left) + if self.right: + ln += len(self.right) + return ln + + def preorder_traverse(self) -> Iterator[int | None]: + yield self.label + if self.left: + yield from self.left.preorder_traverse() + if self.right: + yield from self.right.preorder_traverse() + + def inorder_traverse(self) -> Iterator[int | None]: + if self.left: + yield from self.left.inorder_traverse() + yield self.label + if self.right: + yield from self.right.inorder_traverse() + + def postorder_traverse(self) -> Iterator[int | None]: + if self.left: + yield from self.left.postorder_traverse() + if self.right: + yield from self.right.postorder_traverse() + yield self.label + + def __repr__(self) -> str: + from pprint import pformat + + if self.left is None and self.right is None: + return f"'{self.label} {(self.color and 'red') or 'blk'}'" + return pformat( + { + f"{self.label} {(self.color and 'red') or 'blk'}": ( + self.left, + self.right, + ) + }, + indent=1, + ) + + def __eq__(self, other: object) -> bool: + """Test if two trees are equal.""" + if not isinstance(other, RedBlackTree): + return NotImplemented + if self.label == other.label: + return self.left == other.left and self.right == other.right + else: + return False + + +def color(node: RedBlackTree | None) -> int: + """Returns the color of a node, allowing for None leaves.""" + if node is None: + return 0 + else: + return node.color + + +""" +Code for testing the various +functions of the red-black tree. +""" + + +def test_rotations() -> bool: + """Test that the rotate_left and rotate_right functions work.""" + # Make a tree to test on + tree = RedBlackTree(0) + tree.left = RedBlackTree(-10, parent=tree) + tree.right = RedBlackTree(10, parent=tree) + tree.left.left = RedBlackTree(-20, parent=tree.left) + tree.left.right = RedBlackTree(-5, parent=tree.left) + tree.right.left = RedBlackTree(5, parent=tree.right) + tree.right.right = RedBlackTree(20, parent=tree.right) + # Make the right rotation + left_rot = RedBlackTree(10) + left_rot.left = RedBlackTree(0, parent=left_rot) + left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) + left_rot.left.right = RedBlackTree(5, parent=left_rot.left) + left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) + left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) + left_rot.right = RedBlackTree(20, parent=left_rot) + tree = tree.rotate_left() + if tree != left_rot: + return False + tree = tree.rotate_right() + tree = tree.rotate_right() + # Make the left rotation + right_rot = RedBlackTree(-10) + right_rot.left = RedBlackTree(-20, parent=right_rot) + right_rot.right = RedBlackTree(0, parent=right_rot) + right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) + right_rot.right.right = RedBlackTree(10, parent=right_rot.right) + right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) + right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) + return tree == right_rot + + +def test_insertion_speed() -> bool: + """Test that the tree balances inserts to O(log(n)) by doing a lot + of them. + """ + tree = RedBlackTree(-1) + for i in range(300000): + tree = tree.insert(i) + return True + + +def test_insert() -> bool: + """Test the insert() method of the tree correctly balances, colors, + and inserts. + """ + tree = RedBlackTree(0) + tree.insert(8) + tree.insert(-8) + tree.insert(4) + tree.insert(12) + tree.insert(10) + tree.insert(11) + ans = RedBlackTree(0, 0) + ans.left = RedBlackTree(-8, 0, ans) + ans.right = RedBlackTree(8, 1, ans) + ans.right.left = RedBlackTree(4, 0, ans.right) + ans.right.right = RedBlackTree(11, 0, ans.right) + ans.right.right.left = RedBlackTree(10, 1, ans.right.right) + ans.right.right.right = RedBlackTree(12, 1, ans.right.right) + return tree == ans + + +def test_insert_and_search() -> bool: + """Tests searching through the tree for values.""" + tree = RedBlackTree(0) + tree.insert(8) + tree.insert(-8) + tree.insert(4) + tree.insert(12) + tree.insert(10) + tree.insert(11) + if any(i in tree for i in (5, -6, -10, 13)): + # Found something not in there + return False + # Find all these things in there + return all(i in tree for i in (11, 12, -8, 0)) + + +def test_insert_delete() -> bool: + """Test the insert() and delete() method of the tree, verifying the + insertion and removal of elements, and the balancing of the tree. + """ + tree = RedBlackTree(0) + tree = tree.insert(-12) + tree = tree.insert(8) + tree = tree.insert(-8) + tree = tree.insert(15) + tree = tree.insert(4) + tree = tree.insert(12) + tree = tree.insert(10) + tree = tree.insert(9) + tree = tree.insert(11) + tree = tree.remove(15) + tree = tree.remove(-12) + tree = tree.remove(9) + if not tree.check_color_properties(): + return False + return list(tree.inorder_traverse()) == [-8, 0, 4, 8, 10, 11, 12] + + +def test_floor_ceil() -> bool: + """Tests the floor and ceiling functions in the tree.""" + tree = RedBlackTree(0) + tree.insert(-16) + tree.insert(16) + tree.insert(8) + tree.insert(24) + tree.insert(20) + tree.insert(22) + tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] + for val, floor, ceil in tuples: + if tree.floor(val) != floor or tree.ceil(val) != ceil: + return False + return True + + +def test_min_max() -> bool: + """Tests the min and max functions in the tree.""" + tree = RedBlackTree(0) + tree.insert(-16) + tree.insert(16) + tree.insert(8) + tree.insert(24) + tree.insert(20) + tree.insert(22) + return not (tree.get_max() != 22 or tree.get_min() != -16) + + +def test_tree_traversal() -> bool: + """Tests the three different tree traversal functions.""" + tree = RedBlackTree(0) + tree = tree.insert(-16) + tree.insert(16) + tree.insert(8) + tree.insert(24) + tree.insert(20) + tree.insert(22) + if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: + return False + if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: + return False + return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0] + + +def test_tree_chaining() -> bool: + """Tests the three different tree chaining functions.""" + tree = RedBlackTree(0) + tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) + if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: + return False + if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: + return False + return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0] + + +def print_results(msg: str, passes: bool) -> None: + print(str(msg), "works!" if passes else "doesn't work :(") + + +def pytests() -> None: + assert test_rotations() + assert test_insert() + assert test_insert_and_search() + assert test_insert_delete() + assert test_floor_ceil() + assert test_tree_traversal() + assert test_tree_chaining() + + +def main() -> None: + """ + >>> pytests() + """ + print_results("Rotating right and left", test_rotations()) + print_results("Inserting", test_insert()) + print_results("Searching", test_insert_and_search()) + print_results("Deleting", test_insert_delete()) + print_results("Floor and ceil", test_floor_ceil()) + print_results("Tree traversal", test_tree_traversal()) + print_results("Tree traversal", test_tree_chaining()) + print("Testing tree balancing...") + print("This should only be a few seconds.") + test_insertion_speed() + print("Done!") + + +if __name__ == "__main__": + main()
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 tree1 is None: return tree2 if tree2 is None: return tree1 tree1.value = tree1.value + tree2.value tree1.left = merge_two_binary_trees(tree1.left, tree2.left) tree1.right = merge_two_binary_trees(tree1.right, tree2.right) return tree1 def print_preorder(root: Node | None) -> None: if root: print(root.value) print_preorder(root.left) print_preorder(root.right) if __name__ == "__main__": tree1 = Node(1) tree1.left = Node(2) tree1.right = Node(3) tree1.left.left = Node(4) tree2 = Node(2) tree2.left = Node(4) tree2.right = Node(6) tree2.left.right = Node(9) tree2.right.right = Node(5) print("Tree1 is: ") print_preorder(tree1) print("Tree2 is: ") print_preorder(tree2) merged_tree = merge_two_binary_trees(tree1, tree2) print("Merged Tree is: ") print_preorder(merged_tree)
--- +++ @@ -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. +""" from __future__ import annotations class Node: + """ + A binary node has value variable and pointers to its left and right node. + """ def __init__(self, value: int = 0) -> None: self.value = value @@ -12,6 +21,27 @@ def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node | None: + """ + Returns root node of the merged tree. + + >>> tree1 = Node(5) + >>> tree1.left = Node(6) + >>> tree1.right = Node(7) + >>> tree1.left.left = Node(2) + >>> tree2 = Node(4) + >>> tree2.left = Node(5) + >>> tree2.right = Node(8) + >>> tree2.left.right = Node(1) + >>> tree2.right.right = Node(4) + >>> merged_tree = merge_two_binary_trees(tree1, tree2) + >>> print_preorder(merged_tree) + 9 + 11 + 2 + 1 + 15 + 4 + """ if tree1 is None: return tree2 if tree2 is None: @@ -24,6 +54,19 @@ def print_preorder(root: Node | None) -> None: + """ + Print pre-order traversal of the tree. + + >>> root = Node(1) + >>> root.left = Node(2) + >>> root.right = Node(3) + >>> print_preorder(root) + 1 + 2 + 3 + >>> print_preorder(root.right) + 3 + """ if root: print(root.value) print_preorder(root.left) @@ -48,4 +91,4 @@ print_preorder(tree2) merged_tree = merge_two_binary_trees(tree1, tree2) print("Merged Tree is: ") - print_preorder(merged_tree)+ print_preorder(merged_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 def __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class SegmentTree: def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): self._update_tree(self.root, i, val) def query_range(self, i, j): return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
--- +++ @@ -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: + """ + >>> import operator + >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) + >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE + (SegmentTreeNode(start=0, end=4, val=15), + SegmentTreeNode(start=0, end=2, val=8), + SegmentTreeNode(start=3, end=4, val=7), + SegmentTreeNode(start=0, end=1, val=3), + SegmentTreeNode(start=2, end=2, val=5), + SegmentTreeNode(start=3, end=3, val=3), + SegmentTreeNode(start=4, end=4, val=4), + SegmentTreeNode(start=0, end=0, val=2), + SegmentTreeNode(start=1, end=1, val=1)) + >>> + >>> num_arr.update(1, 5) + >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE + (SegmentTreeNode(start=0, end=4, val=19), + SegmentTreeNode(start=0, end=2, val=12), + SegmentTreeNode(start=3, end=4, val=7), + SegmentTreeNode(start=0, end=1, val=7), + SegmentTreeNode(start=2, end=2, val=5), + SegmentTreeNode(start=3, end=3, val=3), + SegmentTreeNode(start=4, end=4, val=4), + SegmentTreeNode(start=0, end=0, val=2), + SegmentTreeNode(start=1, end=1, val=5)) + >>> + >>> num_arr.query_range(3, 4) + 7 + >>> num_arr.query_range(2, 2) + 5 + >>> num_arr.query_range(1, 3) + 13 + >>> + >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) + >>> for node in max_arr.traverse(): + ... print(node) + ... + SegmentTreeNode(start=0, end=4, val=5) + SegmentTreeNode(start=0, end=2, val=5) + SegmentTreeNode(start=3, end=4, val=4) + SegmentTreeNode(start=0, end=1, val=2) + SegmentTreeNode(start=2, end=2, val=5) + SegmentTreeNode(start=3, end=3, val=3) + SegmentTreeNode(start=4, end=4, val=4) + SegmentTreeNode(start=0, end=0, val=2) + SegmentTreeNode(start=1, end=1, val=1) + >>> + >>> max_arr.update(1, 5) + >>> for node in max_arr.traverse(): + ... print(node) + ... + SegmentTreeNode(start=0, end=4, val=5) + SegmentTreeNode(start=0, end=2, val=5) + SegmentTreeNode(start=3, end=4, val=4) + SegmentTreeNode(start=0, end=1, val=5) + SegmentTreeNode(start=2, end=2, val=5) + SegmentTreeNode(start=3, end=3, val=3) + SegmentTreeNode(start=4, end=4, val=4) + SegmentTreeNode(start=0, end=0, val=2) + SegmentTreeNode(start=1, end=1, val=5) + >>> + >>> max_arr.query_range(3, 4) + 4 + >>> max_arr.query_range(2, 2) + 5 + >>> max_arr.query_range(1, 3) + 5 + >>> + >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) + >>> for node in min_arr.traverse(): + ... print(node) + ... + SegmentTreeNode(start=0, end=4, val=1) + SegmentTreeNode(start=0, end=2, val=1) + SegmentTreeNode(start=3, end=4, val=3) + SegmentTreeNode(start=0, end=1, val=1) + SegmentTreeNode(start=2, end=2, val=5) + SegmentTreeNode(start=3, end=3, val=3) + SegmentTreeNode(start=4, end=4, val=4) + SegmentTreeNode(start=0, end=0, val=2) + SegmentTreeNode(start=1, end=1, val=1) + >>> + >>> min_arr.update(1, 5) + >>> for node in min_arr.traverse(): + ... print(node) + ... + SegmentTreeNode(start=0, end=4, val=2) + SegmentTreeNode(start=0, end=2, val=2) + SegmentTreeNode(start=3, end=4, val=3) + SegmentTreeNode(start=0, end=1, val=2) + SegmentTreeNode(start=2, end=2, val=5) + SegmentTreeNode(start=3, end=3, val=3) + SegmentTreeNode(start=4, end=4, val=4) + SegmentTreeNode(start=0, end=0, val=2) + SegmentTreeNode(start=1, end=1, val=5) + >>> + >>> min_arr.query_range(3, 4) + 3 + >>> min_arr.query_range(2, 2) + 5 + >>> min_arr.query_range(1, 3) + 3 + >>> + """ def __init__(self, collection: Sequence, function): self.collection = collection @@ -25,9 +134,35 @@ self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): + """ + Update an element in log(N) time + :param i: position to be update + :param val: new value + >>> import operator + >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) + >>> num_arr.update(1, 5) + >>> num_arr.query_range(1, 3) + 13 + """ self._update_tree(self.root, i, val) def query_range(self, i, j): + """ + Get range query value in log(N) time + :param i: left element index + :param j: right element index + :return: element combined in the range [i, j] + >>> import operator + >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) + >>> num_arr.update(1, 5) + >>> num_arr.query_range(3, 4) + 7 + >>> num_arr.query_range(2, 2) + 5 + >>> num_arr.query_range(1, 3) + 13 + >>> + """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): @@ -99,4 +234,4 @@ print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 - print()+ print()
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[int]]) -> list[list[int]]: j = 1 while (1 << j) < max_node: for i in range(1, max_node + 1): parent[j][i] = parent[j - 1][parent[j - 1][i]] j += 1 return parent # returns lca of node u,v def lowest_common_ancestor( u: int, v: int, level: list[int], parent: list[list[int]] ) -> int: # u must be deeper in the tree than v if level[u] < level[v]: u, v = swap(u, v) # making depth of u same as depth of v for i in range(18, -1, -1): if level[u] - (1 << i) >= level[v]: u = parent[i][u] # at the same depth if u==v that mean lca is found if u == v: return u # moving both nodes upwards till lca in found for i in range(18, -1, -1): if parent[i][u] not in [0, parent[i][v]]: u, v = parent[i][u], parent[i][v] # returning longest common ancestor of u,v return parent[0][u] # runs a breadth first search from root node of the tree def breadth_first_search( level: list[int], parent: list[list[int]], max_node: int, graph: dict[int, list[int]], root: int = 1, ) -> tuple[list[int], list[list[int]]]: level[root] = 0 q: Queue[int] = Queue(maxsize=max_node) q.put(root) while q.qsize() != 0: u = q.get() for v in graph[u]: if level[v] == -1: level[v] = level[u] + 1 q.put(v) parent[0][v] = u return level, parent def main() -> None: max_node = 13 # initializing with 0 parent = [[0 for _ in range(max_node + 10)] for _ in range(20)] # initializing with -1 which means every node is unvisited level = [-1 for _ in range(max_node + 10)] graph: dict[int, list[int]] = { 1: [2, 3, 4], 2: [5], 3: [6, 7], 4: [8], 5: [9, 10], 6: [11], 7: [], 8: [12, 13], 9: [], 10: [], 11: [], 12: [], 13: [], } level, parent = breadth_first_search(level, parent, max_node, graph, 1) parent = create_sparse(max_node, parent) print("LCA of node 1 and 3 is: ", lowest_common_ancestor(1, 3, level, parent)) print("LCA of node 5 and 6 is: ", lowest_common_ancestor(5, 6, level, parent)) print("LCA of node 7 and 11 is: ", lowest_common_ancestor(7, 11, level, parent)) print("LCA of node 6 and 7 is: ", lowest_common_ancestor(6, 7, level, parent)) print("LCA of node 4 and 12 is: ", lowest_common_ancestor(4, 12, level, parent)) print("LCA of node 8 and 8 is: ", lowest_common_ancestor(8, 8, level, parent)) if __name__ == "__main__": main()
--- +++ @@ -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 @@ -14,6 +25,26 @@ def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]: + """ + creating sparse table which saves each nodes 2^i-th parent + >>> max_node = 6 + >>> parent = [[0, 0, 1, 1, 2, 2, 3]] + [[0] * 7 for _ in range(19)] + >>> parent = create_sparse(max_node=max_node, parent=parent) + >>> parent[0] + [0, 0, 1, 1, 2, 2, 3] + >>> parent[1] + [0, 0, 0, 0, 1, 1, 1] + >>> parent[2] + [0, 0, 0, 0, 0, 0, 0] + + >>> max_node = 1 + >>> parent = [[0, 0]] + [[0] * 2 for _ in range(19)] + >>> parent = create_sparse(max_node=max_node, parent=parent) + >>> parent[0] + [0, 0] + >>> parent[1] + [0, 0] + """ j = 1 while (1 << j) < max_node: for i in range(1, max_node + 1): @@ -26,6 +57,21 @@ def lowest_common_ancestor( u: int, v: int, level: list[int], parent: list[list[int]] ) -> int: + """ + Return the lowest common ancestor between u and v + + >>> level = [-1, 0, 1, 1, 2, 2, 2] + >>> parent = [[0, 0, 1, 1, 2, 2, 3],[0, 0, 0, 0, 1, 1, 1]] + \ + [[0] * 7 for _ in range(17)] + >>> lowest_common_ancestor(u=4, v=5, level=level, parent=parent) + 2 + >>> lowest_common_ancestor(u=4, v=6, level=level, parent=parent) + 1 + >>> lowest_common_ancestor(u=2, v=3, level=level, parent=parent) + 1 + >>> lowest_common_ancestor(u=6, v=6, level=level, parent=parent) + 6 + """ # u must be deeper in the tree than v if level[u] < level[v]: u, v = swap(u, v) @@ -52,6 +98,31 @@ graph: dict[int, list[int]], root: int = 1, ) -> tuple[list[int], list[list[int]]]: + """ + sets every nodes direct parent + parent of root node is set to 0 + calculates depth of each node from root node + >>> level = [-1] * 7 + >>> parent = [[0] * 7 for _ in range(20)] + >>> graph = {1: [2, 3], 2: [4, 5], 3: [6], 4: [], 5: [], 6: []} + >>> level, parent = breadth_first_search( + ... level=level, parent=parent, max_node=6, graph=graph, root=1) + >>> level + [-1, 0, 1, 1, 2, 2, 2] + >>> parent[0] + [0, 0, 1, 1, 2, 2, 3] + + + >>> level = [-1] * 2 + >>> parent = [[0] * 2 for _ in range(20)] + >>> graph = {1: []} + >>> level, parent = breadth_first_search( + ... level=level, parent=parent, max_node=1, graph=graph, root=1) + >>> level + [-1, 0] + >>> parent[0] + [0, 0] + """ level[root] = 0 q: Queue[int] = Queue(maxsize=max_node) q.put(root) @@ -97,4 +168,4 @@ if __name__ == "__main__": - main()+ main()
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.right = Node(4) root.right.left = Node(4) root.right.right = Node(3) return root def make_asymmetric_tree() -> Node: root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(3) root.right.right = Node(4) return root def is_symmetric_tree(tree: Node) -> bool: if tree: return is_mirror(tree.left, tree.right) return True # An empty tree is considered symmetric. def is_mirror(left: Node | None, right: Node | None) -> bool: if left is None and right is None: # Both sides are empty, which is symmetric. return True if left is None or right is None: # One side is empty while the other is not, which is not symmetric. return False if left.data == right.data: # The values match, so check the subtrees recursively. return is_mirror(left.left, right.right) and is_mirror(left.right, right.left) return False if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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 represents an element of a binary tree, which contains: + + Attributes: + data: The value stored in the node (int). + left: Pointer to the left child node (Node or None). + right: Pointer to the right child node (Node or None). + + Example: + >>> node = Node(1, Node(2), Node(3)) + >>> node.data + 1 + >>> node.left.data + 2 + >>> node.right.data + 3 + """ data: int left: Node | None = None @@ -13,6 +36,28 @@ def make_symmetric_tree() -> Node: + r""" + Create a symmetric tree for testing. + + The tree looks like this: + 1 + / \ + 2 2 + / \ / \ + 3 4 4 3 + + Returns: + Node: Root node of a symmetric tree. + + Example: + >>> tree = make_symmetric_tree() + >>> tree.data + 1 + >>> tree.left.data == tree.right.data + True + >>> tree.left.left.data == tree.right.right.data + True + """ root = Node(1) root.left = Node(2) root.right = Node(2) @@ -24,6 +69,28 @@ def make_asymmetric_tree() -> Node: + r""" + Create an asymmetric tree for testing. + + The tree looks like this: + 1 + / \ + 2 2 + / \ / \ + 3 4 3 4 + + Returns: + Node: Root node of an asymmetric tree. + + Example: + >>> tree = make_asymmetric_tree() + >>> tree.data + 1 + >>> tree.left.data == tree.right.data + True + >>> tree.left.left.data == tree.right.right.data + False + """ root = Node(1) root.left = Node(2) root.right = Node(2) @@ -35,12 +102,45 @@ def is_symmetric_tree(tree: Node) -> bool: + """ + Check if a binary tree is symmetric (i.e., a mirror of itself). + + Parameters: + tree: The root node of the binary tree. + + Returns: + bool: True if the tree is symmetric, False otherwise. + + Example: + >>> is_symmetric_tree(make_symmetric_tree()) + True + >>> is_symmetric_tree(make_asymmetric_tree()) + False + """ if tree: return is_mirror(tree.left, tree.right) return True # An empty tree is considered symmetric. def is_mirror(left: Node | None, right: Node | None) -> bool: + """ + Check if two subtrees are mirror images of each other. + + Parameters: + left: The root node of the left subtree. + right: The root node of the right subtree. + + Returns: + bool: True if the two subtrees are mirrors of each other, False otherwise. + + Example: + >>> tree1 = make_symmetric_tree() + >>> is_mirror(tree1.left, tree1.right) + True + >>> tree2 = make_asymmetric_tree() + >>> is_mirror(tree2.left, tree2.right) + False + """ if left is None and right is None: # Both sides are empty, which is symmetric. return True @@ -56,4 +156,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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 self.right: Node | None = None def __repr__(self) -> str: return f"Node(min_value={self.minn} max_value={self.maxx})" def build_tree(arr: list[int]) -> Node | None: root = Node(len(arr)) root.minn, root.maxx = min(arr), max(arr) # Leaf node case where the node contains only one unique value if root.minn == root.maxx: return root """ Take the mean of min and max element of arr as the pivot and partition arr into left_arr and right_arr with all elements <= pivot in the left_arr and the rest in right_arr, maintaining the order of the elements, then recursively build trees for left_arr and right_arr """ pivot = (root.minn + root.maxx) // 2 left_arr: list[int] = [] right_arr: list[int] = [] for index, num in enumerate(arr): if num <= pivot: left_arr.append(num) else: right_arr.append(num) root.map_left[index] = len(left_arr) root.left = build_tree(left_arr) root.right = build_tree(right_arr) return root def rank_till_index(node: Node | None, num: int, index: int) -> int: if index < 0 or node is None: return 0 # Leaf node cases if node.minn == node.maxx: return index + 1 if node.minn == num else 0 pivot = (node.minn + node.maxx) // 2 if num <= pivot: # go the left subtree and map index to the left subtree return rank_till_index(node.left, num, node.map_left[index] - 1) else: # go to the right subtree and map index to the right subtree return rank_till_index(node.right, num, index - node.map_left[index]) def rank(node: Node | None, num: int, start: int, end: int) -> int: if start > end: return 0 rank_till_end = rank_till_index(node, num, end) rank_before_start = rank_till_index(node, num, start - 1) return rank_till_end - rank_before_start def quantile(node: Node | None, index: int, start: int, end: int) -> int: if index > (end - start) or start > end or node is None: return -1 # Leaf node case if node.minn == node.maxx: return node.minn # Number of elements in the left subtree in interval [start, end] num_elements_in_left_tree = node.map_left[end] - ( node.map_left[start - 1] if start else 0 ) if num_elements_in_left_tree > index: return quantile( node.left, index, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, ) else: return quantile( node.right, index - num_elements_in_left_tree, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], ) def range_counting( node: Node | None, start: int, end: int, start_num: int, end_num: int ) -> int: if ( start > end or node is None or start_num > end_num or node.minn > end_num or node.maxx < start_num ): return 0 if start_num <= node.minn and node.maxx <= end_num: return end - start + 1 left = range_counting( node.left, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, start_num, end_num, ) right = range_counting( node.right, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], start_num, end_num, ) return left + right if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 fenwick trees. You can read more about them here: +1. https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf +2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s +3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s +""" from __future__ import annotations @@ -13,10 +22,24 @@ self.right: Node | None = None def __repr__(self) -> str: + """ + >>> node = Node(length=27) + >>> repr(node) + 'Node(min_value=-1 max_value=-1)' + >>> repr(node) == str(node) + True + """ return f"Node(min_value={self.minn} max_value={self.maxx})" def build_tree(arr: list[int]) -> Node | None: + """ + Builds the tree for arr and returns the root + of the constructed tree + + >>> build_tree(test_array) + Node(min_value=0 max_value=9) + """ root = Node(len(arr)) root.minn, root.maxx = min(arr), max(arr) # Leaf node case where the node contains only one unique value @@ -45,6 +68,21 @@ def rank_till_index(node: Node | None, num: int, index: int) -> int: + """ + Returns the number of occurrences of num in interval [0, index] in the list + + >>> root = build_tree(test_array) + >>> rank_till_index(root, 6, 6) + 1 + >>> rank_till_index(root, 2, 0) + 1 + >>> rank_till_index(root, 1, 10) + 2 + >>> rank_till_index(root, 17, 7) + 0 + >>> rank_till_index(root, 0, 9) + 1 + """ if index < 0 or node is None: return 0 # Leaf node cases @@ -60,6 +98,19 @@ def rank(node: Node | None, num: int, start: int, end: int) -> int: + """ + Returns the number of occurrences of num in interval [start, end] in the list + + >>> root = build_tree(test_array) + >>> rank(root, 6, 3, 13) + 2 + >>> rank(root, 2, 0, 19) + 4 + >>> rank(root, 9, 2 ,2) + 0 + >>> rank(root, 0, 5, 10) + 2 + """ if start > end: return 0 rank_till_end = rank_till_index(node, num, end) @@ -68,6 +119,20 @@ def quantile(node: Node | None, index: int, start: int, end: int) -> int: + """ + Returns the index'th smallest element in interval [start, end] in the list + index is 0-indexed + + >>> root = build_tree(test_array) + >>> quantile(root, 2, 2, 5) + 5 + >>> quantile(root, 5, 2, 13) + 4 + >>> quantile(root, 0, 6, 6) + 8 + >>> quantile(root, 4, 2, 5) + -1 + """ if index > (end - start) or start > end or node is None: return -1 # Leaf node case @@ -96,6 +161,22 @@ def range_counting( node: Node | None, start: int, end: int, start_num: int, end_num: int ) -> int: + """ + Returns the number of elements in range [start_num, end_num] + in interval [start, end] in the list + + >>> root = build_tree(test_array) + >>> range_counting(root, 1, 10, 3, 7) + 3 + >>> range_counting(root, 2, 2, 1, 4) + 1 + >>> range_counting(root, 0, 19, 0, 100) + 20 + >>> range_counting(root, 1, 0, 1, 100) + 0 + >>> range_counting(root, 0, 17, 100, 1) + 0 + """ if ( start > end or node is None @@ -126,4 +207,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 = ( next_prime(value % self.size_table) if not is_prime(value % self.size_table) else value % self.size_table ) # gt = bigger than return next_prime_gt - (data % next_prime_gt) def __hash_double_function(self, key, data, increment): return (increment * self.__hash_function_2(key, data)) % self.size_table def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(data) while self.values[new_key] is not None and self.values[new_key] != key: new_key = ( self.__hash_double_function(key, data, i) if self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break else: i += 1 return new_key if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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, +producing a uniform distribution of records throughout a hash table. This technique +does not yield any clusters. It is one of effective method for resolving collisions. + +Double hashing can be done using: (hash1(key) + i * hash2(key)) % TABLE_SIZE +Where hash1() and hash2() are hash functions and TABLE_SIZE is size of hash table. + +Reference: https://en.wikipedia.org/wiki/Double_hashing +""" from .hash_table import HashTable from .number_theory.prime_numbers import is_prime, next_prime class DoubleHash(HashTable): + """ + Hash Table example with open addressing and Double Hash + """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -21,6 +36,33 @@ return (increment * self.__hash_function_2(key, data)) % self.size_table def _collision_resolution(self, key, data=None): + """ + Examples: + + 1. Try to add three data elements when the size is three + >>> dh = DoubleHash(3) + >>> dh.insert_data(10) + >>> dh.insert_data(20) + >>> dh.insert_data(30) + >>> dh.keys() + {1: 10, 2: 20, 0: 30} + + 2. Try to add three data elements when the size is two + >>> dh = DoubleHash(2) + >>> dh.insert_data(10) + >>> dh.insert_data(20) + >>> dh.insert_data(30) + >>> dh.keys() + {10: 10, 9: 20, 8: 30} + + 3. Try to add three data elements when the size is four + >>> dh = DoubleHash(4) + >>> dh.insert_data(10) + >>> dh.insert_data(20) + >>> dh.insert_data(30) + >>> dh.keys() + {9: 20, 10: 10, 8: 30} + """ i = 1 new_key = self.hash_function(data) @@ -41,4 +83,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 while node: # Avoid infinite loop in there's a cycle if node in visited: return visited.append(node) yield node.data node = node.next_node def add_node(self, data: Any) -> None: new_node = Node(data) if self.head is None: self.head = new_node return current_node = self.head while current_node.next_node is not None: current_node = current_node.next_node current_node.next_node = new_node def detect_cycle(self) -> bool: if self.head is None: return False slow_pointer: Node | None = self.head fast_pointer: Node | None = self.head while fast_pointer is not None and fast_pointer.next_node is not None: slow_pointer = slow_pointer.next_node if slow_pointer else None fast_pointer = fast_pointer.next_node.next_node if slow_pointer == fast_pointer: return True return False if __name__ == "__main__": import doctest doctest.testmod() linked_list = LinkedList() linked_list.add_node(1) linked_list.add_node(2) linked_list.add_node(3) linked_list.add_node(4) # Create a cycle in the linked list # It first checks if the head, next_node, and next_node.next_node attributes of the # linked list are not None to avoid any potential type errors. if ( linked_list.head and linked_list.head.next_node and linked_list.head.next_node.next_node ): linked_list.head.next_node.next_node.next_node = linked_list.head.next_node has_cycle = linked_list.detect_cycle() print(has_cycle) # Output: True
--- +++ @@ -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 a cycle in the linked list, +the fast pointer will eventually catch up to the slow pointer and they will +meet at the same node. If there is no cycle, the fast pointer will reach the end of +the linked list and the algorithm will terminate. + +For more information: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare +""" from collections.abc import Iterator from dataclasses import dataclass @@ -6,6 +17,9 @@ @dataclass class Node: + """ + A class representing a node in a singly linked list. + """ data: Any next_node: Self | None = None @@ -13,10 +27,27 @@ @dataclass class LinkedList: + """ + A class representing a singly linked list. + """ head: Node | None = None def __iter__(self) -> Iterator: + """ + Iterates through the linked list. + + Returns: + Iterator: An iterator over the linked list. + + Examples: + >>> linked_list = LinkedList() + >>> list(linked_list) + [] + >>> linked_list.add_node(1) + >>> tuple(linked_list) + (1,) + """ visited = [] node = self.head while node: @@ -28,6 +59,21 @@ node = node.next_node def add_node(self, data: Any) -> None: + """ + Adds a new node to the end of the linked list. + + Args: + data (Any): The data to be stored in the new node. + + Examples: + >>> linked_list = LinkedList() + >>> linked_list.add_node(1) + >>> linked_list.add_node(2) + >>> linked_list.add_node(3) + >>> linked_list.add_node(4) + >>> tuple(linked_list) + (1, 2, 3, 4) + """ new_node = Node(data) if self.head is None: @@ -41,6 +87,29 @@ current_node.next_node = new_node def detect_cycle(self) -> bool: + """ + Detects if there is a cycle in the linked list using + Floyd's cycle detection algorithm. + + Returns: + bool: True if there is a cycle, False otherwise. + + Examples: + >>> linked_list = LinkedList() + >>> linked_list.add_node(1) + >>> linked_list.add_node(2) + >>> linked_list.add_node(3) + >>> linked_list.add_node(4) + + >>> linked_list.detect_cycle() + False + + # Create a cycle in the linked list + >>> linked_list.head.next_node.next_node.next_node = linked_list.head.next_node + + >>> linked_list.detect_cycle() + True + """ if self.head is None: return False @@ -78,4 +147,4 @@ linked_list.head.next_node.next_node.next_node = linked_list.head.next_node has_cycle = linked_list.detect_cycle() - print(has_cycle) # Output: True+ print(has_cycle) # Output: True
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 self.values = [None] * self.size_table self.lim_charge = 0.75 if lim_charge is None else lim_charge self.charge_factor = 1 if charge_factor is None else charge_factor self.__aux_list: list = [] self._keys: dict = {} def keys(self): return self._keys def balanced_factor(self): return sum(1 for slot in self.values if slot is not None) / ( self.size_table * self.charge_factor ) def hash_function(self, key): return key % self.size_table def _step_by_step(self, step_ord): print(f"step {step_ord}") print(list(range(len(self.values)))) print(self.values) def bulk_insert(self, values): i = 1 self.__aux_list = values for value in values: self.insert_data(value) self._step_by_step(i) i += 1 def _set_value(self, key, data): self.values[key] = data self._keys[key] = data @abstractmethod def _collision_resolution(self, key, data=None): new_key = self.hash_function(key + 1) while self.values[new_key] is not None and self.values[new_key] != key: if self.values.count(None) > 0: new_key = self.hash_function(new_key + 1) else: new_key = None break return new_key def rehashing(self): survivor_values = [value for value in self.values if value is not None] self.size_table = next_prime(self.size_table, factor=2) self._keys.clear() self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/ for value in survivor_values: self.insert_data(value) def insert_data(self, data): key = self.hash_function(data) if self.values[key] is None: self._set_value(key, data) elif self.values[key] == data: pass else: collision_resolution = self._collision_resolution(key, data) if collision_resolution is not None: self._set_value(collision_resolution, data) else: self.rehashing() self.insert_data(data) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 value pairs. + key being the index number in hash table and value being the data value. + + Examples: + 1. creating HashTable with size 10 and inserting 3 elements + >>> ht = HashTable(10) + >>> ht.insert_data(10) + >>> ht.insert_data(20) + >>> ht.insert_data(30) + >>> ht.keys() + {0: 10, 1: 20, 2: 30} + + 2. creating HashTable with size 5 and inserting 5 elements + >>> ht = HashTable(5) + >>> ht.insert_data(5) + >>> ht.insert_data(4) + >>> ht.insert_data(3) + >>> ht.insert_data(2) + >>> ht.insert_data(1) + >>> ht.keys() + {0: 5, 4: 4, 3: 3, 2: 2, 1: 1} + """ return self._keys def balanced_factor(self): @@ -28,6 +54,30 @@ ) def hash_function(self, key): + """ + Generates hash for the given key value + + Examples: + + Creating HashTable with size 5 + >>> ht = HashTable(5) + >>> ht.hash_function(10) + 0 + >>> ht.hash_function(20) + 0 + >>> ht.hash_function(4) + 4 + >>> ht.hash_function(18) + 3 + >>> ht.hash_function(-18) + 2 + >>> ht.hash_function(18.5) + 3.5 + >>> ht.hash_function(0) + 0 + >>> ht.hash_function(-0) + 0 + """ return key % self.size_table def _step_by_step(self, step_ord): @@ -36,6 +86,43 @@ print(self.values) def bulk_insert(self, values): + """ + bulk_insert is used for entering more than one element at a time + in the HashTable. + + Examples: + 1. + >>> ht = HashTable(5) + >>> ht.bulk_insert((10,20,30)) + step 1 + [0, 1, 2, 3, 4] + [10, None, None, None, None] + step 2 + [0, 1, 2, 3, 4] + [10, 20, None, None, None] + step 3 + [0, 1, 2, 3, 4] + [10, 20, 30, None, None] + + 2. + >>> ht = HashTable(5) + >>> ht.bulk_insert([5,4,3,2,1]) + step 1 + [0, 1, 2, 3, 4] + [5, None, None, None, None] + step 2 + [0, 1, 2, 3, 4] + [5, None, None, None, 4] + step 3 + [0, 1, 2, 3, 4] + [5, None, None, 3, 4] + step 4 + [0, 1, 2, 3, 4] + [5, None, 2, 3, 4] + step 5 + [0, 1, 2, 3, 4] + [5, 1, 2, 3, 4] + """ i = 1 self.__aux_list = values for value in values: @@ -44,11 +131,100 @@ i += 1 def _set_value(self, key, data): + """ + _set_value functions allows to update value at a particular hash + + Examples: + 1. _set_value in HashTable of size 5 + >>> ht = HashTable(5) + >>> ht.insert_data(10) + >>> ht.insert_data(20) + >>> ht.insert_data(30) + >>> ht._set_value(0,15) + >>> ht.keys() + {0: 15, 1: 20, 2: 30} + + 2. _set_value in HashTable of size 2 + >>> ht = HashTable(2) + >>> ht.insert_data(17) + >>> ht.insert_data(18) + >>> ht.insert_data(99) + >>> ht._set_value(3,15) + >>> ht.keys() + {3: 15, 2: 17, 4: 99} + + 3. _set_value in HashTable when hash is not present + >>> ht = HashTable(2) + >>> ht.insert_data(17) + >>> ht.insert_data(18) + >>> ht.insert_data(99) + >>> ht._set_value(0,15) + >>> ht.keys() + {3: 18, 2: 17, 4: 99, 0: 15} + + 4. _set_value in HashTable when multiple hash are not present + >>> ht = HashTable(2) + >>> ht.insert_data(17) + >>> ht.insert_data(18) + >>> ht.insert_data(99) + >>> ht._set_value(0,15) + >>> ht._set_value(1,20) + >>> ht.keys() + {3: 18, 2: 17, 4: 99, 0: 15, 1: 20} + """ self.values[key] = data self._keys[key] = data @abstractmethod def _collision_resolution(self, key, data=None): + """ + This method is a type of open addressing which is used for handling collision. + + In this implementation the concept of linear probing has been used. + + The hash table is searched sequentially from the original location of the + hash, if the new hash/location we get is already occupied we check for the next + hash/location. + + references: + - https://en.wikipedia.org/wiki/Linear_probing + + Examples: + 1. The collision will be with keys 18 & 99, so new hash will be created for 99 + >>> ht = HashTable(3) + >>> ht.insert_data(17) + >>> ht.insert_data(18) + >>> ht.insert_data(99) + >>> ht.keys() + {2: 17, 0: 18, 1: 99} + + 2. The collision will be with keys 17 & 101, so new hash + will be created for 101 + >>> ht = HashTable(4) + >>> ht.insert_data(17) + >>> ht.insert_data(18) + >>> ht.insert_data(99) + >>> ht.insert_data(101) + >>> ht.keys() + {1: 17, 2: 18, 3: 99, 0: 101} + + 2. The collision will be with all keys, so new hash will be created for all + >>> ht = HashTable(1) + >>> ht.insert_data(17) + >>> ht.insert_data(18) + >>> ht.insert_data(99) + >>> ht.keys() + {2: 17, 3: 18, 4: 99} + + 3. Trying to insert float key in hash + >>> ht = HashTable(1) + >>> ht.insert_data(17) + >>> ht.insert_data(18) + >>> ht.insert_data(99.99) + Traceback (most recent call last): + ... + TypeError: list indices must be integers or slices, not float + """ new_key = self.hash_function(key + 1) while self.values[new_key] is not None and self.values[new_key] != key: @@ -69,6 +245,21 @@ self.insert_data(value) def insert_data(self, data): + """ + insert_data is used for inserting a single element at a time in the HashTable. + + Examples: + + >>> ht = HashTable(3) + >>> ht.insert_data(5) + >>> ht.keys() + {2: 5} + >>> ht = HashTable(5) + >>> ht.insert_data(30) + >>> ht.insert_data(50) + >>> ht.keys() + {0: 30, 1: 50} + """ key = self.hash_function(data) if self.values[key] is None: @@ -89,4 +280,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: src_parent = self.get_parent(src) dst_parent = self.get_parent(dst) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] self.set_counts[src_parent] = 0 self.parents[src_parent] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 joined_set_size = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] self.set_counts[dst_parent] = 0 self.parents[dst_parent] = src_parent joined_set_size = self.set_counts[src_parent] self.max_set = max(self.max_set, joined_set_size) return True def get_parent(self, disj_set: int) -> int: if self.parents[disj_set] == disj_set: return disj_set self.parents[disj_set] = self.get_parent(self.parents[disj_set]) return self.parents[disj_set]
--- +++ @@ -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 + and with rank = 1 for each set + """ self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) @@ -9,6 +17,18 @@ self.parents = list(range(num_sets)) def merge(self, src: int, dst: int) -> bool: + """ + Merge two sets together using Union by rank heuristic + Return True if successful + Merge two disjoint sets + >>> A = DisjointSet([1, 1, 1]) + >>> A.merge(1, 2) + True + >>> A.merge(0, 2) + True + >>> A.merge(0, 1) + False + """ src_parent = self.get_parent(src) dst_parent = self.get_parent(dst) @@ -32,7 +52,17 @@ return True def get_parent(self, disj_set: int) -> int: + """ + Find the Parent of a given set + >>> A = DisjointSet([1, 1, 1]) + >>> A.merge(1, 2) + True + >>> A.get_parent(0) + 0 + >>> A.get_parent(1) + 2 + """ if self.parents[disj_set] == disj_set: return disj_set self.parents[disj_set] = self.get_parent(self.parents[disj_set]) - return self.parents[disj_set]+ return self.parents[disj_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) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 + """ + Quadratic probing is an open addressing scheme used for resolving + collisions in hash table. + + It works by taking the original hash index and adding successive + values of an arbitrary quadratic polynomial until open slot is found. + + Hash + 1², Hash + 2², Hash + 3² .... Hash + n² + + reference: + - https://en.wikipedia.org/wiki/Quadratic_probing + e.g: + 1. Create hash table with size 7 + >>> qp = QuadraticProbing(7) + >>> qp.insert_data(90) + >>> qp.insert_data(340) + >>> qp.insert_data(24) + >>> qp.insert_data(45) + >>> qp.insert_data(99) + >>> qp.insert_data(73) + >>> qp.insert_data(7) + >>> qp.keys() + {11: 45, 14: 99, 7: 24, 0: 340, 5: 73, 6: 90, 8: 7} + + 2. Create hash table with size 8 + >>> qp = QuadraticProbing(8) + >>> qp.insert_data(0) + >>> qp.insert_data(999) + >>> qp.insert_data(111) + >>> qp.keys() + {0: 0, 7: 999, 3: 111} + + 3. Try to add three data elements when the size is two + >>> qp = QuadraticProbing(2) + >>> qp.insert_data(0) + >>> qp.insert_data(999) + >>> qp.insert_data(111) + >>> qp.keys() + {0: 0, 4: 999, 1: 111} + + 4. Try to add three data elements when the size is one + >>> qp = QuadraticProbing(1) + >>> qp.insert_data(0) + >>> qp.insert_data(999) + >>> qp.insert_data(111) + >>> qp.keys() + {4: 999, 1: 111} + """ i = 1 new_key = self.hash_function(key + i * i) @@ -30,4 +81,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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__(None, None) def __bool__(self) -> bool: return False _deleted = _DeletedItem() class HashMap(MutableMapping[KEY, VAL]): def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 ) -> None: self._initial_block_size = initial_block_size self._buckets: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 self._capacity_factor = capacity_factor self._len = 0 def _get_bucket_index(self, key: KEY) -> int: return hash(key) % len(self._buckets) def _get_next_ind(self, ind: int) -> int: return (ind + 1) % len(self._buckets) def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: stored = self._buckets[ind] if not stored: # A falsy item means that bucket was never used (None) # or was deleted (_deleted). self._buckets[ind] = _Item(key, val) self._len += 1 return True elif stored.key == key: stored.val = val return True else: return False def _is_full(self) -> bool: limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit) def _is_sparse(self) -> bool: if len(self._buckets) <= self._initial_block_size: return False limit = len(self._buckets) * self._capacity_factor / 2 return len(self) < limit def _resize(self, new_size: int) -> None: old_buckets = self._buckets self._buckets = [None] * new_size self._len = 0 for item in old_buckets: if item: self._add_item(item.key, item.val) def _size_up(self) -> None: self._resize(len(self._buckets) * 2) def _size_down(self) -> None: self._resize(len(self._buckets) // 2) def _iterate_buckets(self, key: KEY) -> Iterator[int]: ind = self._get_bucket_index(key) for _ in range(len(self._buckets)): yield ind ind = self._get_next_ind(ind) def _add_item(self, key: KEY, val: VAL) -> None: for ind in self._iterate_buckets(key): if self._try_set(ind, key, val): break def __setitem__(self, key: KEY, val: VAL) -> None: if self._is_full(): self._size_up() self._add_item(key, val) def __delitem__(self, key: KEY) -> None: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: raise KeyError(key) if item is _deleted: continue if item.key == key: self._buckets[ind] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__(self, key: KEY) -> VAL: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(key) def __len__(self) -> int: return self._len def __iter__(self) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__(self) -> str: val_string = ", ".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})" if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 dataclasses import dataclass @@ -25,6 +34,9 @@ class HashMap(MutableMapping[KEY, VAL]): + """ + Hash map with open addressing. + """ def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 @@ -39,9 +51,29 @@ return hash(key) % len(self._buckets) def _get_next_ind(self, ind: int) -> int: + """ + Get next index. + + Implements linear open addressing. + >>> HashMap(5)._get_next_ind(3) + 4 + >>> HashMap(5)._get_next_ind(5) + 1 + >>> HashMap(5)._get_next_ind(6) + 2 + >>> HashMap(5)._get_next_ind(9) + 0 + """ return (ind + 1) % len(self._buckets) def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: + """ + Try to add value to the bucket. + + If bucket is empty or key is the same, does insert and return True. + + If bucket has another key that means that we need to check next bucket. + """ stored = self._buckets[ind] if not stored: # A falsy item means that bucket was never used (None) @@ -56,10 +88,24 @@ return False def _is_full(self) -> bool: + """ + Return true if we have reached safe capacity. + + So we need to increase the number of buckets to avoid collisions. + + >>> hm = HashMap(2) + >>> hm._add_item(1, 10) + >>> hm._add_item(2, 20) + >>> hm._is_full() + True + >>> HashMap(2)._is_full() + False + """ limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit) def _is_sparse(self) -> bool: + """Return true if we need twice fewer buckets when we have now.""" if len(self._buckets) <= self._initial_block_size: return False limit = len(self._buckets) * self._capacity_factor / 2 @@ -86,17 +132,125 @@ ind = self._get_next_ind(ind) def _add_item(self, key: KEY, val: VAL) -> None: + """ + Try to add 3 elements when the size is 5 + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm._add_item(2, 20) + >>> hm._add_item(3, 30) + >>> hm + HashMap(1: 10, 2: 20, 3: 30) + + Try to add 3 elements when the size is 5 + >>> hm = HashMap(5) + >>> hm._add_item(-5, 10) + >>> hm._add_item(6, 30) + >>> hm._add_item(-7, 20) + >>> hm + HashMap(-5: 10, 6: 30, -7: 20) + + Try to add 3 elements when size is 1 + >>> hm = HashMap(1) + >>> hm._add_item(10, 13.2) + >>> hm._add_item(6, 5.26) + >>> hm._add_item(7, 5.155) + >>> hm + HashMap(10: 13.2) + + Trying to add an element with a key that is a floating point value + >>> hm = HashMap(5) + >>> hm._add_item(1.5, 10) + >>> hm + HashMap(1.5: 10) + + 5. Trying to add an item with the same key + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm._add_item(1, 20) + >>> hm + HashMap(1: 20) + """ for ind in self._iterate_buckets(key): if self._try_set(ind, key, val): break def __setitem__(self, key: KEY, val: VAL) -> None: + """ + 1. Changing value of item whose key is present + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm.__setitem__(1, 20) + >>> hm + HashMap(1: 20) + + 2. Changing value of item whose key is not present + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm.__setitem__(0, 20) + >>> hm + HashMap(0: 20, 1: 10) + + 3. Changing the value of the same item multiple times + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm.__setitem__(1, 20) + >>> hm.__setitem__(1, 30) + >>> hm + HashMap(1: 30) + """ if self._is_full(): self._size_up() self._add_item(key, val) def __delitem__(self, key: KEY) -> None: + """ + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm._add_item(2, 20) + >>> hm._add_item(3, 30) + >>> hm.__delitem__(3) + >>> hm + HashMap(1: 10, 2: 20) + >>> hm = HashMap(5) + >>> hm._add_item(-5, 10) + >>> hm._add_item(6, 30) + >>> hm._add_item(-7, 20) + >>> hm.__delitem__(-5) + >>> hm + HashMap(6: 30, -7: 20) + + # Trying to remove a non-existing item + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm._add_item(2, 20) + >>> hm._add_item(3, 30) + >>> hm.__delitem__(4) + Traceback (most recent call last): + ... + KeyError: 4 + + # Test resize down when sparse + ## Setup: resize up + >>> hm = HashMap(initial_block_size=100, capacity_factor=0.75) + >>> len(hm._buckets) + 100 + >>> for i in range(75): + ... hm[i] = i + >>> len(hm._buckets) + 100 + >>> hm[75] = 75 + >>> len(hm._buckets) + 200 + + ## Resize down + >>> del hm[75] + >>> len(hm._buckets) + 200 + >>> del hm[74] + >>> len(hm._buckets) + 100 + """ for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: @@ -111,6 +265,25 @@ self._size_down() def __getitem__(self, key: KEY) -> VAL: + """ + Returns the item at the given key + + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm.__getitem__(1) + 10 + + >>> hm = HashMap(5) + >>> hm._add_item(10, -10) + >>> hm._add_item(20, -20) + >>> hm.__getitem__(20) + -20 + + >>> hm = HashMap(5) + >>> hm._add_item(-1, 10) + >>> hm.__getitem__(-1) + 10 + """ for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: @@ -122,6 +295,20 @@ raise KeyError(key) def __len__(self) -> int: + """ + Returns the number of items present in hashmap + + >>> hm = HashMap(5) + >>> hm._add_item(1, 10) + >>> hm._add_item(2, 20) + >>> hm._add_item(3, 30) + >>> hm.__len__() + 3 + + >>> hm = HashMap(5) + >>> hm.__len__() + 0 + """ return self._len def __iter__(self) -> Iterator[KEY]: @@ -137,4 +324,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: # Negatives, 0, 1 and all even numbers are not primes return False odd_numbers = range(3, int(math.sqrt(number) + 1), 2) return not any(not number % i for i in odd_numbers) def next_prime(value, factor=1, **kwargs): value = factor * value first_value_val = value while not is_prime(value): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1, **kwargs) return value
--- +++ @@ -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 + >>> is_prime(1) + False + >>> is_prime(2) + True + >>> is_prime(3) + True + >>> is_prime(27) + False + >>> is_prime(87) + False + >>> is_prime(563) + True + >>> is_prime(2999) + True + >>> is_prime(67483) + False + """ # precondition assert isinstance(number, int) and (number >= 0), ( @@ -30,4 +56,4 @@ if value == first_value_val: return next_prime(value + 1, **kwargs) - return value+ return value
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 ints: self.append(i) def __iter__(self) -> Iterator[int]: node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def __str__(self) -> str: return " -> ".join([str(node) for node in self]) def append(self, data: int) -> None: if not self.head: self.head = Node(data) return node = self.head while node.next_node: node = node.next_node node.next_node = Node(data) def reverse_k_nodes(self, group_size: int) -> None: if self.head is None or self.head.next_node is None: return length = len(self) dummy_head = Node(0) dummy_head.next_node = self.head previous_node = dummy_head while length >= group_size: current_node = previous_node.next_node assert current_node next_node = current_node.next_node for _ in range(1, group_size): assert next_node, current_node current_node.next_node = next_node.next_node assert previous_node next_node.next_node = previous_node.next_node previous_node.next_node = next_node next_node = current_node.next_node previous_node = current_node length -= group_size self.head = dummy_head.next_node if __name__ == "__main__": import doctest doctest.testmod() ll = LinkedList([1, 2, 3, 4, 5]) print(f"Original Linked List: {ll}") k = 2 ll.reverse_k_nodes(k) print(f"After reversing groups of size {k}: {ll}")
--- +++ @@ -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 = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: + """ + >>> for i in range(3): + ... len(LinkedList(range(i))) == i + True + True + True + >>> len(LinkedList("abcdefgh")) + 8 + """ return sum(1 for _ in self) def __str__(self) -> str: + """ + >>> str(LinkedList([])) + '' + >>> str(LinkedList(range(5))) + '0 -> 1 -> 2 -> 3 -> 4' + """ return " -> ".join([str(node) for node in self]) def append(self, data: int) -> None: + """ + >>> ll = LinkedList([1, 2]) + >>> tuple(ll) + (1, 2) + >>> ll.append(3) + >>> tuple(ll) + (1, 2, 3) + >>> ll.append(4) + >>> tuple(ll) + (1, 2, 3, 4) + >>> len(ll) + 4 + """ if not self.head: self.head = Node(data) return @@ -38,6 +74,15 @@ node.next_node = Node(data) def reverse_k_nodes(self, group_size: int) -> None: + """ + reverse nodes within groups of size k + >>> ll = LinkedList([1, 2, 3, 4, 5]) + >>> ll.reverse_k_nodes(2) + >>> tuple(ll) + (2, 1, 4, 3, 5) + >>> str(ll) + '2 -> 1 -> 4 -> 3 -> 5' + """ if self.head is None or self.head.next_node is None: return @@ -70,4 +115,4 @@ print(f"Original Linked List: {ll}") k = 2 ll.reverse_k_nodes(k) - print(f"After reversing groups of size {k}: {ll}")+ print(f"After reversing groups of size {k}: {ll}")
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, "Unequal Sizes of Blocks" if self.val < other.val: other.left = self.right other.parent = None if self.right: self.right.parent = other self.right = other self.left_tree_size = self.left_tree_size * 2 + 1 return self else: self.left = other.right self.parent = None if other.right: other.right.parent = self other.right = self other.left_tree_size = other.left_tree_size * 2 + 1 return other class BinomialHeap: def __init__(self, bottom_root=None, min_node=None, heap_size=0): self.size = heap_size self.bottom_root = bottom_root self.min_node = min_node def merge_heaps(self, other): # Empty heaps corner cases if other.size == 0: return None if self.size == 0: self.size = other.size self.bottom_root = other.bottom_root self.min_node = other.min_node return None # Update size self.size = self.size + other.size # Update min.node if self.min_node.val > other.min_node.val: self.min_node = other.min_node # Merge # Order roots by left_subtree_size combined_roots_list = [] i, j = self.bottom_root, other.bottom_root while i or j: if i and ((not j) or i.left_tree_size < j.left_tree_size): combined_roots_list.append((i, True)) i = i.parent else: combined_roots_list.append((j, False)) j = j.parent # Insert links between them for i in range(len(combined_roots_list) - 1): if combined_roots_list[i][1] != combined_roots_list[i + 1][1]: combined_roots_list[i][0].parent = combined_roots_list[i + 1][0] combined_roots_list[i + 1][0].left = combined_roots_list[i][0] # Consecutively merge roots with same left_tree_size i = combined_roots_list[0][0] while i.parent: if ( (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent) ) or ( i.left_tree_size == i.parent.left_tree_size and i.left_tree_size != i.parent.parent.left_tree_size ): # Neighbouring Nodes previous_node = i.left next_node = i.parent.parent # Merging trees i = i.merge_trees(i.parent) # Updating links i.left = previous_node i.parent = next_node if previous_node: previous_node.parent = i if next_node: next_node.left = i else: i = i.parent # Updating self.bottom_root while i.left: i = i.left self.bottom_root = i # Update other other.size = self.size other.bottom_root = self.bottom_root other.min_node = self.min_node # Return the merged heap return self def insert(self, val): if self.size == 0: self.bottom_root = Node(val) self.size = 1 self.min_node = self.bottom_root else: # Create new node new_node = Node(val) # Update size self.size += 1 # update min_node if val < self.min_node.val: self.min_node = new_node # Put new_node as a bottom_root in heap self.bottom_root.left = new_node new_node.parent = self.bottom_root self.bottom_root = new_node # Consecutively merge roots with same left_tree_size while ( self.bottom_root.parent and self.bottom_root.left_tree_size == self.bottom_root.parent.left_tree_size ): # Next node next_node = self.bottom_root.parent.parent # Merge self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent) # Update Links self.bottom_root.parent = next_node self.bottom_root.left = None if next_node: next_node.left = self.bottom_root def peek(self): return self.min_node.val def is_empty(self): return self.size == 0 def delete_min(self): # assert not self.isEmpty(), "Empty Heap" # Save minimal value min_value = self.min_node.val # Last element in heap corner case if self.size == 1: # Update size self.size = 0 # Update bottom root self.bottom_root = None # Update min_node self.min_node = None return min_value # No right subtree corner case # The structure of the tree implies that this should be the bottom root # and there is at least one other root if self.min_node.right is None: # Update size self.size -= 1 # Update bottom root self.bottom_root = self.bottom_root.parent self.bottom_root.left = None # Update min_node self.min_node = self.bottom_root i = self.bottom_root.parent while i: if i.val < self.min_node.val: self.min_node = i i = i.parent return min_value # General case # Find the BinomialHeap of the right subtree of min_node bottom_of_new = self.min_node.right bottom_of_new.parent = None min_of_new = bottom_of_new size_of_new = 1 # Size, min_node and bottom_root while bottom_of_new.left: size_of_new = size_of_new * 2 + 1 bottom_of_new = bottom_of_new.left if bottom_of_new.val < min_of_new.val: min_of_new = bottom_of_new # Corner case of single root on top left path if (not self.min_node.left) and (not self.min_node.parent): self.size = size_of_new self.bottom_root = bottom_of_new self.min_node = min_of_new # print("Single root, multiple nodes case") return min_value # Remaining cases # Construct heap of right subtree new_heap = BinomialHeap( bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new ) # Update size self.size = self.size - 1 - size_of_new # Neighbour nodes previous_node = self.min_node.left next_node = self.min_node.parent # Initialize new bottom_root and min_node self.min_node = previous_node or next_node self.bottom_root = next_node # Update links of previous_node and search below for new min_node and # bottom_root if previous_node: previous_node.parent = next_node # Update bottom_root and search for min_node below self.bottom_root = previous_node self.min_node = previous_node while self.bottom_root.left: self.bottom_root = self.bottom_root.left if self.bottom_root.val < self.min_node.val: self.min_node = self.bottom_root if next_node: next_node.left = previous_node # Search for new min_node above min_node i = next_node while i: if i.val < self.min_node.val: self.min_node = i i = i.parent # Merge heaps self.merge_heaps(new_heap) return int(min_value) def pre_order(self): # Find top root top_root = self.bottom_root while top_root.parent: top_root = top_root.parent # preorder heap_pre_order = [] self.__traversal(top_root, heap_pre_order) return heap_pre_order def __traversal(self, curr_node, preorder, level=0): if curr_node: preorder.append((curr_node.val, level)) self.__traversal(curr_node.left, preorder, level + 1) self.__traversal(curr_node.right, preorder, level + 1) else: preorder.append(("#", level)) def __str__(self): if self.is_empty(): return "" preorder_heap = self.pre_order() return "\n".join(("-" * level + str(value)) for value, level in preorder_heap) # Unit Tests if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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_tree_size == other.left_tree_size, "Unequal Sizes of Blocks" - - if self.val < other.val: - other.left = self.right - other.parent = None - if self.right: - self.right.parent = other - self.right = other - self.left_tree_size = self.left_tree_size * 2 + 1 - return self - else: - self.left = other.right - self.parent = None - if other.right: - other.right.parent = self - other.right = self - other.left_tree_size = other.left_tree_size * 2 + 1 - return other - - -class BinomialHeap: - - def __init__(self, bottom_root=None, min_node=None, heap_size=0): - self.size = heap_size - self.bottom_root = bottom_root - self.min_node = min_node - - def merge_heaps(self, other): - - # Empty heaps corner cases - if other.size == 0: - return None - if self.size == 0: - self.size = other.size - self.bottom_root = other.bottom_root - self.min_node = other.min_node - return None - # Update size - self.size = self.size + other.size - - # Update min.node - if self.min_node.val > other.min_node.val: - self.min_node = other.min_node - # Merge - - # Order roots by left_subtree_size - combined_roots_list = [] - i, j = self.bottom_root, other.bottom_root - while i or j: - if i and ((not j) or i.left_tree_size < j.left_tree_size): - combined_roots_list.append((i, True)) - i = i.parent - else: - combined_roots_list.append((j, False)) - j = j.parent - # Insert links between them - for i in range(len(combined_roots_list) - 1): - if combined_roots_list[i][1] != combined_roots_list[i + 1][1]: - combined_roots_list[i][0].parent = combined_roots_list[i + 1][0] - combined_roots_list[i + 1][0].left = combined_roots_list[i][0] - # Consecutively merge roots with same left_tree_size - i = combined_roots_list[0][0] - while i.parent: - if ( - (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent) - ) or ( - i.left_tree_size == i.parent.left_tree_size - and i.left_tree_size != i.parent.parent.left_tree_size - ): - # Neighbouring Nodes - previous_node = i.left - next_node = i.parent.parent - - # Merging trees - i = i.merge_trees(i.parent) - - # Updating links - i.left = previous_node - i.parent = next_node - if previous_node: - previous_node.parent = i - if next_node: - next_node.left = i - else: - i = i.parent - # Updating self.bottom_root - while i.left: - i = i.left - self.bottom_root = i - - # Update other - other.size = self.size - other.bottom_root = self.bottom_root - other.min_node = self.min_node - - # Return the merged heap - return self - - def insert(self, val): - if self.size == 0: - self.bottom_root = Node(val) - self.size = 1 - self.min_node = self.bottom_root - else: - # Create new node - new_node = Node(val) - - # Update size - self.size += 1 - - # update min_node - if val < self.min_node.val: - self.min_node = new_node - # Put new_node as a bottom_root in heap - self.bottom_root.left = new_node - new_node.parent = self.bottom_root - self.bottom_root = new_node - - # Consecutively merge roots with same left_tree_size - while ( - self.bottom_root.parent - and self.bottom_root.left_tree_size - == self.bottom_root.parent.left_tree_size - ): - # Next node - next_node = self.bottom_root.parent.parent - - # Merge - self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent) - - # Update Links - self.bottom_root.parent = next_node - self.bottom_root.left = None - if next_node: - next_node.left = self.bottom_root - - def peek(self): - return self.min_node.val - - def is_empty(self): - return self.size == 0 - - def delete_min(self): - # assert not self.isEmpty(), "Empty Heap" - - # Save minimal value - min_value = self.min_node.val - - # Last element in heap corner case - if self.size == 1: - # Update size - self.size = 0 - - # Update bottom root - self.bottom_root = None - - # Update min_node - self.min_node = None - - return min_value - # No right subtree corner case - # The structure of the tree implies that this should be the bottom root - # and there is at least one other root - if self.min_node.right is None: - # Update size - self.size -= 1 - - # Update bottom root - self.bottom_root = self.bottom_root.parent - self.bottom_root.left = None - - # Update min_node - self.min_node = self.bottom_root - i = self.bottom_root.parent - while i: - if i.val < self.min_node.val: - self.min_node = i - i = i.parent - return min_value - # General case - # Find the BinomialHeap of the right subtree of min_node - bottom_of_new = self.min_node.right - bottom_of_new.parent = None - min_of_new = bottom_of_new - size_of_new = 1 - - # Size, min_node and bottom_root - while bottom_of_new.left: - size_of_new = size_of_new * 2 + 1 - bottom_of_new = bottom_of_new.left - if bottom_of_new.val < min_of_new.val: - min_of_new = bottom_of_new - # Corner case of single root on top left path - if (not self.min_node.left) and (not self.min_node.parent): - self.size = size_of_new - self.bottom_root = bottom_of_new - self.min_node = min_of_new - # print("Single root, multiple nodes case") - return min_value - # Remaining cases - # Construct heap of right subtree - new_heap = BinomialHeap( - bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new - ) - - # Update size - self.size = self.size - 1 - size_of_new - - # Neighbour nodes - previous_node = self.min_node.left - next_node = self.min_node.parent - - # Initialize new bottom_root and min_node - self.min_node = previous_node or next_node - self.bottom_root = next_node - - # Update links of previous_node and search below for new min_node and - # bottom_root - if previous_node: - previous_node.parent = next_node - - # Update bottom_root and search for min_node below - self.bottom_root = previous_node - self.min_node = previous_node - while self.bottom_root.left: - self.bottom_root = self.bottom_root.left - if self.bottom_root.val < self.min_node.val: - self.min_node = self.bottom_root - if next_node: - next_node.left = previous_node - - # Search for new min_node above min_node - i = next_node - while i: - if i.val < self.min_node.val: - self.min_node = i - i = i.parent - # Merge heaps - self.merge_heaps(new_heap) - - return int(min_value) - - def pre_order(self): - # Find top root - top_root = self.bottom_root - while top_root.parent: - top_root = top_root.parent - # preorder - heap_pre_order = [] - self.__traversal(top_root, heap_pre_order) - return heap_pre_order - - def __traversal(self, curr_node, preorder, level=0): - if curr_node: - preorder.append((curr_node.val, level)) - self.__traversal(curr_node.left, preorder, level + 1) - self.__traversal(curr_node.right, preorder, level + 1) - else: - preorder.append(("#", level)) - - def __str__(self): - if self.is_empty(): - return "" - preorder_heap = self.pre_order() - - return "\n".join(("-" * level + str(value)) for value, level in preorder_heap) - - -# Unit Tests -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +Binomial Heap +Reference: Advanced Data Structures, Peter Brass +""" + + +class Node: + """ + Node in a doubly-linked binomial tree, containing: + - value + - size of left subtree + - link to left, right and parent nodes + """ + + 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): + """ + In-place merge of two binomial trees of equal size. + Returns the root of the resulting tree + """ + assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks" + + if self.val < other.val: + other.left = self.right + other.parent = None + if self.right: + self.right.parent = other + self.right = other + self.left_tree_size = self.left_tree_size * 2 + 1 + return self + else: + self.left = other.right + self.parent = None + if other.right: + other.right.parent = self + other.right = self + other.left_tree_size = other.left_tree_size * 2 + 1 + return other + + +class BinomialHeap: + r""" + Min-oriented priority queue implemented with the Binomial Heap data + structure implemented with the BinomialHeap class. It supports: + - Insert element in a heap with n elements: Guaranteed logn, amoratized 1 + - Merge (meld) heaps of size m and n: O(logn + logm) + - Delete Min: O(logn) + - Peek (return min without deleting it): O(1) + + Example: + + Create a random permutation of 30 integers to be inserted and 19 of them deleted + >>> import numpy as np + >>> permutation = np.random.permutation(list(range(30))) + + Create a Heap and insert the 30 integers + __init__() test + >>> first_heap = BinomialHeap() + + 30 inserts - insert() test + >>> for number in permutation: + ... first_heap.insert(number) + + Size test + >>> first_heap.size + 30 + + Deleting - delete() test + >>> [int(first_heap.delete_min()) for _ in range(20)] + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + + Create a new Heap + >>> second_heap = BinomialHeap() + >>> vals = [17, 20, 31, 34] + >>> for value in vals: + ... second_heap.insert(value) + + + The heap should have the following structure: + + 17 + / \ + # 31 + / \ + 20 34 + / \ / \ + # # # # + + preOrder() test + >>> " ".join(str(x) for x in second_heap.pre_order()) + "(17, 0) ('#', 1) (31, 1) (20, 2) ('#', 3) ('#', 3) (34, 2) ('#', 3) ('#', 3)" + + printing Heap - __str__() test + >>> print(second_heap) + 17 + -# + -31 + --20 + ---# + ---# + --34 + ---# + ---# + + mergeHeaps() test + >>> + >>> merged = second_heap.merge_heaps(first_heap) + >>> merged.peek() + 17 + + values in merged heap; (merge is inplace) + >>> results = [] + >>> while not first_heap.is_empty(): + ... results.append(int(first_heap.delete_min())) + >>> results + [17, 20, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31, 34] + """ + + def __init__(self, bottom_root=None, min_node=None, heap_size=0): + self.size = heap_size + self.bottom_root = bottom_root + self.min_node = min_node + + def merge_heaps(self, other): + """ + In-place merge of two binomial heaps. + Both of them become the resulting merged heap + """ + + # Empty heaps corner cases + if other.size == 0: + return None + if self.size == 0: + self.size = other.size + self.bottom_root = other.bottom_root + self.min_node = other.min_node + return None + # Update size + self.size = self.size + other.size + + # Update min.node + if self.min_node.val > other.min_node.val: + self.min_node = other.min_node + # Merge + + # Order roots by left_subtree_size + combined_roots_list = [] + i, j = self.bottom_root, other.bottom_root + while i or j: + if i and ((not j) or i.left_tree_size < j.left_tree_size): + combined_roots_list.append((i, True)) + i = i.parent + else: + combined_roots_list.append((j, False)) + j = j.parent + # Insert links between them + for i in range(len(combined_roots_list) - 1): + if combined_roots_list[i][1] != combined_roots_list[i + 1][1]: + combined_roots_list[i][0].parent = combined_roots_list[i + 1][0] + combined_roots_list[i + 1][0].left = combined_roots_list[i][0] + # Consecutively merge roots with same left_tree_size + i = combined_roots_list[0][0] + while i.parent: + if ( + (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent) + ) or ( + i.left_tree_size == i.parent.left_tree_size + and i.left_tree_size != i.parent.parent.left_tree_size + ): + # Neighbouring Nodes + previous_node = i.left + next_node = i.parent.parent + + # Merging trees + i = i.merge_trees(i.parent) + + # Updating links + i.left = previous_node + i.parent = next_node + if previous_node: + previous_node.parent = i + if next_node: + next_node.left = i + else: + i = i.parent + # Updating self.bottom_root + while i.left: + i = i.left + self.bottom_root = i + + # Update other + other.size = self.size + other.bottom_root = self.bottom_root + other.min_node = self.min_node + + # Return the merged heap + return self + + def insert(self, val): + """ + insert a value in the heap + """ + if self.size == 0: + self.bottom_root = Node(val) + self.size = 1 + self.min_node = self.bottom_root + else: + # Create new node + new_node = Node(val) + + # Update size + self.size += 1 + + # update min_node + if val < self.min_node.val: + self.min_node = new_node + # Put new_node as a bottom_root in heap + self.bottom_root.left = new_node + new_node.parent = self.bottom_root + self.bottom_root = new_node + + # Consecutively merge roots with same left_tree_size + while ( + self.bottom_root.parent + and self.bottom_root.left_tree_size + == self.bottom_root.parent.left_tree_size + ): + # Next node + next_node = self.bottom_root.parent.parent + + # Merge + self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent) + + # Update Links + self.bottom_root.parent = next_node + self.bottom_root.left = None + if next_node: + next_node.left = self.bottom_root + + def peek(self): + """ + return min element without deleting it + """ + return self.min_node.val + + def is_empty(self): + return self.size == 0 + + def delete_min(self): + """ + delete min element and return it + """ + # assert not self.isEmpty(), "Empty Heap" + + # Save minimal value + min_value = self.min_node.val + + # Last element in heap corner case + if self.size == 1: + # Update size + self.size = 0 + + # Update bottom root + self.bottom_root = None + + # Update min_node + self.min_node = None + + return min_value + # No right subtree corner case + # The structure of the tree implies that this should be the bottom root + # and there is at least one other root + if self.min_node.right is None: + # Update size + self.size -= 1 + + # Update bottom root + self.bottom_root = self.bottom_root.parent + self.bottom_root.left = None + + # Update min_node + self.min_node = self.bottom_root + i = self.bottom_root.parent + while i: + if i.val < self.min_node.val: + self.min_node = i + i = i.parent + return min_value + # General case + # Find the BinomialHeap of the right subtree of min_node + bottom_of_new = self.min_node.right + bottom_of_new.parent = None + min_of_new = bottom_of_new + size_of_new = 1 + + # Size, min_node and bottom_root + while bottom_of_new.left: + size_of_new = size_of_new * 2 + 1 + bottom_of_new = bottom_of_new.left + if bottom_of_new.val < min_of_new.val: + min_of_new = bottom_of_new + # Corner case of single root on top left path + if (not self.min_node.left) and (not self.min_node.parent): + self.size = size_of_new + self.bottom_root = bottom_of_new + self.min_node = min_of_new + # print("Single root, multiple nodes case") + return min_value + # Remaining cases + # Construct heap of right subtree + new_heap = BinomialHeap( + bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new + ) + + # Update size + self.size = self.size - 1 - size_of_new + + # Neighbour nodes + previous_node = self.min_node.left + next_node = self.min_node.parent + + # Initialize new bottom_root and min_node + self.min_node = previous_node or next_node + self.bottom_root = next_node + + # Update links of previous_node and search below for new min_node and + # bottom_root + if previous_node: + previous_node.parent = next_node + + # Update bottom_root and search for min_node below + self.bottom_root = previous_node + self.min_node = previous_node + while self.bottom_root.left: + self.bottom_root = self.bottom_root.left + if self.bottom_root.val < self.min_node.val: + self.min_node = self.bottom_root + if next_node: + next_node.left = previous_node + + # Search for new min_node above min_node + i = next_node + while i: + if i.val < self.min_node.val: + self.min_node = i + i = i.parent + # Merge heaps + self.merge_heaps(new_heap) + + return int(min_value) + + def pre_order(self): + """ + Returns the Pre-order representation of the heap including + values of nodes plus their level distance from the root; + Empty nodes appear as # + """ + # Find top root + top_root = self.bottom_root + while top_root.parent: + top_root = top_root.parent + # preorder + heap_pre_order = [] + self.__traversal(top_root, heap_pre_order) + return heap_pre_order + + def __traversal(self, curr_node, preorder, level=0): + """ + Pre-order traversal of nodes + """ + if curr_node: + preorder.append((curr_node.val, level)) + self.__traversal(curr_node.left, preorder, level + 1) + self.__traversal(curr_node.right, preorder, level + 1) + else: + preorder.append(("#", level)) + + def __str__(self): + """ + Overwriting str for a pre-order print of nodes in heap; + Performance is poor, so use only for small examples + """ + if self.is_empty(): + return "" + preorder_heap = self.pre_order() + + return "\n".join(("-" * level + str(value)) for value, level in preorder_heap) + + +# Unit Tests +if __name__ == "__main__": + import doctest + + doctest.testmod()
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(self, item: Any, position: int = 0) -> None: if position < 0: raise ValueError("Position must be non-negative") if position == 0 or self.head is None: new_node = Node(item, self.head) self.head = new_node else: current = self.head for _ in range(position - 1): current = current.next if current is None: raise ValueError("Out of bounds") new_node = Node(item, current.next) current.next = new_node self.size += 1 def remove(self) -> Any: # Switched 'self.is_empty()' to 'self.head is None' # because mypy was considering the possibility that 'self.head' # can be None in below else part and giving error if self.head is None: return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: if self.is_empty(): return "" else: iterate = self.head item_str = "" item_list: list[str] = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: return self.size
--- +++ @@ -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,41 @@ self.size = 0 def add(self, item: Any, position: int = 0) -> None: + """ + Add an item to the LinkedList at the specified position. + Default position is 0 (the head). + + Args: + item (Any): The item to add to the LinkedList. + position (int, optional): The position at which to add the item. + Defaults to 0. + + Raises: + ValueError: If the position is negative or out of bounds. + + >>> linked_list = LinkedList() + >>> linked_list.add(1) + >>> linked_list.add(2) + >>> linked_list.add(3) + >>> linked_list.add(4, 2) + >>> print(linked_list) + 3 --> 2 --> 4 --> 1 + + # Test adding to a negative position + >>> linked_list.add(5, -3) + Traceback (most recent call last): + ... + ValueError: Position must be non-negative + + # Test adding to an out-of-bounds position + >>> linked_list.add(5,7) + Traceback (most recent call last): + ... + ValueError: Out of bounds + >>> linked_list.add(5, 4) + >>> print(linked_list) + 3 --> 2 --> 4 --> 1 --> 5 + """ if position < 0: raise ValueError("Position must be non-negative") @@ -48,6 +90,14 @@ return self.head is None def __str__(self) -> str: + """ + >>> linked_list = LinkedList() + >>> linked_list.add(23) + >>> linked_list.add(14) + >>> linked_list.add(9) + >>> print(linked_list) + 9 --> 14 --> 23 + """ if self.is_empty(): return "" else: @@ -63,4 +113,21 @@ return item_str def __len__(self) -> int: - return self.size+ """ + >>> linked_list = LinkedList() + >>> len(linked_list) + 0 + >>> linked_list.add("a") + >>> len(linked_list) + 1 + >>> linked_list.add("b") + >>> len(linked_list) + 2 + >>> _ = linked_list.remove() + >>> len(linked_list) + 1 + >>> _ = linked_list.remove() + >>> len(linked_list) + 0 + """ + return self.size
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: pass @abstractmethod def __eq__(self: T, other: object) -> bool: pass T = TypeVar("T", bound=Comparable) class Heap[T: Comparable]: def __init__(self) -> None: self.h: list[T] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> int | None: if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> int | None: left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> int | None: right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) # check which child is larger than its parent if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child # if violation indeed exists if violation != index: # swap to fix the violation self.h[violation], self.h[index] = self.h[index], self.h[violation] # fix the subsequent violation recursively if any self.max_heapify(violation) def build_max_heap(self, collection: Iterable[T]) -> None: self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def extract_max(self) -> T: if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: T) -> None: self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest # run doc test doctest.testmod() # demo for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap: Heap[int] = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
--- +++ @@ -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 + >>> h + [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] + >>> + >>> h.insert(100) + >>> h + [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] + >>> + >>> h.heap_sort() + >>> h + [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] + """ def __init__(self) -> None: self.h: list[T] = [] @@ -32,23 +53,68 @@ return str(self.h) def parent_index(self, child_idx: int) -> int | None: + """ + returns the parent index based on the given child index + + >>> h = Heap() + >>> h.build_max_heap([103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5]) + >>> h + [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] + + >>> h.parent_index(-1) # returns none if index is <=0 + + >>> h.parent_index(0) # returns none if index is <=0 + + >>> h.parent_index(1) + 0 + >>> h.parent_index(2) + 0 + >>> h.parent_index(3) + 1 + >>> h.parent_index(4) + 1 + >>> h.parent_index(5) + 2 + >>> h.parent_index(10.5) + 4.0 + >>> h.parent_index(209.0) + 104.0 + >>> h.parent_index("Test") + Traceback (most recent call last): + ... + TypeError: '>' not supported between instances of 'str' and 'int' + """ if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> int | None: + """ + return the left child index if the left child exists. + if not, return None. + """ left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> int | None: + """ + return the right child index if the right child exists. + if not, return None. + """ right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: + """ + correct a single violation of the heap property in a subtree's root. + + It is the function that is responsible for restoring the property + of Max heap i.e the maximum element is always at top. + """ if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) @@ -66,6 +132,29 @@ self.max_heapify(violation) def build_max_heap(self, collection: Iterable[T]) -> None: + """ + build max heap from an unsorted array + + >>> h = Heap() + >>> h.build_max_heap([20,40,50,20,10]) + >>> h + [50, 40, 20, 20, 10] + + >>> h = Heap() + >>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0]) + >>> h + [9, 8, 7, 4, 5, 6, 3, 2, 1, 0] + + >>> h = Heap() + >>> h.build_max_heap([514,5,61,57,8,99,105]) + >>> h + [514, 57, 105, 5, 8, 99, 61] + + >>> h = Heap() + >>> h.build_max_heap([514,5,61.6,57,8,9.9,105]) + >>> h + [514, 57, 105, 5, 8, 9.9, 61.6] + """ self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: @@ -74,6 +163,24 @@ self.max_heapify(i) def extract_max(self) -> T: + """ + get and remove max from heap + + >>> h = Heap() + >>> h.build_max_heap([20,40,50,20,10]) + >>> h.extract_max() + 50 + + >>> h = Heap() + >>> h.build_max_heap([514,5,61,57,8,99,105]) + >>> h.extract_max() + 514 + + >>> h = Heap() + >>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0]) + >>> h.extract_max() + 9 + """ if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) @@ -87,6 +194,34 @@ raise Exception("Empty heap") def insert(self, value: T) -> None: + """ + insert a new value into the max heap + + >>> h = Heap() + >>> h.insert(10) + >>> h + [10] + + >>> h = Heap() + >>> h.insert(10) + >>> h.insert(10) + >>> h + [10, 10] + + >>> h = Heap() + >>> h.insert(10) + >>> h.insert(10.1) + >>> h + [10.1, 10] + + >>> h = Heap() + >>> h.insert(0.1) + >>> h.insert(0) + >>> h.insert(9) + >>> h.insert(5) + >>> h + [9, 5, 0.1, 0] + """ self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 @@ -138,4 +273,4 @@ print(f"after new value 100 inserted: {heap}") heap.heap_sort() - print(f"heap-sorted array: {heap}\n")+ print(f"heap-sorted array: {heap}\n")
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.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def push(self, new_data: Any) -> None: new_node = Node(new_data) new_node.next_node = self.head self.head = new_node def swap_nodes(self, node_data_1: Any, node_data_2: Any) -> None: if node_data_1 == node_data_2: return node_1 = self.head while node_1 and node_1.data != node_data_1: node_1 = node_1.next_node node_2 = self.head while node_2 and node_2.data != node_data_2: node_2 = node_2.next_node if node_1 is None or node_2 is None: return # Swap the data values of the two nodes node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": """ Python script that outputs the swap of nodes in a linked list. """ from doctest import testmod testmod() linked_list = LinkedList() for i in range(5, 0, -1): linked_list.push(i) print(f"Original Linked List: {list(linked_list)}") linked_list.swap_nodes(1, 4) print(f"Modified Linked List: {list(linked_list)}") print("After swapping the nodes whose data is 1 and 4.")
--- +++ @@ -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 __iter__(self) -> Iterator: - node = self.head - while node: - yield node.data - node = node.next_node - - def __len__(self) -> int: - return sum(1 for _ in self) - - def push(self, new_data: Any) -> None: - new_node = Node(new_data) - new_node.next_node = self.head - self.head = new_node - - def swap_nodes(self, node_data_1: Any, node_data_2: Any) -> None: - if node_data_1 == node_data_2: - return - - node_1 = self.head - while node_1 and node_1.data != node_data_1: - node_1 = node_1.next_node - node_2 = self.head - while node_2 and node_2.data != node_data_2: - node_2 = node_2.next_node - if node_1 is None or node_2 is None: - return - # Swap the data values of the two nodes - node_1.data, node_2.data = node_2.data, node_1.data - - -if __name__ == "__main__": - """ - Python script that outputs the swap of nodes in a linked list. - """ - from doctest import testmod - - testmod() - linked_list = LinkedList() - for i in range(5, 0, -1): - linked_list.push(i) - - print(f"Original Linked List: {list(linked_list)}") - linked_list.swap_nodes(1, 4) - print(f"Modified Linked List: {list(linked_list)}") - print("After swapping the nodes whose data is 1 and 4.")+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: + """ + >>> linked_list = LinkedList() + >>> list(linked_list) + [] + >>> linked_list.push(0) + >>> tuple(linked_list) + (0,) + """ + node = self.head + while node: + yield node.data + node = node.next_node + + def __len__(self) -> int: + """ + >>> linked_list = LinkedList() + >>> len(linked_list) + 0 + >>> linked_list.push(0) + >>> len(linked_list) + 1 + """ + return sum(1 for _ in self) + + def push(self, new_data: Any) -> None: + """ + Add a new node with the given data to the beginning of the Linked List. + + Args: + new_data (Any): The data to be added to the new node. + + Returns: + None + + Examples: + >>> linked_list = LinkedList() + >>> linked_list.push(5) + >>> linked_list.push(4) + >>> linked_list.push(3) + >>> linked_list.push(2) + >>> linked_list.push(1) + >>> list(linked_list) + [1, 2, 3, 4, 5] + """ + new_node = Node(new_data) + new_node.next_node = self.head + self.head = new_node + + def swap_nodes(self, node_data_1: Any, node_data_2: Any) -> None: + """ + Swap the positions of two nodes in the Linked List based on their data values. + + Args: + node_data_1: Data value of the first node to be swapped. + node_data_2: Data value of the second node to be swapped. + + + Note: + If either of the specified data values isn't found then, no swapping occurs. + + Examples: + When both values are present in a linked list. + >>> linked_list = LinkedList() + >>> linked_list.push(5) + >>> linked_list.push(4) + >>> linked_list.push(3) + >>> linked_list.push(2) + >>> linked_list.push(1) + >>> list(linked_list) + [1, 2, 3, 4, 5] + >>> linked_list.swap_nodes(1, 5) + >>> tuple(linked_list) + (5, 2, 3, 4, 1) + + When one value is present and the other isn't in the linked list. + >>> second_list = LinkedList() + >>> second_list.push(6) + >>> second_list.push(7) + >>> second_list.push(8) + >>> second_list.push(9) + >>> second_list.swap_nodes(1, 6) is None + True + + When both values are absent in the linked list. + >>> second_list = LinkedList() + >>> second_list.push(10) + >>> second_list.push(9) + >>> second_list.push(8) + >>> second_list.push(7) + >>> second_list.swap_nodes(1, 3) is None + True + + When linkedlist is empty. + >>> second_list = LinkedList() + >>> second_list.swap_nodes(1, 3) is None + True + + Returns: + None + """ + if node_data_1 == node_data_2: + return + + node_1 = self.head + while node_1 and node_1.data != node_data_1: + node_1 = node_1.next_node + node_2 = self.head + while node_2 and node_2.data != node_data_2: + node_2 = node_2.next_node + if node_1 is None or node_2 is None: + return + # Swap the data values of the two nodes + node_1.data, node_2.data = node_2.data, node_1.data + + +if __name__ == "__main__": + """ + Python script that outputs the swap of nodes in a linked list. + """ + from doctest import testmod + + testmod() + linked_list = LinkedList() + for i in range(5, 0, -1): + linked_list.push(i) + + print(f"Original Linked List: {list(linked_list)}") + linked_list.swap_nodes(1, 4) + print(f"Modified Linked List: {list(linked_list)}") + print("After swapping the nodes whose data is 1 and 4.")
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: RandomizedHeapNode[T] | None = None self.right: RandomizedHeapNode[T] | None = None @property def value(self) -> T: return self._value @staticmethod def merge( root1: RandomizedHeapNode[T] | None, root2: RandomizedHeapNode[T] | None ) -> RandomizedHeapNode[T] | None: if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 if random.choice([True, False]): root1.left, root1.right = root1.right, root1.left root1.left = RandomizedHeapNode.merge(root1.left, root2) return root1 class RandomizedHeap[T: bool]: def __init__(self, data: Iterable[T] | None = ()) -> None: self._root: RandomizedHeapNode[T] | None = None if data: for item in data: self.insert(item) def insert(self, value: T) -> None: self._root = RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value)) def pop(self) -> T | None: result = self.top() if self._root is None: return None self._root = RandomizedHeapNode.merge(self._root.left, self._root.right) return result def top(self) -> T: if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: self._root = None def to_sorted_list(self) -> list[Any]: result = [] while self: result.append(self.pop()) return result def __bool__(self) -> bool: return self._root is not None if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: + """ + Return the value of the node. + + >>> rhn = RandomizedHeapNode(10) + >>> rhn.value + 10 + >>> rhn = RandomizedHeapNode(-10) + >>> rhn.value + -10 + """ return self._value @staticmethod def merge( root1: RandomizedHeapNode[T] | None, root2: RandomizedHeapNode[T] | None ) -> RandomizedHeapNode[T] | None: + """ + Merge 2 nodes together. + + >>> rhn1 = RandomizedHeapNode(10) + >>> rhn2 = RandomizedHeapNode(20) + >>> RandomizedHeapNode.merge(rhn1, rhn2).value + 10 + + >>> rhn1 = RandomizedHeapNode(20) + >>> rhn2 = RandomizedHeapNode(10) + >>> RandomizedHeapNode.merge(rhn1, rhn2).value + 10 + + >>> rhn1 = RandomizedHeapNode(5) + >>> rhn2 = RandomizedHeapNode(0) + >>> RandomizedHeapNode.merge(rhn1, rhn2).value + 0 + """ if not root1: return root2 @@ -42,8 +74,34 @@ class RandomizedHeap[T: bool]: + """ + A data structure that allows inserting a new value and to pop the smallest + values. Both operations take O(logN) time where N is the size of the + structure. + Wiki: https://en.wikipedia.org/wiki/Randomized_meldable_heap + + >>> RandomizedHeap([2, 3, 1, 5, 1, 7]).to_sorted_list() + [1, 1, 2, 3, 5, 7] + + >>> rh = RandomizedHeap() + >>> rh.pop() + Traceback (most recent call last): + ... + IndexError: Can't get top element for the empty heap. + + >>> rh.insert(1) + >>> rh.insert(-1) + >>> rh.insert(0) + >>> rh.to_sorted_list() + [-1, 0, 1] + """ def __init__(self, data: Iterable[T] | None = ()) -> None: + """ + >>> rh = RandomizedHeap([3, 1, 3, 7]) + >>> rh.to_sorted_list() + [1, 3, 3, 7] + """ self._root: RandomizedHeapNode[T] | None = None if data: @@ -51,9 +109,37 @@ self.insert(item) def insert(self, value: T) -> None: + """ + Insert the value into the heap. + + >>> rh = RandomizedHeap() + >>> rh.insert(3) + >>> rh.insert(1) + >>> rh.insert(3) + >>> rh.insert(7) + >>> rh.to_sorted_list() + [1, 3, 3, 7] + """ self._root = RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value)) def pop(self) -> T | None: + """ + Pop the smallest value from the heap and return it. + + >>> rh = RandomizedHeap([3, 1, 3, 7]) + >>> rh.pop() + 1 + >>> rh.pop() + 3 + >>> rh.pop() + 3 + >>> rh.pop() + 7 + >>> rh.pop() + Traceback (most recent call last): + ... + IndexError: Can't get top element for the empty heap. + """ result = self.top() @@ -65,14 +151,48 @@ return result def top(self) -> T: + """ + Return the smallest value from the heap. + + >>> rh = RandomizedHeap() + >>> rh.insert(3) + >>> rh.top() + 3 + >>> rh.insert(1) + >>> rh.top() + 1 + >>> rh.insert(3) + >>> rh.top() + 1 + >>> rh.insert(7) + >>> rh.top() + 1 + """ if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: + """ + Clear the heap. + + >>> rh = RandomizedHeap([3, 1, 3, 7]) + >>> rh.clear() + >>> rh.pop() + Traceback (most recent call last): + ... + IndexError: Can't get top element for the empty heap. + """ self._root = None def to_sorted_list(self) -> list[Any]: + """ + Returns sorted list containing all the values in the heap. + + >>> rh = RandomizedHeap([3, 1, 3, 7]) + >>> rh.to_sorted_list() + [1, 3, 3, 7] + """ result = [] while self: result.append(self.pop()) @@ -80,10 +200,23 @@ return result def __bool__(self) -> bool: + """ + Check if the heap is not empty. + + >>> rh = RandomizedHeap() + >>> bool(rh) + False + >>> rh.insert(1) + >>> bool(rh) + True + >>> rh.clear() + >>> bool(rh) + False + """ return self._root is not None if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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", "^": "RL", } def precedence(char: str) -> int: return PRECEDENCES.get(char, -1) def associativity(char: str) -> Literal["LR", "RL"]: return ASSOCIATIVITIES[char] def infix_to_postfix(expression_str: str) -> str: if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack: Stack[str] = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while True: if stack.is_empty(): stack.push(char) break char_precedence = precedence(char) tos_precedence = precedence(stack.peek()) if char_precedence > tos_precedence: stack.push(char) break if char_precedence < tos_precedence: postfix.append(stack.pop()) continue # Precedences are equal if associativity(char) == "RL": stack.push(char) break postfix.append(stack.pop()) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
--- +++ @@ -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 representing an operator's precedence, or + order of operation. + https://en.wikipedia.org/wiki/Order_of_operations + """ return PRECEDENCES.get(char, -1) def associativity(char: str) -> Literal["LR", "RL"]: + """ + Return the associativity of the operator `char`. + https://en.wikipedia.org/wiki/Operator_associativity + """ return ASSOCIATIVITIES[char] def infix_to_postfix(expression_str: str) -> str: + """ + >>> infix_to_postfix("(1*(2+3)+4))") + Traceback (most recent call last): + ... + ValueError: Mismatched parentheses + >>> infix_to_postfix("") + '' + >>> infix_to_postfix("3+2") + '3 2 +' + >>> infix_to_postfix("(3+4)*5-6") + '3 4 + 5 * 6 -' + >>> infix_to_postfix("(1+2)*3/4-5") + '1 2 + 3 * 4 / 5 -' + >>> infix_to_postfix("a+b*c+(d*e+f)*g") + 'a b c * + d e * f + g * +' + >>> infix_to_postfix("x^y/(5*z)+2") + 'x y ^ 5 z * / 2 +' + >>> infix_to_postfix("2^3^2") + '2 3 2 ^ ^' + """ if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack: Stack[str] = Stack() @@ -76,4 +110,4 @@ print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) - print("Postfix notation: " + infix_to_postfix(expression))+ print("Postfix notation: " + infix_to_postfix(expression))
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" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): return self._insert(self._header, element, self._header._next) def add_last(self, element): return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
--- +++ @@ -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)""" class _Node: __slots__ = "_data", "_next", "_prev" @@ -52,11 +61,25 @@ class LinkedDeque(_DoublyLinkedBase): def first(self): + """return first element + >>> d = LinkedDeque() + >>> d.add_first('A').first() + 'A' + >>> d.add_first('B').first() + 'B' + """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): + """return last element + >>> d = LinkedDeque() + >>> d.add_last('A').last() + 'A' + >>> d.add_last('B').last() + 'B' + """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data @@ -64,19 +87,57 @@ # DEque Insert Operations (At the front, At the end) def add_first(self, element): + """insertion in the front + >>> LinkedDeque().add_first('AV').first() + 'AV' + """ return self._insert(self._header, element, self._header._next) def add_last(self, element): + """insertion in the end + >>> LinkedDeque().add_last('B').last() + 'B' + """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): + """removal from the front + >>> d = LinkedDeque() + >>> d.is_empty() + True + >>> d.remove_first() + Traceback (most recent call last): + ... + IndexError: remove_first from empty list + >>> d.add_first('A') # doctest: +ELLIPSIS + <data_structures.linked_list.deque_doubly.LinkedDeque object at ... + >>> d.remove_first() + 'A' + >>> d.is_empty() + True + """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): + """removal in the end + >>> d = LinkedDeque() + >>> d.is_empty() + True + >>> d.remove_last() + Traceback (most recent call last): + ... + IndexError: remove_first from empty list + >>> d.add_first('A') # doctest: +ELLIPSIS + <data_structures.linked_list.deque_doubly.LinkedDeque object at ... + >>> d.remove_last() + 'A' + >>> d.is_empty() + True + """ if self.is_empty(): raise IndexError("remove_first from empty list") - return self._delete(self._trailer._prev)+ return self._delete(self._trailer._prev)
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 class KDNode: def __init__( self, point: list[float], left: KDNode | None = None, right: KDNode | None = None, ) -> None: self.point = point self.left = left self.right = right
--- +++ @@ -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 | None = None, right: KDNode | None = None, ) -> None: + """ + Initializes a KDNode with the given point and child nodes. + + Args: + point (list[float]): The point stored in this node. + left (Optional[KDNode]): The left child node. + right (Optional[KDNode]): The right child node. + """ self.point = point self.left = left - self.right = right+ self.right = right
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 self.right: SkewNode[T] | None = None @property def value(self) -> T: return self._value @staticmethod def merge( root1: SkewNode[T] | None, root2: SkewNode[T] | None ) -> SkewNode[T] | None: if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 result = root1 temp = root1.right result.right = root1.left result.left = SkewNode.merge(temp, root2) return result class SkewHeap[T: bool]: def __init__(self, data: Iterable[T] | None = ()) -> None: self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item) def __bool__(self) -> bool: return self._root is not None def __iter__(self) -> Iterator[T]: result: list[Any] = [] while self: result.append(self.pop()) # Pushing items back to the heap not to clear it. for item in result: self.insert(item) return iter(result) def insert(self, value: T) -> None: self._root = SkewNode.merge(self._root, SkewNode(value)) def pop(self) -> T | None: result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None ) return result def top(self) -> T: if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: self._root = None if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: + """ + Return the value of the node. + + >>> SkewNode(0).value + 0 + >>> SkewNode(3.14159).value + 3.14159 + >>> SkewNode("hello").value + 'hello' + >>> SkewNode(None).value + + >>> SkewNode(True).value + True + >>> SkewNode([]).value + [] + >>> SkewNode({}).value + {} + >>> SkewNode(set()).value + set() + >>> SkewNode(0.0).value + 0.0 + >>> SkewNode(-1e-10).value + -1e-10 + >>> SkewNode(10).value + 10 + >>> SkewNode(-10.5).value + -10.5 + >>> SkewNode().value + Traceback (most recent call last): + ... + TypeError: SkewNode.__init__() missing 1 required positional argument: 'value' + """ return self._value @staticmethod def merge( root1: SkewNode[T] | None, root2: SkewNode[T] | None ) -> SkewNode[T] | None: + """ + Merge 2 nodes together. + >>> SkewNode.merge(SkewNode(10),SkewNode(-10.5)).value + -10.5 + >>> SkewNode.merge(SkewNode(10),SkewNode(10.5)).value + 10 + >>> SkewNode.merge(SkewNode(10),SkewNode(10)).value + 10 + >>> SkewNode.merge(SkewNode(-100),SkewNode(-10.5)).value + -100 + """ if not root1: return root2 @@ -41,17 +88,64 @@ class SkewHeap[T: bool]: + """ + A data structure that allows inserting a new value and to pop the smallest + values. Both operations take O(logN) time where N is the size of the + structure. + Wiki: https://en.wikipedia.org/wiki/Skew_heap + Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html + + >>> list(SkewHeap([2, 3, 1, 5, 1, 7])) + [1, 1, 2, 3, 5, 7] + + >>> sh = SkewHeap() + >>> sh.pop() + Traceback (most recent call last): + ... + IndexError: Can't get top element for the empty heap. + + >>> sh.insert(1) + >>> sh.insert(-1) + >>> sh.insert(0) + >>> list(sh) + [-1, 0, 1] + """ def __init__(self, data: Iterable[T] | None = ()) -> None: + """ + >>> sh = SkewHeap([3, 1, 3, 7]) + >>> list(sh) + [1, 3, 3, 7] + """ self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item) def __bool__(self) -> bool: + """ + Check if the heap is not empty. + + >>> sh = SkewHeap() + >>> bool(sh) + False + >>> sh.insert(1) + >>> bool(sh) + True + >>> sh.clear() + >>> bool(sh) + False + """ return self._root is not None def __iter__(self) -> Iterator[T]: + """ + Returns sorted list containing all the values in the heap. + + >>> sh = SkewHeap([3, 1, 3, 7]) + >>> list(sh) + [1, 3, 3, 7] + """ result: list[Any] = [] while self: result.append(self.pop()) @@ -63,9 +157,37 @@ return iter(result) def insert(self, value: T) -> None: + """ + Insert the value into the heap. + + >>> sh = SkewHeap() + >>> sh.insert(3) + >>> sh.insert(1) + >>> sh.insert(3) + >>> sh.insert(7) + >>> list(sh) + [1, 3, 3, 7] + """ self._root = SkewNode.merge(self._root, SkewNode(value)) def pop(self) -> T | None: + """ + Pop the smallest value from the heap and return it. + + >>> sh = SkewHeap([3, 1, 3, 7]) + >>> sh.pop() + 1 + >>> sh.pop() + 3 + >>> sh.pop() + 3 + >>> sh.pop() + 7 + >>> sh.pop() + Traceback (most recent call last): + ... + IndexError: Can't get top element for the empty heap. + """ result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None @@ -74,15 +196,42 @@ return result def top(self) -> T: + """ + Return the smallest value from the heap. + + >>> sh = SkewHeap() + >>> sh.insert(3) + >>> sh.top() + 3 + >>> sh.insert(1) + >>> sh.top() + 1 + >>> sh.insert(3) + >>> sh.top() + 1 + >>> sh.insert(7) + >>> sh.top() + 1 + """ if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: + """ + Clear the heap. + + >>> sh = SkewHeap([3, 1, 3, 7]) + >>> sh.clear() + >>> sh.pop() + Traceback (most recent call last): + ... + IndexError: Can't get top element for the empty heap. + """ self._root = None if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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__(self) -> None: self.front: Node | None = None self.rear: Node | None = None def __iter__(self) -> Iterator[Any]: node = self.front while node: yield node.data node = node.next def __len__(self) -> int: return len(tuple(iter(self))) def __str__(self) -> str: return " <- ".join(str(item) for item in self) def is_empty(self) -> bool: return len(self) == 0 def put(self, item: Any) -> None: node = Node(item) if self.is_empty(): self.front = self.rear = node else: assert isinstance(self.rear, Node) self.rear.next = node self.rear = node def get(self) -> Any: if self.is_empty(): raise IndexError("dequeue from empty queue") assert isinstance(self.front, Node) node = self.front self.front = self.front.next if self.front is None: self.rear = None return node.data def clear(self) -> None: self.front = self.rear = None if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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.is_empty() + False + >>> queue.get() + 5 + >>> queue.put('algorithms') + >>> queue.get() + 9 + >>> queue.get() + 'python' + >>> queue.get() + 'algorithms' + >>> queue.is_empty() + True + >>> queue.get() + Traceback (most recent call last): + ... + IndexError: dequeue from empty queue + """ def __init__(self) -> None: self.front: Node | None = None @@ -27,15 +53,57 @@ node = node.next def __len__(self) -> int: + """ + >>> queue = LinkedQueue() + >>> for i in range(1, 6): + ... queue.put(i) + >>> len(queue) + 5 + >>> for i in range(1, 6): + ... assert len(queue) == 6 - i + ... _ = queue.get() + >>> len(queue) + 0 + """ return len(tuple(iter(self))) def __str__(self) -> str: + """ + >>> queue = LinkedQueue() + >>> for i in range(1, 4): + ... queue.put(i) + >>> queue.put("Python") + >>> queue.put(3.14) + >>> queue.put(True) + >>> str(queue) + '1 <- 2 <- 3 <- Python <- 3.14 <- True' + """ return " <- ".join(str(item) for item in self) def is_empty(self) -> bool: + """ + >>> queue = LinkedQueue() + >>> queue.is_empty() + True + >>> for i in range(1, 6): + ... queue.put(i) + >>> queue.is_empty() + False + """ return len(self) == 0 def put(self, item: Any) -> None: + """ + >>> queue = LinkedQueue() + >>> queue.get() + Traceback (most recent call last): + ... + IndexError: dequeue from empty queue + >>> for i in range(1, 6): + ... queue.put(i) + >>> str(queue) + '1 <- 2 <- 3 <- 4 <- 5' + """ node = Node(item) if self.is_empty(): self.front = self.rear = node @@ -45,6 +113,20 @@ self.rear = node def get(self) -> Any: + """ + >>> queue = LinkedQueue() + >>> queue.get() + Traceback (most recent call last): + ... + IndexError: dequeue from empty queue + >>> queue = LinkedQueue() + >>> for i in range(1, 6): + ... queue.put(i) + >>> for i in range(1, 6): + ... assert queue.get() == i + >>> len(queue) + 0 + """ if self.is_empty(): raise IndexError("dequeue from empty queue") assert isinstance(self.front, Node) @@ -55,10 +137,20 @@ return node.data def clear(self) -> None: + """ + >>> queue = LinkedQueue() + >>> for i in range(1, 6): + ... queue.put(i) + >>> queue.clear() + >>> len(queue) + 0 + >>> str(queue) + '' + """ self.front = self.rear = None if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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__(self, head): self.current = head def __iter__(self): return self def __next__(self): if not self.current: raise StopIteration else: value = self.current.data self.current = self.current.next return value @dataclass class LinkedList: head: Node | None = None # First node in list tail: Node | None = None # Last node in list def __str__(self): current = self.head nodes = [] while current is not None: nodes.append(current.data) current = current.next return " ".join(str(node) for node in nodes) def __contains__(self, value: DataType): current = self.head while current: if current.data == value: return True current = current.next return False def __iter__(self): return LinkedListIterator(self.head) def get_head_data(self): if self.head: return self.head.data return None def get_tail_data(self): if self.tail: return self.tail.data return None def set_head(self, node: Node) -> None: if self.head is None: self.head = node self.tail = node else: self.insert_before_node(self.head, node) def set_tail(self, node: Node) -> None: if self.tail is None: self.head = node self.tail = node else: self.insert_after_node(self.tail, node) def insert(self, value: DataType) -> None: node = Node(value) if self.head is None: self.set_head(node) else: self.set_tail(node) def insert_before_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.next = node node_to_insert.previous = node.previous if node.previous is None: self.head = node_to_insert else: node.previous.next = node_to_insert node.previous = node_to_insert def insert_after_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.previous = node node_to_insert.next = node.next if node.next is None: self.tail = node_to_insert else: node.next.previous = node_to_insert node.next = node_to_insert def insert_at_position(self, position: int, value: DataType) -> None: current_position = 1 new_node = Node(value) node = self.head while node: if current_position == position: self.insert_before_node(node, new_node) return current_position += 1 node = node.next self.set_tail(new_node) def get_node(self, item: DataType) -> Node: node = self.head while node: if node.data == item: return node node = node.next raise Exception("Node not found") def delete_value(self, value): if (node := self.get_node(value)) is not None: if node == self.head: self.head = self.head.next if node == self.tail: self.tail = self.tail.previous self.remove_node_pointers(node) @staticmethod def remove_node_pointers(node: Node) -> None: if node.next: node.next.previous = node.previous if node.previous: node.previous.next = node.next node.next = None node.previous = None def is_empty(self): return self.head is None def create_linked_list() -> None: if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 pointer, typically called previous + pointer, together with next pointer and data which are there in singly linked list. + - Advantages over SLL - It can be traversed in both forward and backward direction. + Delete operation is more efficient +""" from dataclasses import dataclass from typing import Self, TypeVar @@ -154,9 +164,100 @@ def create_linked_list() -> None: + """ + >>> new_linked_list = LinkedList() + >>> new_linked_list.get_head_data() is None + True + >>> new_linked_list.get_tail_data() is None + True + >>> new_linked_list.is_empty() + True + >>> new_linked_list.insert(10) + >>> new_linked_list.get_head_data() + 10 + >>> new_linked_list.get_tail_data() + 10 + >>> new_linked_list.insert_at_position(position=3, value=20) + >>> new_linked_list.get_head_data() + 10 + >>> new_linked_list.get_tail_data() + 20 + >>> new_linked_list.set_head(Node(1000)) + >>> new_linked_list.get_head_data() + 1000 + >>> new_linked_list.get_tail_data() + 20 + >>> new_linked_list.set_tail(Node(2000)) + >>> new_linked_list.get_head_data() + 1000 + >>> new_linked_list.get_tail_data() + 2000 + >>> for value in new_linked_list: + ... print(value) + 1000 + 10 + 20 + 2000 + >>> new_linked_list.is_empty() + False + >>> for value in new_linked_list: + ... print(value) + 1000 + 10 + 20 + 2000 + >>> 10 in new_linked_list + True + >>> new_linked_list.delete_value(value=10) + >>> 10 in new_linked_list + False + >>> new_linked_list.delete_value(value=2000) + >>> new_linked_list.get_tail_data() + 20 + >>> new_linked_list.delete_value(value=1000) + >>> new_linked_list.get_tail_data() + 20 + >>> new_linked_list.get_head_data() + 20 + >>> for value in new_linked_list: + ... print(value) + 20 + >>> new_linked_list.delete_value(value=20) + >>> for value in new_linked_list: + ... print(value) + >>> for value in range(1,10): + ... new_linked_list.insert(value=value) + >>> for value in new_linked_list: + ... print(value) + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + >>> linked_list = LinkedList() + >>> linked_list.insert_at_position(position=1, value=10) + >>> str(linked_list) + '10' + >>> linked_list.insert_at_position(position=2, value=20) + >>> str(linked_list) + '10 20' + >>> linked_list.insert_at_position(position=1, value=30) + >>> str(linked_list) + '30 10 20' + >>> linked_list.insert_at_position(position=3, value=40) + >>> str(linked_list) + '30 10 40 20' + >>> linked_list.insert_at_position(position=5, value=50) + >>> str(linked_list) + '30 10 40 20 50' + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 = self.head while node: yield node.data node = node.next def __str__(self): return "->".join([str(item) for item in self]) def __len__(self): return sum(1 for _ in self) def insert_at_head(self, data): self.insert_at_nth(0, data) def insert_at_tail(self, data): self.insert_at_nth(len(self), data) def insert_at_nth(self, index: int, data): length = len(self) if not 0 <= index <= length: raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = self.tail = new_node elif index == 0: self.head.previous = new_node new_node.next = self.head self.head = new_node elif index == length: self.tail.next = new_node new_node.previous = self.tail self.tail = new_node else: temp = self.head for _ in range(index): temp = temp.next temp.previous.next = new_node new_node.previous = temp.previous new_node.next = temp temp.previous = new_node def delete_head(self): return self.delete_at_nth(0) def delete_tail(self): return self.delete_at_nth(len(self) - 1) def delete_at_nth(self, index: int): length = len(self) if not 0 <= index <= length - 1: raise IndexError("list index out of range") delete_node = self.head # default first node if length == 1: self.head = self.tail = None elif index == 0: self.head = self.head.next self.head.previous = None elif index == length - 1: delete_node = self.tail self.tail = self.tail.previous self.tail.next = None else: temp = self.head for _ in range(index): temp = temp.next delete_node = temp temp.next.previous = temp.previous temp.previous.next = temp.next return delete_node.data def delete(self, data) -> str: current = self.head while current.data != data: # Find the position to delete if current.next: current = current.next else: # We have reached the end an no value matches raise ValueError("No data matching given value") if current == self.head: self.delete_head() elif current == self.tail: self.delete_tail() else: # Before: 1 <--> 2(current) <--> 3 current.previous.next = current.next # 1 --> 3 current.next.previous = current.previous # 1 <--> 3 return data def is_empty(self): return len(self) == 0 def test_doubly_linked_list() -> None: linked_list = DoublyLinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_at_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_at_head(0) linked_list.insert_at_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(12)) assert linked_list.delete_head() == 0 assert linked_list.delete_at_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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') + >>> linked_list.insert_at_tail('c') + >>> tuple(linked_list) + ('a', 'b', 'c') + """ node = self.head while node: yield node.data node = node.next def __str__(self): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.insert_at_tail('a') + >>> linked_list.insert_at_tail('b') + >>> linked_list.insert_at_tail('c') + >>> str(linked_list) + 'a->b->c' + """ return "->".join([str(item) for item in self]) def __len__(self): + """ + >>> linked_list = DoublyLinkedList() + >>> for i in range(0, 5): + ... linked_list.insert_at_nth(i, i + 1) + >>> len(linked_list) == 5 + True + """ return sum(1 for _ in self) def insert_at_head(self, data): @@ -34,6 +60,27 @@ self.insert_at_nth(len(self), data) def insert_at_nth(self, index: int, data): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.insert_at_nth(-1, 666) + Traceback (most recent call last): + .... + IndexError: list index out of range + >>> linked_list.insert_at_nth(1, 666) + Traceback (most recent call last): + .... + IndexError: list index out of range + >>> linked_list.insert_at_nth(0, 2) + >>> linked_list.insert_at_nth(0, 1) + >>> linked_list.insert_at_nth(2, 4) + >>> linked_list.insert_at_nth(2, 3) + >>> str(linked_list) + '1->2->3->4' + >>> linked_list.insert_at_nth(5, 5) + Traceback (most recent call last): + .... + IndexError: list index out of range + """ length = len(self) if not 0 <= index <= length: @@ -65,6 +112,27 @@ return self.delete_at_nth(len(self) - 1) def delete_at_nth(self, index: int): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.delete_at_nth(0) + Traceback (most recent call last): + .... + IndexError: list index out of range + >>> for i in range(0, 5): + ... linked_list.insert_at_nth(i, i + 1) + >>> linked_list.delete_at_nth(0) == 1 + True + >>> linked_list.delete_at_nth(3) == 5 + True + >>> linked_list.delete_at_nth(1) == 3 + True + >>> str(linked_list) + '2->4' + >>> linked_list.delete_at_nth(2) + Traceback (most recent call last): + .... + IndexError: list index out of range + """ length = len(self) if not 0 <= index <= length - 1: @@ -109,10 +177,21 @@ return data def is_empty(self): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.is_empty() + True + >>> linked_list.insert_at_tail(1) + >>> linked_list.is_empty() + False + """ return len(self) == 0 def test_doubly_linked_list() -> None: + """ + >>> test_doubly_linked_list() + """ linked_list = DoublyLinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" @@ -148,4 +227,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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 = head.next_node print(head.data) def insert_node(head: Node | None, data: int) -> Node: new_node = Node(data) # If the linked list is empty, the new_node becomes the head if head is None: return new_node temp_node = head while temp_node.next_node: temp_node = temp_node.next_node temp_node.next_node = new_node return head def rotate_to_the_right(head: Node, places: int) -> Node: # Check if the list is empty or has only one element if not head: raise ValueError("The linked list is empty.") if head.next_node is None: return head # Calculate the length of the linked list length = 1 temp_node = head while temp_node.next_node is not None: length += 1 temp_node = temp_node.next_node # Adjust the value of places to avoid places longer than the list. places %= length if places == 0: return head # As no rotation is needed. # Find the new head position after rotation. new_head_index = length - places # Traverse to the new head position temp_node = head for _ in range(new_head_index - 1): assert temp_node.next_node temp_node = temp_node.next_node # Update pointers to perform rotation assert temp_node.next_node new_head = temp_node.next_node temp_node.next_node = None temp_node = new_head while temp_node.next_node: temp_node = temp_node.next_node temp_node.next_node = head assert new_head return new_head if __name__ == "__main__": import doctest doctest.testmod() head = insert_node(None, 5) head = insert_node(head, 1) head = insert_node(head, 2) head = insert_node(head, 4) head = insert_node(head, 3) print("Original list: ", end="") print_linked_list(head) places = 3 new_head = rotate_to_the_right(head, places) print(f"After {places} iterations: ", end="") print_linked_list(new_head)
--- +++ @@ -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, + or None if the linked list is empty. + + >>> head = insert_node(None, 0) + >>> head = insert_node(head, 2) + >>> head = insert_node(head, 1) + >>> print_linked_list(head) + 0->2->1 + >>> head = insert_node(head, 4) + >>> head = insert_node(head, 5) + >>> print_linked_list(head) + 0->2->1->4->5 + """ if head is None: return while head.next_node is not None: @@ -19,6 +38,22 @@ def insert_node(head: Node | None, data: int) -> Node: + """ + Insert a new node at the end of a linked list and return the new head. + + Parameters: + head (Node | None): The head of the linked list. + data (int): The data to be inserted into the new node. + + Returns: + Node: The new head of the linked list. + + >>> head = insert_node(None, 10) + >>> head = insert_node(head, 9) + >>> head = insert_node(head, 8) + >>> print_linked_list(head) + 10->9->8 + """ new_node = Node(data) # If the linked list is empty, the new_node becomes the head if head is None: @@ -33,6 +68,32 @@ def rotate_to_the_right(head: Node, places: int) -> Node: + """ + Rotate a linked list to the right by places times. + + Parameters: + head: The head of the linked list. + places: The number of places to rotate. + + Returns: + Node: The head of the rotated linked list. + + >>> rotate_to_the_right(None, places=1) + Traceback (most recent call last): + ... + ValueError: The linked list is empty. + >>> head = insert_node(None, 1) + >>> rotate_to_the_right(head, places=1) == head + True + >>> head = insert_node(None, 1) + >>> head = insert_node(head, 2) + >>> head = insert_node(head, 3) + >>> head = insert_node(head, 4) + >>> head = insert_node(head, 5) + >>> new_head = rotate_to_the_right(head, places=2) + >>> print_linked_list(new_head) + 4->5->1->2->3 + """ # Check if the list is empty or has only one element if not head: raise ValueError("The linked list is empty.") @@ -92,4 +153,4 @@ new_head = rotate_to_the_right(head, places) print(f"After {places} iterations: ", end="") - print_linked_list(new_head)+ print_linked_list(new_head)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/data_structures/linked_list/rotate_to_the_right.py