diff --git a/arithmetic_analysis/newton_method.py b/arithmetic_analysis/newton_method.py index 542f994aa..97d5d3d3e 100644 --- a/arithmetic_analysis/newton_method.py +++ b/arithmetic_analysis/newton_method.py @@ -7,7 +7,11 @@ RealFunc = Callable[[float], float] # type alias for a real -> real function # function is the f(x) and derivative is the f'(x) -def newton(function: RealFunc, derivative: RealFunc, starting_int: int,) -> float: +def newton( + function: RealFunc, + derivative: RealFunc, + starting_int: int, +) -> float: """ >>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3) 2.0945514815423474 diff --git a/arithmetic_analysis/newton_raphson.py b/arithmetic_analysis/newton_raphson.py index 890cff060..948759a09 100644 --- a/arithmetic_analysis/newton_raphson.py +++ b/arithmetic_analysis/newton_raphson.py @@ -9,7 +9,7 @@ from sympy import diff def newton_raphson(func: str, a: int, precision: int = 10 ** -10) -> float: - """ Finds root from the point 'a' onwards by Newton-Raphson method + """Finds root from the point 'a' onwards by Newton-Raphson method >>> newton_raphson("sin(x)", 2) 3.1415926536808043 >>> newton_raphson("x**2 - 5*x +2", 0.4) diff --git a/backtracking/all_permutations.py b/backtracking/all_permutations.py index d14443603..5244fef97 100644 --- a/backtracking/all_permutations.py +++ b/backtracking/all_permutations.py @@ -13,10 +13,10 @@ def generate_all_permutations(sequence): def create_state_space_tree(sequence, current_sequence, index, index_used): """ - Creates a state space tree to iterate through each branch using DFS. - We know that each state has exactly len(sequence) - index children. - It terminates when it reaches the end of the given sequence. - """ + Creates a state space tree to iterate through each branch using DFS. + We know that each state has exactly len(sequence) - index children. + It terminates when it reaches the end of the given sequence. + """ if index == len(sequence): print(current_sequence) diff --git a/backtracking/all_subsequences.py b/backtracking/all_subsequences.py index 828338699..3851c4ab0 100644 --- a/backtracking/all_subsequences.py +++ b/backtracking/all_subsequences.py @@ -13,10 +13,10 @@ def generate_all_subsequences(sequence): def create_state_space_tree(sequence, current_subsequence, index): """ - Creates a state space tree to iterate through each branch using DFS. - We know that each state has exactly two children. - It terminates when it reaches the end of the given sequence. - """ + Creates a state space tree to iterate through each branch using DFS. + We know that each state has exactly two children. + It terminates when it reaches the end of the given sequence. + """ if index == len(sequence): print(current_subsequence) diff --git a/backtracking/sudoku.py b/backtracking/sudoku.py index d864e2823..b3d38b4cc 100644 --- a/backtracking/sudoku.py +++ b/backtracking/sudoku.py @@ -105,7 +105,7 @@ def sudoku(grid): [7, 4, 5, 2, 8, 6, 3, 1, 9]] >>> sudoku(no_solution) False - """ + """ if is_completed(grid): return grid diff --git a/backtracking/sum_of_subsets.py b/backtracking/sum_of_subsets.py index c03df18ae..425ddcff9 100644 --- a/backtracking/sum_of_subsets.py +++ b/backtracking/sum_of_subsets.py @@ -19,13 +19,13 @@ def generate_sum_of_subsets_soln(nums, max_sum): def create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum): """ - Creates a state space tree to iterate through each branch using DFS. - It terminates the branching of a node when any of the two conditions - given below satisfy. - This algorithm follows depth-fist-search and backtracks when the node is not - branchable. + Creates a state space tree to iterate through each branch using DFS. + It terminates the branching of a node when any of the two conditions + given below satisfy. + This algorithm follows depth-fist-search and backtracks when the node is not + branchable. - """ + """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: diff --git a/blockchain/modular_division.py b/blockchain/modular_division.py index c09863a3c..8fcf6e37c 100644 --- a/blockchain/modular_division.py +++ b/blockchain/modular_division.py @@ -74,13 +74,13 @@ def modular_division2(a, b, n): def extended_gcd(a, b): """ - >>> extended_gcd(10, 6) - (2, -1, 2) + >>> extended_gcd(10, 6) + (2, -1, 2) - >>> extended_gcd(7, 5) - (1, -2, 3) + >>> extended_gcd(7, 5) + (1, -2, 3) - ** extended_gcd function is used when d = gcd(a,b) is required in output + ** extended_gcd function is used when d = gcd(a,b) is required in output """ assert a >= 0 and b >= 0 diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index 4c79e1c2f..0fbe97284 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -17,26 +17,50 @@ Created by TrapinchO # used alphabet -------------------------- # from string.ascii_uppercase -abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # -------------------------- default selection -------------------------- # rotors -------------------------- -rotor1 = 'EGZWVONAHDCLFQMSIPJBYUKXTR' -rotor2 = 'FOBHMDKEXQNRAULPGSJVTYICZW' -rotor3 = 'ZJXESIUQLHAVRMDOYGTNFWPBKC' +rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR" +rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW" +rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC" # reflector -------------------------- -reflector = {'A': 'N', 'N': 'A', 'B': 'O', 'O': 'B', 'C': 'P', 'P': 'C', 'D': 'Q', - 'Q': 'D', 'E': 'R', 'R': 'E', 'F': 'S', 'S': 'F', 'G': 'T', 'T': 'G', - 'H': 'U', 'U': 'H', 'I': 'V', 'V': 'I', 'J': 'W', 'W': 'J', 'K': 'X', - 'X': 'K', 'L': 'Y', 'Y': 'L', 'M': 'Z', 'Z': 'M'} +reflector = { + "A": "N", + "N": "A", + "B": "O", + "O": "B", + "C": "P", + "P": "C", + "D": "Q", + "Q": "D", + "E": "R", + "R": "E", + "F": "S", + "S": "F", + "G": "T", + "T": "G", + "H": "U", + "U": "H", + "I": "V", + "V": "I", + "J": "W", + "W": "J", + "K": "X", + "X": "K", + "L": "Y", + "Y": "L", + "M": "Z", + "Z": "M", +} # -------------------------- extra rotors -------------------------- -rotor4 = 'RMDJXFUWGISLHVTCQNKYPBEZOA' -rotor5 = 'SGLCPQWZHKXAREONTFBVIYJUDM' -rotor6 = 'HVSICLTYKQUBXDWAJZOMFGPREN' -rotor7 = 'RZWQHFMVDBKICJLNTUXAGYPSOE' -rotor8 = 'LFKIJODBEGAMQPXVUHYSTCZRWN' -rotor9 = 'KOAEGVDHXPQZMLFTYWJNBRCIUS' +rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA" +rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM" +rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN" +rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE" +rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN" +rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple: @@ -57,19 +81,22 @@ def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple: unique_rotsel = len(set(rotsel)) if unique_rotsel < 3: - raise Exception(f'Please use 3 unique rotors (not {unique_rotsel})') + raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})") # Checks if rotor positions are valid rotorpos1, rotorpos2, rotorpos3 = rotpos if not 0 < rotorpos1 <= len(abc): - raise ValueError(f'First rotor position is not within range of 1..26 (' - f'{rotorpos1}') + raise ValueError( + f"First rotor position is not within range of 1..26 (" f"{rotorpos1}" + ) if not 0 < rotorpos2 <= len(abc): - raise ValueError(f'Second rotor position is not within range of 1..26 (' - f'{rotorpos2})') + raise ValueError( + f"Second rotor position is not within range of 1..26 (" f"{rotorpos2})" + ) if not 0 < rotorpos3 <= len(abc): - raise ValueError(f'Third rotor position is not within range of 1..26 (' - f'{rotorpos3})') + raise ValueError( + f"Third rotor position is not within range of 1..26 (" f"{rotorpos3})" + ) # Validates string and returns dict pb = _plugboard(pb) @@ -97,21 +124,21 @@ def _plugboard(pbstring: str) -> dict: # a) is type string # b) has even length (so pairs can be made) if not isinstance(pbstring, str): - raise TypeError(f'Plugboard setting isn\'t type string ({type(pbstring)})') + raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})") elif len(pbstring) % 2 != 0: - raise Exception(f'Odd number of symbols ({len(pbstring)})') - elif pbstring == '': + raise Exception(f"Odd number of symbols ({len(pbstring)})") + elif pbstring == "": return {} - pbstring.replace(' ', '') + pbstring.replace(" ", "") # Checks if all characters are unique tmppbl = set() for i in pbstring: if i not in abc: - raise Exception(f'\'{i}\' not in list of symbols') + raise Exception(f"'{i}' not in list of symbols") elif i in tmppbl: - raise Exception(f'Duplicate symbol ({i})') + raise Exception(f"Duplicate symbol ({i})") else: tmppbl.add(i) del tmppbl @@ -125,8 +152,12 @@ def _plugboard(pbstring: str) -> dict: return pb -def enigma(text: str, rotor_position: tuple, - rotor_selection: tuple = (rotor1, rotor2, rotor3), plugb: str = '') -> str: +def enigma( + text: str, + rotor_position: tuple, + rotor_selection: tuple = (rotor1, rotor2, rotor3), + plugb: str = "", +) -> str: """ The only difference with real-world enigma is that I allowed string input. All characters are converted to uppercase. (non-letter symbol are ignored) @@ -179,7 +210,8 @@ def enigma(text: str, rotor_position: tuple, text = text.upper() rotor_position, rotor_selection, plugboard = _validator( - rotor_position, rotor_selection, plugb.upper()) + rotor_position, rotor_selection, plugb.upper() + ) rotorpos1, rotorpos2, rotorpos3 = rotor_position rotor1, rotor2, rotor3 = rotor_selection @@ -245,12 +277,12 @@ def enigma(text: str, rotor_position: tuple, return "".join(result) -if __name__ == '__main__': - message = 'This is my Python script that emulates the Enigma machine from WWII.' +if __name__ == "__main__": + message = "This is my Python script that emulates the Enigma machine from WWII." rotor_pos = (1, 1, 1) - pb = 'pictures' + pb = "pictures" rotor_sel = (rotor2, rotor4, rotor8) en = enigma(message, rotor_pos, rotor_sel, pb) - print('Encrypted message:', en) - print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb)) + print("Encrypted message:", en) + print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb)) diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index 0fcfbb0b9..3b045fdac 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -21,20 +21,20 @@ class XORCipher: def __init__(self, key=0): """ - simple constructor that receives a key or uses - default key = 0 - """ + simple constructor that receives a key or uses + default key = 0 + """ # private field self.__key = key def encrypt(self, content, key): """ - 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 - """ + 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 + """ # precondition assert isinstance(key, int) and isinstance(content, str) @@ -55,11 +55,11 @@ class XORCipher: def decrypt(self, content, key): """ - 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 - """ + 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 + """ # precondition assert isinstance(key, int) and isinstance(content, list) @@ -80,11 +80,11 @@ class XORCipher: def encrypt_string(self, content, key=0): """ - 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 - """ + 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 + """ # precondition assert isinstance(key, int) and isinstance(content, str) @@ -105,11 +105,11 @@ class XORCipher: def decrypt_string(self, content, key=0): """ - 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 - """ + 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 + """ # precondition assert isinstance(key, int) and isinstance(content, str) @@ -130,12 +130,12 @@ class XORCipher: def encrypt_file(self, file, key=0): """ - 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 - """ + 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) and isinstance(key, int) @@ -155,12 +155,12 @@ class XORCipher: def decrypt_file(self, file, key): """ - 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 - """ + 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) and isinstance(key, int) diff --git a/conversions/decimal_to_any.py b/conversions/decimal_to_any.py index cbed1ac12..3c72a7732 100644 --- a/conversions/decimal_to_any.py +++ b/conversions/decimal_to_any.py @@ -3,55 +3,55 @@ 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 + 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") diff --git a/conversions/decimal_to_binary.py b/conversions/decimal_to_binary.py index 8fcf226c3..7e83aee4f 100644 --- a/conversions/decimal_to_binary.py +++ b/conversions/decimal_to_binary.py @@ -4,28 +4,28 @@ def decimal_to_binary(num: int) -> str: """ - Convert an Integer Decimal Number to a Binary Number as str. - >>> decimal_to_binary(0) - '0b0' - >>> decimal_to_binary(2) - '0b10' - >>> decimal_to_binary(7) - '0b111' - >>> decimal_to_binary(35) - '0b100011' - >>> # negatives work too - >>> decimal_to_binary(-2) - '-0b10' - >>> # other floats will error - >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS - Traceback (most recent call last): - ... - TypeError: 'float' object cannot be interpreted as an integer - >>> # strings will error as well - >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS - Traceback (most recent call last): - ... - TypeError: 'str' object cannot be interpreted as an integer + Convert an Integer Decimal Number to a Binary Number as str. + >>> decimal_to_binary(0) + '0b0' + >>> decimal_to_binary(2) + '0b10' + >>> decimal_to_binary(7) + '0b111' + >>> decimal_to_binary(35) + '0b100011' + >>> # negatives work too + >>> decimal_to_binary(-2) + '-0b10' + >>> # other floats will error + >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'float' object cannot be interpreted as an integer + >>> # strings will error as well + >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'str' object cannot be interpreted as an integer """ if type(num) == float: diff --git a/conversions/decimal_to_hexadecimal.py b/conversions/decimal_to_hexadecimal.py index 6bd9533ab..433f78dfe 100644 --- a/conversions/decimal_to_hexadecimal.py +++ b/conversions/decimal_to_hexadecimal.py @@ -23,39 +23,39 @@ values = { def decimal_to_hexadecimal(decimal): """ - 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 + 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 type(decimal) in (int, float) and decimal == int(decimal) hexadecimal = "" diff --git a/data_structures/binary_tree/avl_tree.py b/data_structures/binary_tree/avl_tree.py index c6a45f1cb..3362610b9 100644 --- a/data_structures/binary_tree/avl_tree.py +++ b/data_structures/binary_tree/avl_tree.py @@ -109,7 +109,7 @@ def right_rotation(node): def left_rotation(node): """ - a mirror symmetry rotation of the left_rotation + a mirror symmetry rotation of the left_rotation """ print("right rotation node:", node.get_data()) ret = node.get_right() diff --git a/data_structures/binary_tree/red_black_tree.py b/data_structures/binary_tree/red_black_tree.py index 379cee61d..5d721edfa 100644 --- a/data_structures/binary_tree/red_black_tree.py +++ b/data_structures/binary_tree/red_black_tree.py @@ -28,11 +28,11 @@ class RedBlackTree: right: Optional["RedBlackTree"] = 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 + 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 diff --git a/data_structures/binary_tree/treap.py b/data_structures/binary_tree/treap.py index 52b757d58..fbb576502 100644 --- a/data_structures/binary_tree/treap.py +++ b/data_structures/binary_tree/treap.py @@ -118,7 +118,7 @@ def inorder(root: Node): return else: inorder(root.left) - print(root.value, end=" ") + print(root.value, end=",") inorder(root.right) @@ -130,19 +130,19 @@ def interactTreap(root, args): >>> root = interactTreap(None, "+1") >>> inorder(root) - 1 + 1, >>> root = interactTreap(root, "+3 +5 +17 +19 +2 +16 +4 +0") >>> inorder(root) - 0 1 2 3 4 5 16 17 19 + 0,1,2,3,4,5,16,17,19, >>> root = interactTreap(root, "+4 +4 +4") >>> inorder(root) - 0 1 2 3 4 4 4 4 5 16 17 19 + 0,1,2,3,4,4,4,4,5,16,17,19, >>> root = interactTreap(root, "-0") >>> inorder(root) - 1 2 3 4 4 4 4 5 16 17 19 + 1,2,3,4,4,4,4,5,16,17,19, >>> root = interactTreap(root, "-4") >>> inorder(root) - 1 2 3 5 16 17 19 + 1,2,3,5,16,17,19, >>> root = interactTreap(root, "=0") Unknown command """ diff --git a/data_structures/hashing/double_hash.py b/data_structures/hashing/double_hash.py index 9c6c8fed6..1007849c5 100644 --- a/data_structures/hashing/double_hash.py +++ b/data_structures/hashing/double_hash.py @@ -5,7 +5,7 @@ from number_theory.prime_numbers import check_prime, next_prime class DoubleHash(HashTable): """ - Hash Table example with open addressing and Double Hash + Hash Table example with open addressing and Double Hash """ def __init__(self, *args, **kwargs): diff --git a/data_structures/hashing/hash_table.py b/data_structures/hashing/hash_table.py index 3b39742f9..6e03be95b 100644 --- a/data_structures/hashing/hash_table.py +++ b/data_structures/hashing/hash_table.py @@ -4,7 +4,7 @@ from number_theory.prime_numbers import next_prime class HashTable: """ - Basic Hash Table example with open addressing and linear probing + Basic Hash Table example with open addressing and linear probing """ def __init__(self, size_table, charge_factor=None, lim_charge=None): diff --git a/data_structures/hashing/number_theory/prime_numbers.py b/data_structures/hashing/number_theory/prime_numbers.py index 2a966e0da..db4d40f47 100644 --- a/data_structures/hashing/number_theory/prime_numbers.py +++ b/data_structures/hashing/number_theory/prime_numbers.py @@ -6,8 +6,8 @@ def check_prime(number): """ - it's not the best solution - """ + it's not the best solution + """ special_non_primes = [0, 1, 2] if number in special_non_primes[:2]: return 2 diff --git a/data_structures/hashing/quadratic_probing.py b/data_structures/hashing/quadratic_probing.py index 668ddaa85..06f3ced49 100644 --- a/data_structures/hashing/quadratic_probing.py +++ b/data_structures/hashing/quadratic_probing.py @@ -5,7 +5,7 @@ from hash_table import HashTable class QuadraticProbing(HashTable): """ - Basic Hash Table example with open addressing using Quadratic Probing + Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): diff --git a/data_structures/linked_list/deque_doubly.py b/data_structures/linked_list/deque_doubly.py index 7025a7ea2..c6ee2ed27 100644 --- a/data_structures/linked_list/deque_doubly.py +++ b/data_structures/linked_list/deque_doubly.py @@ -61,7 +61,7 @@ class _DoublyLinkedBase: class LinkedDeque(_DoublyLinkedBase): def first(self): - """ return first element + """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' @@ -73,7 +73,7 @@ class LinkedDeque(_DoublyLinkedBase): return self._header._next._data def last(self): - """ return last element + """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' @@ -87,14 +87,14 @@ class LinkedDeque(_DoublyLinkedBase): # DEque Insert Operations (At the front, At the end) def add_first(self, element): - """ insertion in the front + """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 + """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ @@ -103,7 +103,7 @@ class LinkedDeque(_DoublyLinkedBase): # DEqueu Remove Operations (At the front, At the end) def remove_first(self): - """ removal from the front + """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True @@ -123,7 +123,7 @@ class LinkedDeque(_DoublyLinkedBase): return self._delete(self._header._next) def remove_last(self): - """ removal in the end + """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True diff --git a/data_structures/stacks/infix_to_postfix_conversion.py b/data_structures/stacks/infix_to_postfix_conversion.py index 611144023..4a1180c9d 100644 --- a/data_structures/stacks/infix_to_postfix_conversion.py +++ b/data_structures/stacks/infix_to_postfix_conversion.py @@ -10,7 +10,7 @@ def is_operand(char): def precedence(char): - """ Return integer value representing an operator's precedence, or + """Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations @@ -20,7 +20,7 @@ def precedence(char): def infix_to_postfix(expression): - """ Convert infix notation to postfix notation using the Shunting-yard + """Convert infix notation to postfix notation using the Shunting-yard algorithm. https://en.wikipedia.org/wiki/Shunting-yard_algorithm diff --git a/data_structures/stacks/stack.py b/data_structures/stacks/stack.py index baa0857ee..a4bcb5bea 100644 --- a/data_structures/stacks/stack.py +++ b/data_structures/stacks/stack.py @@ -2,7 +2,7 @@ __author__ = "Omkar Pathak" class Stack: - """ A stack is an abstract data type that serves as a collection of + """A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are diff --git a/digital_image_processing/index_calculation.py b/digital_image_processing/index_calculation.py index d55815a6e..4350b8603 100644 --- a/digital_image_processing/index_calculation.py +++ b/digital_image_processing/index_calculation.py @@ -10,98 +10,98 @@ import numpy as np # Class implemented to calculus the index class IndexCalculation: """ - # Class Summary - This algorithm consists in calculating vegetation indices, these - indices can be used for precision agriculture for example (or remote - sensing). There are functions to define the data and to calculate the - implemented indices. + # Class Summary + This algorithm consists in calculating vegetation indices, these + indices can be used for precision agriculture for example (or remote + sensing). There are functions to define the data and to calculate the + implemented indices. - # Vegetation index - https://en.wikipedia.org/wiki/Vegetation_Index - A Vegetation Index (VI) is a spectral transformation of two or more bands - designed to enhance the contribution of vegetation properties and allow - reliable spatial and temporal inter-comparisons of terrestrial - photosynthetic activity and canopy structural variations + # Vegetation index + https://en.wikipedia.org/wiki/Vegetation_Index + A Vegetation Index (VI) is a spectral transformation of two or more bands + designed to enhance the contribution of vegetation properties and allow + reliable spatial and temporal inter-comparisons of terrestrial + photosynthetic activity and canopy structural variations - # Information about channels (Wavelength range for each) - * nir - near-infrared - https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy - Wavelength Range 700 nm to 2500 nm - * Red Edge - https://en.wikipedia.org/wiki/Red_edge - Wavelength Range 680 nm to 730 nm - * red - https://en.wikipedia.org/wiki/Color - Wavelength Range 635 nm to 700 nm - * blue - https://en.wikipedia.org/wiki/Color - Wavelength Range 450 nm to 490 nm - * green - https://en.wikipedia.org/wiki/Color - Wavelength Range 520 nm to 560 nm + # Information about channels (Wavelength range for each) + * nir - near-infrared + https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy + Wavelength Range 700 nm to 2500 nm + * Red Edge + https://en.wikipedia.org/wiki/Red_edge + Wavelength Range 680 nm to 730 nm + * red + https://en.wikipedia.org/wiki/Color + Wavelength Range 635 nm to 700 nm + * blue + https://en.wikipedia.org/wiki/Color + Wavelength Range 450 nm to 490 nm + * green + https://en.wikipedia.org/wiki/Color + Wavelength Range 520 nm to 560 nm - # Implemented index list - #"abbreviationOfIndexName" -- list of channels used + # Implemented index list + #"abbreviationOfIndexName" -- list of channels used - #"ARVI2" -- red, nir - #"CCCI" -- red, redEdge, nir - #"CVI" -- red, green, nir - #"GLI" -- red, green, blue - #"NDVI" -- red, nir - #"BNDVI" -- blue, nir - #"redEdgeNDVI" -- red, redEdge - #"GNDVI" -- green, nir - #"GBNDVI" -- green, blue, nir - #"GRNDVI" -- red, green, nir - #"RBNDVI" -- red, blue, nir - #"PNDVI" -- red, green, blue, nir - #"ATSAVI" -- red, nir - #"BWDRVI" -- blue, nir - #"CIgreen" -- green, nir - #"CIrededge" -- redEdge, nir - #"CI" -- red, blue - #"CTVI" -- red, nir - #"GDVI" -- green, nir - #"EVI" -- red, blue, nir - #"GEMI" -- red, nir - #"GOSAVI" -- green, nir - #"GSAVI" -- green, nir - #"Hue" -- red, green, blue - #"IVI" -- red, nir - #"IPVI" -- red, nir - #"I" -- red, green, blue - #"RVI" -- red, nir - #"MRVI" -- red, nir - #"MSAVI" -- red, nir - #"NormG" -- red, green, nir - #"NormNIR" -- red, green, nir - #"NormR" -- red, green, nir - #"NGRDI" -- red, green - #"RI" -- red, green - #"S" -- red, green, blue - #"IF" -- red, green, blue - #"DVI" -- red, nir - #"TVI" -- red, nir - #"NDRE" -- redEdge, nir + #"ARVI2" -- red, nir + #"CCCI" -- red, redEdge, nir + #"CVI" -- red, green, nir + #"GLI" -- red, green, blue + #"NDVI" -- red, nir + #"BNDVI" -- blue, nir + #"redEdgeNDVI" -- red, redEdge + #"GNDVI" -- green, nir + #"GBNDVI" -- green, blue, nir + #"GRNDVI" -- red, green, nir + #"RBNDVI" -- red, blue, nir + #"PNDVI" -- red, green, blue, nir + #"ATSAVI" -- red, nir + #"BWDRVI" -- blue, nir + #"CIgreen" -- green, nir + #"CIrededge" -- redEdge, nir + #"CI" -- red, blue + #"CTVI" -- red, nir + #"GDVI" -- green, nir + #"EVI" -- red, blue, nir + #"GEMI" -- red, nir + #"GOSAVI" -- green, nir + #"GSAVI" -- green, nir + #"Hue" -- red, green, blue + #"IVI" -- red, nir + #"IPVI" -- red, nir + #"I" -- red, green, blue + #"RVI" -- red, nir + #"MRVI" -- red, nir + #"MSAVI" -- red, nir + #"NormG" -- red, green, nir + #"NormNIR" -- red, green, nir + #"NormR" -- red, green, nir + #"NGRDI" -- red, green + #"RI" -- red, green + #"S" -- red, green, blue + #"IF" -- red, green, blue + #"DVI" -- red, nir + #"TVI" -- red, nir + #"NDRE" -- redEdge, nir - #list of all index implemented - #allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI", - "GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI", - "BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI", - "GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI", - "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", - "S", "IF", "DVI", "TVI", "NDRE"] + #list of all index implemented + #allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI", + "GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI", + "BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI", + "GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI", + "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", + "S", "IF", "DVI", "TVI", "NDRE"] - #list of index with not blue channel - #notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI", - "GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI", - "GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI", - "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI", - "TVI", "NDRE"] + #list of index with not blue channel + #notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI", + "GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI", + "GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI", + "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI", + "TVI", "NDRE"] - #list of index just with RGB channels - #RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"] + #list of index just with RGB channels + #RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"] """ def __init__(self, red=None, green=None, blue=None, redEdge=None, nir=None): @@ -189,9 +189,9 @@ class IndexCalculation: def CCCI(self): """ - Canopy Chlorophyll Content Index - https://www.indexdatabase.de/db/i-single.php?id=224 - :return: index + Canopy Chlorophyll Content Index + https://www.indexdatabase.de/db/i-single.php?id=224 + :return: index """ return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) @@ -199,17 +199,17 @@ class IndexCalculation: def CVI(self): """ - Chlorophyll vegetation index - https://www.indexdatabase.de/db/i-single.php?id=391 - :return: index + Chlorophyll vegetation index + https://www.indexdatabase.de/db/i-single.php?id=391 + :return: index """ return self.nir * (self.red / (self.green ** 2)) def GLI(self): """ - self.green leaf index - https://www.indexdatabase.de/db/i-single.php?id=375 - :return: index + self.green leaf index + https://www.indexdatabase.de/db/i-single.php?id=375 + :return: index """ return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue @@ -217,43 +217,43 @@ class IndexCalculation: def NDVI(self): """ - Normalized Difference self.nir/self.red Normalized Difference Vegetation - Index, Calibrated NDVI - CDVI - https://www.indexdatabase.de/db/i-single.php?id=58 - :return: index + Normalized Difference self.nir/self.red Normalized Difference Vegetation + Index, Calibrated NDVI - CDVI + https://www.indexdatabase.de/db/i-single.php?id=58 + :return: index """ return (self.nir - self.red) / (self.nir + self.red) def BNDVI(self): """ - Normalized Difference self.nir/self.blue self.blue-normalized difference - vegetation index - https://www.indexdatabase.de/db/i-single.php?id=135 - :return: index + Normalized Difference self.nir/self.blue self.blue-normalized difference + vegetation index + https://www.indexdatabase.de/db/i-single.php?id=135 + :return: index """ return (self.nir - self.blue) / (self.nir + self.blue) def redEdgeNDVI(self): """ - Normalized Difference self.rededge/self.red - https://www.indexdatabase.de/db/i-single.php?id=235 - :return: index + Normalized Difference self.rededge/self.red + https://www.indexdatabase.de/db/i-single.php?id=235 + :return: index """ return (self.redEdge - self.red) / (self.redEdge + self.red) def GNDVI(self): """ - Normalized Difference self.nir/self.green self.green NDVI - https://www.indexdatabase.de/db/i-single.php?id=401 - :return: index + Normalized Difference self.nir/self.green self.green NDVI + https://www.indexdatabase.de/db/i-single.php?id=401 + :return: index """ return (self.nir - self.green) / (self.nir + self.green) def GBNDVI(self): """ - self.green-self.blue NDVI - https://www.indexdatabase.de/db/i-single.php?id=186 - :return: index + self.green-self.blue NDVI + https://www.indexdatabase.de/db/i-single.php?id=186 + :return: index """ return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) @@ -261,9 +261,9 @@ class IndexCalculation: def GRNDVI(self): """ - self.green-self.red NDVI - https://www.indexdatabase.de/db/i-single.php?id=185 - :return: index + self.green-self.red NDVI + https://www.indexdatabase.de/db/i-single.php?id=185 + :return: index """ return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) @@ -271,17 +271,17 @@ class IndexCalculation: def RBNDVI(self): """ - self.red-self.blue NDVI - https://www.indexdatabase.de/db/i-single.php?id=187 - :return: index + self.red-self.blue NDVI + https://www.indexdatabase.de/db/i-single.php?id=187 + :return: index """ return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def PNDVI(self): """ - Pan NDVI - https://www.indexdatabase.de/db/i-single.php?id=188 - :return: index + Pan NDVI + https://www.indexdatabase.de/db/i-single.php?id=188 + :return: index """ return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) @@ -289,9 +289,9 @@ class IndexCalculation: def ATSAVI(self, X=0.08, a=1.22, b=0.03): """ - Adjusted transformed soil-adjusted VI - https://www.indexdatabase.de/db/i-single.php?id=209 - :return: index + Adjusted transformed soil-adjusted VI + https://www.indexdatabase.de/db/i-single.php?id=209 + :return: index """ return a * ( (self.nir - a * self.red - b) @@ -300,58 +300,58 @@ class IndexCalculation: def BWDRVI(self): """ - self.blue-wide dynamic range vegetation index - https://www.indexdatabase.de/db/i-single.php?id=136 - :return: index + self.blue-wide dynamic range vegetation index + https://www.indexdatabase.de/db/i-single.php?id=136 + :return: index """ return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def CIgreen(self): """ - Chlorophyll Index self.green - https://www.indexdatabase.de/db/i-single.php?id=128 - :return: index + Chlorophyll Index self.green + https://www.indexdatabase.de/db/i-single.php?id=128 + :return: index """ return (self.nir / self.green) - 1 def CIrededge(self): """ - Chlorophyll Index self.redEdge - https://www.indexdatabase.de/db/i-single.php?id=131 - :return: index + Chlorophyll Index self.redEdge + https://www.indexdatabase.de/db/i-single.php?id=131 + :return: index """ return (self.nir / self.redEdge) - 1 def CI(self): """ - Coloration Index - https://www.indexdatabase.de/db/i-single.php?id=11 - :return: index + Coloration Index + https://www.indexdatabase.de/db/i-single.php?id=11 + :return: index """ return (self.red - self.blue) / self.red def CTVI(self): """ - Corrected Transformed Vegetation Index - https://www.indexdatabase.de/db/i-single.php?id=244 - :return: index + Corrected Transformed Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=244 + :return: index """ ndvi = self.NDVI() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def GDVI(self): """ - Difference self.nir/self.green self.green Difference Vegetation Index - https://www.indexdatabase.de/db/i-single.php?id=27 - :return: index + Difference self.nir/self.green self.green Difference Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=27 + :return: index """ return self.nir - self.green def EVI(self): """ - Enhanced Vegetation Index - https://www.indexdatabase.de/db/i-single.php?id=16 - :return: index + Enhanced Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=16 + :return: index """ return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) @@ -359,9 +359,9 @@ class IndexCalculation: def GEMI(self): """ - Global Environment Monitoring Index - https://www.indexdatabase.de/db/i-single.php?id=25 - :return: index + Global Environment Monitoring Index + https://www.indexdatabase.de/db/i-single.php?id=25 + :return: index """ n = (2 * (self.nir ** 2 - self.red ** 2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 @@ -370,27 +370,27 @@ class IndexCalculation: def GOSAVI(self, Y=0.16): """ - self.green Optimized Soil Adjusted Vegetation Index - https://www.indexdatabase.de/db/i-single.php?id=29 - mit Y = 0,16 - :return: index + self.green Optimized Soil Adjusted Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=29 + mit Y = 0,16 + :return: index """ return (self.nir - self.green) / (self.nir + self.green + Y) def GSAVI(self, L=0.5): """ - self.green Soil Adjusted Vegetation Index - https://www.indexdatabase.de/db/i-single.php?id=31 - mit L = 0,5 - :return: index + self.green Soil Adjusted Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=31 + mit L = 0,5 + :return: index """ return ((self.nir - self.green) / (self.nir + self.green + L)) * (1 + L) def Hue(self): """ - Hue - https://www.indexdatabase.de/db/i-single.php?id=34 - :return: index + Hue + https://www.indexdatabase.de/db/i-single.php?id=34 + :return: index """ return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) @@ -398,51 +398,51 @@ class IndexCalculation: def IVI(self, a=None, b=None): """ - Ideal vegetation index - https://www.indexdatabase.de/db/i-single.php?id=276 - b=intercept of vegetation line - a=soil line slope - :return: index + Ideal vegetation index + https://www.indexdatabase.de/db/i-single.php?id=276 + b=intercept of vegetation line + a=soil line slope + :return: index """ return (self.nir - b) / (a * self.red) def IPVI(self): """ - Infraself.red percentage vegetation index - https://www.indexdatabase.de/db/i-single.php?id=35 - :return: index + Infraself.red percentage vegetation index + https://www.indexdatabase.de/db/i-single.php?id=35 + :return: index """ return (self.nir / ((self.nir + self.red) / 2)) * (self.NDVI() + 1) def I(self): # noqa: E741,E743 """ - Intensity - https://www.indexdatabase.de/db/i-single.php?id=36 - :return: index + Intensity + https://www.indexdatabase.de/db/i-single.php?id=36 + :return: index """ return (self.red + self.green + self.blue) / 30.5 def RVI(self): """ - Ratio-Vegetation-Index - http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html - :return: index + Ratio-Vegetation-Index + http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html + :return: index """ return self.nir / self.red def MRVI(self): """ - Modified Normalized Difference Vegetation Index RVI - https://www.indexdatabase.de/db/i-single.php?id=275 - :return: index + Modified Normalized Difference Vegetation Index RVI + https://www.indexdatabase.de/db/i-single.php?id=275 + :return: index """ return (self.RVI() - 1) / (self.RVI() + 1) def MSAVI(self): """ - Modified Soil Adjusted Vegetation Index - https://www.indexdatabase.de/db/i-single.php?id=44 - :return: index + Modified Soil Adjusted Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=44 + :return: index """ return ( (2 * self.nir + 1) @@ -451,51 +451,51 @@ class IndexCalculation: def NormG(self): """ - Norm G - https://www.indexdatabase.de/db/i-single.php?id=50 - :return: index + Norm G + https://www.indexdatabase.de/db/i-single.php?id=50 + :return: index """ return self.green / (self.nir + self.red + self.green) def NormNIR(self): """ - Norm self.nir - https://www.indexdatabase.de/db/i-single.php?id=51 - :return: index + Norm self.nir + https://www.indexdatabase.de/db/i-single.php?id=51 + :return: index """ return self.nir / (self.nir + self.red + self.green) def NormR(self): """ - Norm R - https://www.indexdatabase.de/db/i-single.php?id=52 - :return: index + Norm R + https://www.indexdatabase.de/db/i-single.php?id=52 + :return: index """ return self.red / (self.nir + self.red + self.green) def NGRDI(self): """ - Normalized Difference self.green/self.red Normalized self.green self.red - difference index, Visible Atmospherically Resistant Indices self.green - (VIself.green) - https://www.indexdatabase.de/db/i-single.php?id=390 - :return: index + Normalized Difference self.green/self.red Normalized self.green self.red + difference index, Visible Atmospherically Resistant Indices self.green + (VIself.green) + https://www.indexdatabase.de/db/i-single.php?id=390 + :return: index """ return (self.green - self.red) / (self.green + self.red) def RI(self): """ - Normalized Difference self.red/self.green self.redness Index - https://www.indexdatabase.de/db/i-single.php?id=74 - :return: index + Normalized Difference self.red/self.green self.redness Index + https://www.indexdatabase.de/db/i-single.php?id=74 + :return: index """ return (self.red - self.green) / (self.red + self.green) def S(self): """ - Saturation - https://www.indexdatabase.de/db/i-single.php?id=77 - :return: index + Saturation + https://www.indexdatabase.de/db/i-single.php?id=77 + :return: index """ max = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) @@ -503,26 +503,26 @@ class IndexCalculation: def IF(self): """ - Shape Index - https://www.indexdatabase.de/db/i-single.php?id=79 - :return: index + Shape Index + https://www.indexdatabase.de/db/i-single.php?id=79 + :return: index """ return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def DVI(self): """ - Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index - Number (VIN) - https://www.indexdatabase.de/db/i-single.php?id=12 - :return: index + Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index + Number (VIN) + https://www.indexdatabase.de/db/i-single.php?id=12 + :return: index """ return self.nir / self.red def TVI(self): """ - Transformed Vegetation Index - https://www.indexdatabase.de/db/i-single.php?id=98 - :return: index + Transformed Vegetation Index + https://www.indexdatabase.de/db/i-single.php?id=98 + :return: index """ return (self.NDVI() + 0.5) ** (1 / 2) diff --git a/divide_and_conquer/closest_pair_of_points.py b/divide_and_conquer/closest_pair_of_points.py index eecf53a74..cb7fa00d1 100644 --- a/divide_and_conquer/closest_pair_of_points.py +++ b/divide_and_conquer/closest_pair_of_points.py @@ -82,7 +82,7 @@ def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): - """ divide and conquer approach + """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) diff --git a/divide_and_conquer/max_subarray_sum.py b/divide_and_conquer/max_subarray_sum.py index 03bf9d25c..43f58086e 100644 --- a/divide_and_conquer/max_subarray_sum.py +++ b/divide_and_conquer/max_subarray_sum.py @@ -11,7 +11,7 @@ Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION def max_sum_from_start(array): - """ This function finds the maximum contiguous sum of array from 0 index + """This function finds the maximum contiguous sum of array from 0 index Parameters : array (list[int]) : given array @@ -30,7 +30,7 @@ def max_sum_from_start(array): def max_cross_array_sum(array, left, mid, right): - """ This function finds the maximum contiguous sum of left and right arrays + """This function finds the maximum contiguous sum of left and right arrays Parameters : array, left, mid, right (list[int], int, int, int) @@ -46,7 +46,7 @@ def max_cross_array_sum(array, left, mid, right): def max_subarray_sum(array, left, right): - """ Maximum contiguous sub-array sum, using divide and conquer method + """Maximum contiguous sub-array sum, using divide and conquer method Parameters : array, left, right (list[int], int, int) : diff --git a/divide_and_conquer/strassen_matrix_multiplication.py b/divide_and_conquer/strassen_matrix_multiplication.py index ea54b0f52..486258e8b 100644 --- a/divide_and_conquer/strassen_matrix_multiplication.py +++ b/divide_and_conquer/strassen_matrix_multiplication.py @@ -29,7 +29,9 @@ def matrix_subtraction(matrix_a: List, matrix_b: List): ] -def split_matrix(a: List,) -> Tuple[List, List, List, List]: +def split_matrix( + a: List, +) -> Tuple[List, List, List, List]: """ Given an even length matrix, returns the top_left, top_right, bot_left, bot_right quadrant. diff --git a/dynamic_programming/rod_cutting.py b/dynamic_programming/rod_cutting.py index a4919742e..442a39cb1 100644 --- a/dynamic_programming/rod_cutting.py +++ b/dynamic_programming/rod_cutting.py @@ -13,30 +13,30 @@ pieces separately or not cutting it at all if the price of it is the maximum obt def naive_cut_rod_recursive(n: int, prices: list): """ - Solves the rod-cutting problem via naively without using the benefit of dynamic - programming. The results is the same sub-problems are solved several times - leading to an exponential runtime + Solves the rod-cutting problem via naively without using the benefit of dynamic + programming. The results is the same sub-problems are solved several times + leading to an exponential runtime - Runtime: O(2^n) + Runtime: O(2^n) - Arguments - ------- - n: int, the length of the rod - prices: list, the prices for each piece of rod. ``p[i-i]`` is the - price for a rod of length ``i`` + Arguments + ------- + n: int, the length of the rod + prices: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` - Returns - ------- - The maximum revenue obtainable for a rod of length n given the list of prices - for each piece. + Returns + ------- + The maximum revenue obtainable for a rod of length n given the list of prices + for each piece. - Examples - -------- - >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) - 10 - >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) - 30 - """ + Examples + -------- + >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) + 10 + >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) + 30 + """ _enforce_args(n, prices) if n == 0: @@ -52,35 +52,35 @@ def naive_cut_rod_recursive(n: int, prices: list): def top_down_cut_rod(n: int, prices: list): """ - Constructs a top-down dynamic programming solution for the rod-cutting - problem via memoization. This function serves as a wrapper for - _top_down_cut_rod_recursive + Constructs a top-down dynamic programming solution for the rod-cutting + problem via memoization. This function serves as a wrapper for + _top_down_cut_rod_recursive - Runtime: O(n^2) + Runtime: O(n^2) - Arguments - -------- - n: int, the length of the rod - prices: list, the prices for each piece of rod. ``p[i-i]`` is the - price for a rod of length ``i`` + Arguments + -------- + n: int, the length of the rod + prices: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` - Note - ---- - For convenience and because Python's lists using 0-indexing, length(max_rev) = - n + 1, to accommodate for the revenue obtainable from a rod of length 0. + Note + ---- + For convenience and because Python's lists using 0-indexing, length(max_rev) = + n + 1, to accommodate for the revenue obtainable from a rod of length 0. - Returns - ------- - The maximum revenue obtainable for a rod of length n given the list of prices - for each piece. + Returns + ------- + The maximum revenue obtainable for a rod of length n given the list of prices + for each piece. - Examples - ------- - >>> top_down_cut_rod(4, [1, 5, 8, 9]) - 10 - >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) - 30 - """ + Examples + ------- + >>> top_down_cut_rod(4, [1, 5, 8, 9]) + 10 + >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) + 30 + """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) @@ -88,24 +88,24 @@ def top_down_cut_rod(n: int, prices: list): def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ - Constructs a top-down dynamic programming solution for the rod-cutting problem - via memoization. + Constructs a top-down dynamic programming solution for the rod-cutting problem + via memoization. - Runtime: O(n^2) + Runtime: O(n^2) - Arguments - -------- - n: int, the length of the rod - prices: list, the prices for each piece of rod. ``p[i-i]`` is the - price for a rod of length ``i`` - max_rev: list, the computed maximum revenue for a piece of rod. - ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` + Arguments + -------- + n: int, the length of the rod + prices: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` + max_rev: list, the computed maximum revenue for a piece of rod. + ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` - Returns - ------- - The maximum revenue obtainable for a rod of length n given the list of prices - for each piece. - """ + Returns + ------- + The maximum revenue obtainable for a rod of length n given the list of prices + for each piece. + """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: @@ -125,28 +125,28 @@ def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): def bottom_up_cut_rod(n: int, prices: list): """ - Constructs a bottom-up dynamic programming solution for the rod-cutting problem + Constructs a bottom-up dynamic programming solution for the rod-cutting problem - Runtime: O(n^2) + Runtime: O(n^2) - Arguments - ---------- - n: int, the maximum length of the rod. - prices: list, the prices for each piece of rod. ``p[i-i]`` is the - price for a rod of length ``i`` + Arguments + ---------- + n: int, the maximum length of the rod. + prices: list, the prices for each piece of rod. ``p[i-i]`` is the + price for a rod of length ``i`` - Returns - ------- - The maximum revenue obtainable from cutting a rod of length n given - the prices for each piece of rod p. + Returns + ------- + The maximum revenue obtainable from cutting a rod of length n given + the prices for each piece of rod p. - Examples - ------- - >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) - 10 - >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) - 30 - """ + Examples + ------- + >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) + 10 + >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) + 30 + """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of @@ -166,16 +166,16 @@ def bottom_up_cut_rod(n: int, prices: list): def _enforce_args(n: int, prices: list): """ - Basic checks on the arguments to the rod-cutting algorithms + Basic checks on the arguments to the rod-cutting algorithms - n: int, the length of the rod - prices: list, the price list for each piece of rod. + n: int, the length of the rod + prices: list, the price list for each piece of rod. - Throws ValueError: + Throws ValueError: - if n is negative or there are fewer items in the price list than the length of - the rod - """ + if n is negative or there are fewer items in the price list than the length of + the rod + """ if n < 0: raise ValueError(f"n must be greater than or equal to 0. Got n = {n}") diff --git a/graphs/bfs_shortest_path.py b/graphs/bfs_shortest_path.py index c3664796e..1655ca642 100644 --- a/graphs/bfs_shortest_path.py +++ b/graphs/bfs_shortest_path.py @@ -20,18 +20,18 @@ graph = { def bfs_shortest_path(graph: dict, start, goal) -> str: """Find shortest path between `start` and `goal` nodes. - Args: - graph (dict): node/list of neighboring nodes key/value pairs. - start: start node. - goal: target node. + Args: + graph (dict): node/list of neighboring nodes key/value pairs. + start: start node. + goal: target node. - Returns: - Shortest path between `start` and `goal` nodes as a string of nodes. - 'Not found' string if no path found. + Returns: + Shortest path between `start` and `goal` nodes as a string of nodes. + 'Not found' string if no path found. - Example: - >>> bfs_shortest_path(graph, "G", "D") - ['G', 'C', 'A', 'B', 'D'] + Example: + >>> bfs_shortest_path(graph, "G", "D") + ['G', 'C', 'A', 'B', 'D'] """ # keep track of explored nodes explored = [] @@ -70,22 +70,22 @@ def bfs_shortest_path(graph: dict, start, goal) -> str: def bfs_shortest_path_distance(graph: dict, start, target) -> int: """Find shortest path distance between `start` and `target` nodes. - Args: - graph: node/list of neighboring nodes key/value pairs. - start: node to start search from. - target: node to search for. + Args: + graph: node/list of neighboring nodes key/value pairs. + start: node to start search from. + target: node to search for. - Returns: - Number of edges in shortest path between `start` and `target` nodes. - -1 if no path exists. + Returns: + Number of edges in shortest path between `start` and `target` nodes. + -1 if no path exists. - Example: - >>> bfs_shortest_path_distance(graph, "G", "D") - 4 - >>> bfs_shortest_path_distance(graph, "A", "A") - 0 - >>> bfs_shortest_path_distance(graph, "A", "H") - -1 + Example: + >>> bfs_shortest_path_distance(graph, "G", "D") + 4 + >>> bfs_shortest_path_distance(graph, "A", "A") + 0 + >>> bfs_shortest_path_distance(graph, "A", "H") + -1 """ if not graph or start not in graph or target not in graph: return -1 diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index 1e2231907..9ec7083c7 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -17,18 +17,18 @@ from typing import Dict, Set def depth_first_search(graph: Dict, start: str) -> Set[int]: """Depth First Search on Graph - :param graph: directed graph in dictionary format - :param vertex: starting vectex as a string - :returns: the trace of the search - >>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], - ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], - ... "F": ["C", "E", "G"], "G": ["F"] } - >>> start = "A" - >>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'}) - >>> all(x in output_G for x in list(depth_first_search(G, "A"))) - True - >>> all(x in output_G for x in list(depth_first_search(G, "G"))) - True + :param graph: directed graph in dictionary format + :param vertex: starting vectex as a string + :returns: the trace of the search + >>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], + ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], + ... "F": ["C", "E", "G"], "G": ["F"] } + >>> start = "A" + >>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'}) + >>> all(x in output_G for x in list(depth_first_search(G, "A"))) + True + >>> all(x in output_G for x in list(depth_first_search(G, "G"))) + True """ explored, stack = set(start), [start] while stack: diff --git a/graphs/prim.py b/graphs/prim.py index a1d46a5a1..f7376cfb4 100644 --- a/graphs/prim.py +++ b/graphs/prim.py @@ -56,14 +56,14 @@ def connect(graph, a, b, edge): def prim(graph: list, root: Vertex) -> list: """Prim's Algorithm. - Runtime: - O(mn) with `m` edges and `n` vertices + Runtime: + O(mn) with `m` edges and `n` vertices - Return: - List with the edges of a Minimum Spanning Tree + Return: + List with the edges of a Minimum Spanning Tree - Usage: - prim(graph, graph[0]) + Usage: + prim(graph, graph[0]) """ a = [] for u in graph: @@ -86,14 +86,14 @@ def prim(graph: list, root: Vertex) -> list: def prim_heap(graph: list, root: Vertex) -> Iterator[tuple]: """Prim's Algorithm with min heap. - Runtime: - O((m + n)log n) with `m` edges and `n` vertices + Runtime: + O((m + n)log n) with `m` edges and `n` vertices - Yield: - Edges of a Minimum Spanning Tree + Yield: + Edges of a Minimum Spanning Tree - Usage: - prim(graph, graph[0]) + Usage: + prim(graph, graph[0]) """ for u in graph: u.key = math.inf diff --git a/hashes/md5.py b/hashes/md5.py index 85565533d..b7888fb61 100644 --- a/hashes/md5.py +++ b/hashes/md5.py @@ -94,9 +94,7 @@ def not32(i): def sum32(a, b): - """ - - """ + """""" return (a + b) % 2 ** 32 diff --git a/linear_algebra/src/lib.py b/linear_algebra/src/lib.py index 10b9da658..353c83340 100644 --- a/linear_algebra/src/lib.py +++ b/linear_algebra/src/lib.py @@ -26,29 +26,29 @@ import random class Vector: """ - This class represents a vector of arbitrary size. - You need to give the vector components. + This class represents a vector of arbitrary size. + You need to give the vector components. - Overview about the methods: + Overview about the methods: - constructor(components : list) : init the vector - set(components : list) : changes the vector components. - __str__() : toString method - component(i : int): gets the i-th component (start by 0) - __len__() : gets the size of the vector (number of components) - euclidLength() : returns the euclidean length of the vector. - operator + : vector addition - operator - : vector subtraction - operator * : scalar multiplication and dot product - copy() : copies this vector and returns it. - changeComponent(pos,value) : changes the specified component. - TODO: compare-operator + constructor(components : list) : init the vector + set(components : list) : changes the vector components. + __str__() : toString method + component(i : int): gets the i-th component (start by 0) + __len__() : gets the size of the vector (number of components) + euclidLength() : returns the euclidean length of the vector. + operator + : vector addition + operator - : vector subtraction + operator * : scalar multiplication and dot product + copy() : copies this vector and returns it. + changeComponent(pos,value) : changes the specified component. + TODO: compare-operator """ def __init__(self, components=None): """ - input: components or nothing - simple constructor for init the vector + input: components or nothing + simple constructor for init the vector """ if components is None: components = [] @@ -56,9 +56,9 @@ class Vector: def set(self, components): """ - input: new components - changes the components of the vector. - replace the components with newer one. + input: new components + changes the components of the vector. + replace the components with newer one. """ if len(components) > 0: self.__components = list(components) @@ -67,14 +67,14 @@ class Vector: def __str__(self): """ - returns a string representation of the vector + returns a string representation of the vector """ return "(" + ",".join(map(str, self.__components)) + ")" def component(self, i): """ - input: index (start at 0) - output: the i-th component of the vector. + input: index (start at 0) + output: the i-th component of the vector. """ if type(i) is int and -len(self.__components) <= i < len(self.__components): return self.__components[i] @@ -83,13 +83,13 @@ class Vector: def __len__(self): """ - returns the size of the vector + returns the size of the vector """ return len(self.__components) def euclidLength(self): """ - returns the euclidean length of the vector + returns the euclidean length of the vector """ summe = 0 for c in self.__components: @@ -98,9 +98,9 @@ class Vector: def __add__(self, other): """ - input: other vector - assumes: other vector has the same size - returns a new vector that represents the sum. + input: other vector + assumes: other vector has the same size + returns a new vector that represents the sum. """ size = len(self) if size == len(other): @@ -111,9 +111,9 @@ class Vector: def __sub__(self, other): """ - input: other vector - assumes: other vector has the same size - returns a new vector that represents the difference. + input: other vector + assumes: other vector has the same size + returns a new vector that represents the difference. """ size = len(self) if size == len(other): @@ -124,8 +124,8 @@ class Vector: def __mul__(self, other): """ - mul implements the scalar multiplication - and the dot-product + mul implements the scalar multiplication + and the dot-product """ if isinstance(other, float) or isinstance(other, int): ans = [c * other for c in self.__components] @@ -141,15 +141,15 @@ class Vector: def copy(self): """ - copies this vector and returns it. + copies this vector and returns it. """ return Vector(self.__components) def changeComponent(self, pos, value): """ - input: an index (pos) and a value - changes the specified component (pos) with the - 'value' + input: an index (pos) and a value + changes the specified component (pos) with the + 'value' """ # precondition assert -len(self.__components) <= pos < len(self.__components) @@ -158,7 +158,7 @@ class Vector: def zeroVector(dimension): """ - returns a zero-vector of size 'dimension' + returns a zero-vector of size 'dimension' """ # precondition assert isinstance(dimension, int) @@ -167,8 +167,8 @@ def zeroVector(dimension): def unitBasisVector(dimension, pos): """ - returns a unit basis vector with a One - at index 'pos' (indexing at 0) + returns a unit basis vector with a One + at index 'pos' (indexing at 0) """ # precondition assert isinstance(dimension, int) and (isinstance(pos, int)) @@ -179,9 +179,9 @@ def unitBasisVector(dimension, pos): def axpy(scalar, x, y): """ - input: a 'scalar' and two vectors 'x' and 'y' - output: a vector - computes the axpy operation + input: a 'scalar' and two vectors 'x' and 'y' + output: a vector + computes the axpy operation """ # precondition assert ( @@ -194,10 +194,10 @@ def axpy(scalar, x, y): def randomVector(N, a, b): """ - input: size (N) of the vector. - random range (a,b) - output: returns a random vector of size N, with - random integer components between 'a' and 'b'. + input: size (N) of the vector. + random range (a,b) + output: returns a random vector of size N, with + random integer components between 'a' and 'b'. """ random.seed(None) ans = [random.randint(a, b) for i in range(N)] @@ -224,8 +224,8 @@ class Matrix: def __init__(self, matrix, w, h): """ - simple constructor for initializing - the matrix with components. + simple constructor for initializing + the matrix with components. """ self.__matrix = matrix self.__width = w @@ -233,8 +233,8 @@ class Matrix: def __str__(self): """ - returns a string representation of this - matrix. + returns a string representation of this + matrix. """ ans = "" for i in range(self.__height): @@ -248,7 +248,7 @@ class Matrix: def changeComponent(self, x, y, value): """ - changes the x-y component of this matrix + changes the x-y component of this matrix """ if 0 <= x < self.__height and 0 <= y < self.__width: self.__matrix[x][y] = value @@ -257,7 +257,7 @@ class Matrix: def component(self, x, y): """ - returns the specified (x,y) component + returns the specified (x,y) component """ if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] @@ -266,19 +266,19 @@ class Matrix: def width(self): """ - getter for the width + getter for the width """ return self.__width def height(self): """ - getter for the height + getter for the height """ return self.__height def determinate(self) -> float: """ - returns the determinate of an nxn matrix using Laplace expansion + returns the determinate of an nxn matrix using Laplace expansion """ if self.__height == self.__width and self.__width >= 2: total = 0 @@ -305,8 +305,8 @@ class Matrix: def __mul__(self, other): """ - implements the matrix-vector multiplication. - implements the matrix-scalar multiplication + implements the matrix-vector multiplication. + implements the matrix-scalar multiplication """ if isinstance(other, Vector): # vector-matrix if len(other) == self.__width: @@ -332,7 +332,7 @@ class Matrix: def __add__(self, other): """ - implements the matrix-addition. + implements the matrix-addition. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] @@ -347,7 +347,7 @@ class Matrix: def __sub__(self, other): """ - implements the matrix-subtraction. + implements the matrix-subtraction. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] @@ -363,7 +363,7 @@ class Matrix: def squareZeroMatrix(N): """ - returns a square zero-matrix of dimension NxN + returns a square zero-matrix of dimension NxN """ ans = [[0] * N for i in range(N)] return Matrix(ans, N, N) @@ -371,8 +371,8 @@ def squareZeroMatrix(N): def randomMatrix(W, H, a, b): """ - returns a random matrix WxH with integer components - between 'a' and 'b' + returns a random matrix WxH with integer components + between 'a' and 'b' """ random.seed(None) matrix = [[random.randint(a, b) for j in range(W)] for i in range(H)] diff --git a/linear_algebra/src/test_linear_algebra.py b/linear_algebra/src/test_linear_algebra.py index 8db480ceb..668ffe858 100644 --- a/linear_algebra/src/test_linear_algebra.py +++ b/linear_algebra/src/test_linear_algebra.py @@ -14,7 +14,7 @@ from lib import Matrix, Vector, axpy, squareZeroMatrix, unitBasisVector, zeroVec class Test(unittest.TestCase): def test_component(self): """ - test for method component + test for method component """ x = Vector([1, 2, 3]) self.assertEqual(x.component(0), 1) @@ -23,28 +23,28 @@ class Test(unittest.TestCase): def test_str(self): """ - test for toString() method + test for toString() method """ x = Vector([0, 0, 0, 0, 0, 1]) self.assertEqual(str(x), "(0,0,0,0,0,1)") def test_size(self): """ - test for size()-method + test for size()-method """ x = Vector([1, 2, 3, 4]) self.assertEqual(len(x), 4) def test_euclidLength(self): """ - test for the eulidean length + test for the eulidean length """ x = Vector([1, 2]) self.assertAlmostEqual(x.euclidLength(), 2.236, 3) def test_add(self): """ - test for + operator + test for + operator """ x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) @@ -54,7 +54,7 @@ class Test(unittest.TestCase): def test_sub(self): """ - test for - operator + test for - operator """ x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) @@ -64,7 +64,7 @@ class Test(unittest.TestCase): def test_mul(self): """ - test for * operator + test for * operator """ x = Vector([1, 2, 3]) a = Vector([2, -1, 4]) # for test of dot-product @@ -74,19 +74,19 @@ class Test(unittest.TestCase): def test_zeroVector(self): """ - test for the global function zeroVector(...) + test for the global function zeroVector(...) """ self.assertTrue(str(zeroVector(10)).count("0") == 10) def test_unitBasisVector(self): """ - test for the global function unitBasisVector(...) + test for the global function unitBasisVector(...) """ self.assertEqual(str(unitBasisVector(3, 1)), "(0,1,0)") def test_axpy(self): """ - test for the global function axpy(...) (operation) + test for the global function axpy(...) (operation) """ x = Vector([1, 2, 3]) y = Vector([1, 0, 1]) @@ -94,7 +94,7 @@ class Test(unittest.TestCase): def test_copy(self): """ - test for the copy()-method + test for the copy()-method """ x = Vector([1, 0, 0, 0, 0, 0]) y = x.copy() @@ -102,7 +102,7 @@ class Test(unittest.TestCase): def test_changeComponent(self): """ - test for the changeComponent(...)-method + test for the changeComponent(...)-method """ x = Vector([1, 0, 0]) x.changeComponent(0, 0) @@ -115,7 +115,7 @@ class Test(unittest.TestCase): def test_determinate(self): """ - test for determinate() + test for determinate() """ A = Matrix([[1, 1, 4, 5], [3, 3, 3, 2], [5, 1, 9, 0], [9, 7, 7, 9]], 4, 4) self.assertEqual(-376, A.determinate()) diff --git a/machine_learning/decision_tree.py b/machine_learning/decision_tree.py index fe1d54736..ace6fb0fa 100644 --- a/machine_learning/decision_tree.py +++ b/machine_learning/decision_tree.py @@ -135,8 +135,7 @@ class Decision_Tree: class Test_Decision_Tree: - """Decision Tres test class - """ + """Decision Tres test class""" @staticmethod def helper_mean_squared_error_test(labels, prediction): diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 4da904ae3..130e7f1ad 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -132,12 +132,12 @@ def kmeans( data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False ): """This function runs k-means on given data and initial set of centroids. - maxiter: maximum number of iterations to run.(default=500) - record_heterogeneity: (optional) a list, to store the history of heterogeneity - as function of iterations - if None, do not store the history. - verbose: if True, print how many data points changed their cluster labels in - each iteration""" + maxiter: maximum number of iterations to run.(default=500) + record_heterogeneity: (optional) a list, to store the history of heterogeneity + as function of iterations + if None, do not store the history. + verbose: if True, print how many data points changed their cluster labels in + each iteration""" centroids = initial_centroids[:] prev_cluster_assignment = None diff --git a/machine_learning/linear_discriminant_analysis.py b/machine_learning/linear_discriminant_analysis.py index b26da2628..22ee63a5a 100644 --- a/machine_learning/linear_discriminant_analysis.py +++ b/machine_learning/linear_discriminant_analysis.py @@ -153,7 +153,7 @@ def calculate_variance(items: list, means: list, total_count: int) -> float: def predict_y_values( x_items: list, means: list, variance: float, probabilities: list ) -> list: - """ This function predicts new indexes(groups for our data) + """This function predicts new indexes(groups for our data) :param x_items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculate_variance function diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index 8c0dfebbc..a726629ef 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -12,7 +12,7 @@ import requests def collect_dataset(): - """ Collect dataset of CSGO + """Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ @@ -32,7 +32,7 @@ def collect_dataset(): def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): - """ Run steep gradient descent and updates the Feature vector accordingly_ + """Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ @@ -51,7 +51,7 @@ def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): def sum_of_square_error(data_x, data_y, len_data, theta): - """ Return sum of square error for error calculation + """Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset @@ -66,7 +66,7 @@ def sum_of_square_error(data_x, data_y, len_data, theta): def run_linear_regression(data_x, data_y): - """ Implement Linear regression over the dataset + """Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) diff --git a/maths/kth_lexicographic_permutation.py b/maths/kth_lexicographic_permutation.py index 491c1c84f..23eab626f 100644 --- a/maths/kth_lexicographic_permutation.py +++ b/maths/kth_lexicographic_permutation.py @@ -1,18 +1,18 @@ def kthPermutation(k, n): """ - Finds k'th lexicographic permutation (in increasing order) of - 0,1,2,...n-1 in O(n^2) time. + Finds k'th lexicographic permutation (in increasing order) of + 0,1,2,...n-1 in O(n^2) time. - Examples: - First permutation is always 0,1,2,...n - >>> kthPermutation(0,5) - [0, 1, 2, 3, 4] + Examples: + First permutation is always 0,1,2,...n + >>> kthPermutation(0,5) + [0, 1, 2, 3, 4] - The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], - [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], - [1,2,3,0], [1,3,0,2] - >>> kthPermutation(10,4) - [1, 3, 0, 2] + The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], + [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], + [1,2,3,0], [1,3,0,2] + >>> kthPermutation(10,4) + [1, 3, 0, 2] """ # Factorails from 1! to (n-1)! factorials = [1] diff --git a/maths/newton_raphson.py b/maths/newton_raphson.py index d8a98dfa6..f2b7cb976 100644 --- a/maths/newton_raphson.py +++ b/maths/newton_raphson.py @@ -12,8 +12,8 @@ import math as m def calc_derivative(f, a, h=0.001): """ - Calculates derivative at point a for function f using finite difference - method + Calculates derivative at point a for function f using finite difference + method """ return (f(a + h) - f(a - h)) / (2 * h) diff --git a/maths/prime_sieve_eratosthenes.py b/maths/prime_sieve_eratosthenes.py index 0ebdfdb94..da3ae472c 100644 --- a/maths/prime_sieve_eratosthenes.py +++ b/maths/prime_sieve_eratosthenes.py @@ -19,9 +19,9 @@ def prime_sieve_eratosthenes(num): print the prime numbers up to n >>> prime_sieve_eratosthenes(10) - 2 3 5 7 + 2,3,5,7, >>> prime_sieve_eratosthenes(20) - 2 3 5 7 11 13 17 19 + 2,3,5,7,11,13,17,19, """ primes = [True for i in range(num + 1)] @@ -35,10 +35,13 @@ def prime_sieve_eratosthenes(num): for prime in range(2, num + 1): if primes[prime]: - print(prime, end=" ") + print(prime, end=",") if __name__ == "__main__": + import doctest + + doctest.testmod() num = int(input()) prime_sieve_eratosthenes(num) diff --git a/maths/relu.py b/maths/relu.py index 89667ab3e..826ada65f 100644 --- a/maths/relu.py +++ b/maths/relu.py @@ -16,20 +16,20 @@ import numpy as np def relu(vector: List[float]): """ - Implements the relu function + Implements the relu function - Parameters: - vector (np.array,list,tuple): A numpy array of shape (1,n) - consisting of real values or a similar list,tuple + Parameters: + vector (np.array,list,tuple): A numpy array of shape (1,n) + consisting of real values or a similar list,tuple - Returns: - relu_vec (np.array): The input numpy array, after applying - relu. + Returns: + relu_vec (np.array): The input numpy array, after applying + relu. - >>> vec = np.array([-1, 0, 5]) - >>> relu(vec) - array([0, 0, 5]) + >>> vec = np.array([-1, 0, 5]) + >>> relu(vec) + array([0, 0, 5]) """ # compare two arrays and then return element-wise maxima. diff --git a/maths/softmax.py b/maths/softmax.py index 92ff4ca27..e021a7f8a 100644 --- a/maths/softmax.py +++ b/maths/softmax.py @@ -15,28 +15,28 @@ import numpy as np def softmax(vector): """ - Implements the softmax function + Implements the softmax function - Parameters: - vector (np.array,list,tuple): A numpy array of shape (1,n) - consisting of real values or a similar list,tuple + Parameters: + vector (np.array,list,tuple): A numpy array of shape (1,n) + consisting of real values or a similar list,tuple - Returns: - softmax_vec (np.array): The input numpy array after applying - softmax. + Returns: + softmax_vec (np.array): The input numpy array after applying + softmax. - The softmax vector adds up to one. We need to ceil to mitigate for - precision - >>> np.ceil(np.sum(softmax([1,2,3,4]))) - 1.0 + The softmax vector adds up to one. We need to ceil to mitigate for + precision + >>> np.ceil(np.sum(softmax([1,2,3,4]))) + 1.0 - >>> vec = np.array([5,5]) - >>> softmax(vec) - array([0.5, 0.5]) + >>> vec = np.array([5,5]) + >>> softmax(vec) + array([0.5, 0.5]) - >>> softmax([0]) - array([1.]) + >>> softmax([0]) + array([1.]) """ # Calculate e^x for each x in your vector where e is Euler's diff --git a/maths/sum_of_geometric_progression.py b/maths/sum_of_geometric_progression.py index 614d6646e..f29dd8005 100644 --- a/maths/sum_of_geometric_progression.py +++ b/maths/sum_of_geometric_progression.py @@ -1,7 +1,7 @@ def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: - """" + """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 diff --git a/maths/zellers_congruence.py b/maths/zellers_congruence.py index 8608b32f3..2d4a22a0a 100644 --- a/maths/zellers_congruence.py +++ b/maths/zellers_congruence.py @@ -63,8 +63,7 @@ def zeller(date_input: str) -> str: >>> zeller('01-31-19082939') Traceback (most recent call last): ... - ValueError: Must be 10 characters long -""" + ValueError: Must be 10 characters long""" # Days of the week for response days = { diff --git a/matrix/matrix_operation.py b/matrix/matrix_operation.py index 42a94da12..3838dab6b 100644 --- a/matrix/matrix_operation.py +++ b/matrix/matrix_operation.py @@ -168,7 +168,9 @@ def main(): matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] print(f"Add Operation, {add(matrix_a, matrix_b) = } \n") - print(f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",) + print( + f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n", + ) print(f"Identity: {identity(5)}\n") print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n") print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n") diff --git a/other/activity_selection.py b/other/activity_selection.py index 8876eb293..c03956cce 100644 --- a/other/activity_selection.py +++ b/other/activity_selection.py @@ -16,14 +16,14 @@ def printMaxActivities(start, finish): >>> finish = [2, 4, 6, 7, 9, 9] >>> printMaxActivities(start, finish) The following activities are selected: - 0 1 3 4 + 0,1,3,4, """ n = len(finish) print("The following activities are selected:") # The first activity is always selected i = 0 - print(i, end=" ") + print(i, end=",") # Consider rest of the activities for j in range(n): @@ -32,16 +32,15 @@ def printMaxActivities(start, finish): # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: - print(j, end=" ") + print(j, end=",") i = j -# Driver program to test above function -start = [1, 3, 0, 5, 8, 5] -finish = [2, 4, 6, 7, 9, 9] -printMaxActivities(start, finish) +if __name__ == "__main__": + import doctest -""" -The following activities are selected: -0 1 3 4 -""" + doctest.testmod() + + start = [1, 3, 0, 5, 8, 5] + finish = [2, 4, 6, 7, 9, 9] + printMaxActivities(start, finish) diff --git a/other/game_of_life.py b/other/game_of_life.py index 651467969..09863993d 100644 --- a/other/game_of_life.py +++ b/other/game_of_life.py @@ -52,7 +52,7 @@ def seed(canvas): def run(canvas): - """ This function runs the rules of game through all points, and changes their + """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- diff --git a/other/least_recently_used.py b/other/least_recently_used.py index 1b901d544..213339636 100644 --- a/other/least_recently_used.py +++ b/other/least_recently_used.py @@ -12,7 +12,7 @@ class LRUCache: @abstractmethod def __init__(self, n: int): - """ Creates an empty store and map for the keys. + """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() @@ -26,9 +26,9 @@ class LRUCache: def refer(self, x): """ - Looks for a page in the cache store and adds reference to the set. - Remove the least recently used key if the store is full. - Update store to reflect recent access. + Looks for a page in the cache store and adds reference to the set. + Remove the least recently used key if the store is full. + Update store to reflect recent access. """ if x not in self.key_reference_map: if len(self.dq_store) == LRUCache._MAX_CAPACITY: @@ -47,7 +47,7 @@ class LRUCache: def display(self): """ - Prints all the elements in the store. + Prints all the elements in the store. """ for k in self.dq_store: print(k) diff --git a/other/magicdiamondpattern.py b/other/magicdiamondpattern.py index 37b5e4809..71bc50b51 100644 --- a/other/magicdiamondpattern.py +++ b/other/magicdiamondpattern.py @@ -6,7 +6,7 @@ def floyd(n): """ Parameters: n : size of pattern - """ + """ for i in range(0, n): for j in range(0, n - i - 1): # printing spaces print(" ", end="") @@ -20,7 +20,7 @@ def reverse_floyd(n): """ Parameters: n : size of pattern - """ + """ for i in range(n, 0, -1): for j in range(i, 0, -1): # printing stars print("* ", end="") @@ -34,7 +34,7 @@ def pretty_print(n): """ Parameters: n : size of pattern - """ + """ if n <= 0: print(" ... .... nothing printing :(") return diff --git a/other/primelib.py b/other/primelib.py index a6d1d7dfb..37883d9cf 100644 --- a/other/primelib.py +++ b/other/primelib.py @@ -43,8 +43,8 @@ from math import sqrt def isPrime(number): """ - input: positive integer 'number' - returns true if 'number' is prime otherwise false. + input: positive integer 'number' + returns true if 'number' is prime otherwise false. """ # precondition @@ -77,11 +77,11 @@ def isPrime(number): def sieveEr(N): """ - input: positive integer 'N' > 2 - returns a list of prime numbers from 2 up to N. + input: positive integer 'N' > 2 + returns a list of prime numbers from 2 up to N. - This function implements the algorithm called - sieve of erathostenes. + This function implements the algorithm called + sieve of erathostenes. """ @@ -115,9 +115,9 @@ def sieveEr(N): def getPrimeNumbers(N): """ - input: positive integer 'N' > 2 - returns a list of prime numbers from 2 up to N (inclusive) - This function is more efficient as function 'sieveEr(...)' + input: positive integer 'N' > 2 + returns a list of prime numbers from 2 up to N (inclusive) + This function is more efficient as function 'sieveEr(...)' """ # precondition @@ -144,8 +144,8 @@ def getPrimeNumbers(N): def primeFactorization(number): """ - input: positive integer 'number' - returns a list of the prime number factors of 'number' + input: positive integer 'number' + returns a list of the prime number factors of 'number' """ # precondition @@ -188,8 +188,8 @@ def primeFactorization(number): def greatestPrimeFactor(number): """ - input: positive integer 'number' >= 0 - returns the greatest prime number factor of 'number' + input: positive integer 'number' >= 0 + returns the greatest prime number factor of 'number' """ # precondition @@ -215,8 +215,8 @@ def greatestPrimeFactor(number): def smallestPrimeFactor(number): """ - input: integer 'number' >= 0 - returns the smallest prime number factor of 'number' + input: integer 'number' >= 0 + returns the smallest prime number factor of 'number' """ # precondition @@ -242,8 +242,8 @@ def smallestPrimeFactor(number): def isEven(number): """ - input: integer 'number' - returns true if 'number' is even, otherwise false. + input: integer 'number' + returns true if 'number' is even, otherwise false. """ # precondition @@ -258,8 +258,8 @@ def isEven(number): def isOdd(number): """ - input: integer 'number' - returns true if 'number' is odd, otherwise false. + input: integer 'number' + returns true if 'number' is odd, otherwise false. """ # precondition @@ -274,9 +274,9 @@ def isOdd(number): def goldbach(number): """ - Goldbach's assumption - input: a even positive integer 'number' > 2 - returns a list of two prime numbers whose sum is equal to 'number' + Goldbach's assumption + input: a even positive integer 'number' > 2 + returns a list of two prime numbers whose sum is equal to 'number' """ # precondition @@ -329,9 +329,9 @@ def goldbach(number): def gcd(number1, number2): """ - Greatest common divisor - input: two positive integer 'number1' and 'number2' - returns the greatest common divisor of 'number1' and 'number2' + Greatest common divisor + input: two positive integer 'number1' and 'number2' + returns the greatest common divisor of 'number1' and 'number2' """ # precondition @@ -363,9 +363,9 @@ def gcd(number1, number2): def kgV(number1, number2): """ - Least common multiple - input: two positive integer 'number1' and 'number2' - returns the least common multiple of 'number1' and 'number2' + Least common multiple + input: two positive integer 'number1' and 'number2' + returns the least common multiple of 'number1' and 'number2' """ # precondition @@ -443,9 +443,9 @@ def kgV(number1, number2): def getPrime(n): """ - Gets the n-th prime number. - input: positive integer 'n' >= 0 - returns the n-th prime number, beginning at index 0 + Gets the n-th prime number. + input: positive integer 'n' >= 0 + returns the n-th prime number, beginning at index 0 """ # precondition @@ -478,10 +478,10 @@ def getPrime(n): def getPrimesBetween(pNumber1, pNumber2): """ - input: prime numbers 'pNumber1' and 'pNumber2' - pNumber1 < pNumber2 - returns a list of all prime numbers between 'pNumber1' (exclusive) - and 'pNumber2' (exclusive) + input: prime numbers 'pNumber1' and 'pNumber2' + pNumber1 < pNumber2 + returns a list of all prime numbers between 'pNumber1' (exclusive) + and 'pNumber2' (exclusive) """ # precondition @@ -522,8 +522,8 @@ def getPrimesBetween(pNumber1, pNumber2): def getDivisors(n): """ - input: positive integer 'n' >= 1 - returns all divisors of n (inclusive 1 and 'n') + input: positive integer 'n' >= 1 + returns all divisors of n (inclusive 1 and 'n') """ # precondition @@ -547,8 +547,8 @@ def getDivisors(n): def isPerfectNumber(number): """ - input: positive integer 'number' > 1 - returns true if 'number' is a perfect number otherwise false. + input: positive integer 'number' > 1 + returns true if 'number' is a perfect number otherwise false. """ # precondition @@ -574,9 +574,9 @@ def isPerfectNumber(number): def simplifyFraction(numerator, denominator): """ - input: two integer 'numerator' and 'denominator' - assumes: 'denominator' != 0 - returns: a tuple with simplify numerator and denominator. + input: two integer 'numerator' and 'denominator' + assumes: 'denominator' != 0 + returns: a tuple with simplify numerator and denominator. """ # precondition @@ -604,8 +604,8 @@ def simplifyFraction(numerator, denominator): def factorial(n): """ - input: positive integer 'n' - returns the factorial of 'n' (n!) + input: positive integer 'n' + returns the factorial of 'n' (n!) """ # precondition @@ -624,8 +624,8 @@ def factorial(n): def fib(n): """ - input: positive integer 'n' - returns the n-th fibonacci term , indexing by 0 + input: positive integer 'n' + returns the n-th fibonacci term , indexing by 0 """ # precondition diff --git a/project_euler/problem_09/sol2.py b/project_euler/problem_09/sol2.py index de7b12d40..d16835ca0 100644 --- a/project_euler/problem_09/sol2.py +++ b/project_euler/problem_09/sol2.py @@ -23,8 +23,7 @@ def solution(n): product = -1 d = 0 for a in range(1, n // 3): - """Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c - """ + """Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c""" b = (n * n - 2 * a * n) // (2 * n - 2 * a) c = n - a - b if c * c == (a * a + b * b): diff --git a/project_euler/problem_10/sol3.py b/project_euler/problem_10/sol3.py index e5bc0731d..739aaa9f1 100644 --- a/project_euler/problem_10/sol3.py +++ b/project_euler/problem_10/sol3.py @@ -12,7 +12,7 @@ smaller than n when n is smaller than 10 million. Only for positive numbers. def prime_sum(n: int) -> int: - """ Returns the sum of all the primes below n. + """Returns the sum of all the primes below n. >>> prime_sum(2_000_000) 142913828922 diff --git a/project_euler/problem_15/sol1.py b/project_euler/problem_15/sol1.py index 1be7d10ed..feeb3ddab 100644 --- a/project_euler/problem_15/sol1.py +++ b/project_euler/problem_15/sol1.py @@ -8,31 +8,31 @@ from math import factorial def lattice_paths(n): """ - Returns the number of paths possible in a n x n grid starting at top left - corner going to bottom right corner and being able to move right and down - only. + Returns the number of paths possible in a n x n grid starting at top left + corner going to bottom right corner and being able to move right and down + only. -bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 50 -1.008913445455642e+29 -bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 25 -126410606437752.0 -bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 23 -8233430727600.0 -bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 15 -155117520.0 -bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 1 -2.0 + bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 50 + 1.008913445455642e+29 + bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 25 + 126410606437752.0 + bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 23 + 8233430727600.0 + bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 15 + 155117520.0 + bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 1 + 2.0 - >>> lattice_paths(25) - 126410606437752 - >>> lattice_paths(23) - 8233430727600 - >>> lattice_paths(20) - 137846528820 - >>> lattice_paths(15) - 155117520 - >>> lattice_paths(1) - 2 + >>> lattice_paths(25) + 126410606437752 + >>> lattice_paths(23) + 8233430727600 + >>> lattice_paths(20) + 137846528820 + >>> lattice_paths(15) + 155117520 + >>> lattice_paths(1) + 2 """ n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, diff --git a/project_euler/problem_27/problem_27_sol1.py b/project_euler/problem_27/problem_27_sol1.py index 84b007a0b..e4833574c 100644 --- a/project_euler/problem_27/problem_27_sol1.py +++ b/project_euler/problem_27/problem_27_sol1.py @@ -39,17 +39,17 @@ def is_prime(k: int) -> bool: def solution(a_limit: int, b_limit: int) -> int: """ - >>> solution(1000, 1000) - -59231 - >>> solution(200, 1000) - -59231 - >>> solution(200, 200) - -4925 - >>> solution(-1000, 1000) - 0 - >>> solution(-1000, -1000) - 0 - """ + >>> solution(1000, 1000) + -59231 + >>> solution(200, 1000) + -59231 + >>> solution(200, 200) + -4925 + >>> solution(-1000, 1000) + 0 + >>> solution(-1000, -1000) + 0 + """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): diff --git a/project_euler/problem_56/sol1.py b/project_euler/problem_56/sol1.py index 2a00fa6a1..98094ea8e 100644 --- a/project_euler/problem_56/sol1.py +++ b/project_euler/problem_56/sol1.py @@ -1,18 +1,18 @@ def maximum_digital_sum(a: int, b: int) -> int: """ - Considering natural numbers of the form, a**b, where a, b < 100, - what is the maximum digital sum? - :param a: - :param b: - :return: - >>> maximum_digital_sum(10,10) - 45 + Considering natural numbers of the form, a**b, where a, b < 100, + what is the maximum digital sum? + :param a: + :param b: + :return: + >>> maximum_digital_sum(10,10) + 45 - >>> maximum_digital_sum(100,100) - 972 + >>> maximum_digital_sum(100,100) + 972 - >>> maximum_digital_sum(100,200) - 1872 + >>> maximum_digital_sum(100,200) + 1872 """ # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of diff --git a/sorts/merge_sort.py b/sorts/merge_sort.py index 572f38a57..4da29f32a 100644 --- a/sorts/merge_sort.py +++ b/sorts/merge_sort.py @@ -29,11 +29,13 @@ def merge_sort(collection: list) -> list: :param right: right collection :return: merge result """ + def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0) yield from left yield from right + return list(_merge()) if len(collection) <= 1: @@ -44,6 +46,7 @@ def merge_sort(collection: list) -> list: if __name__ == "__main__": import doctest + doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] diff --git a/sorts/recursive_bubble_sort.py b/sorts/recursive_bubble_sort.py index 79d706e61..82af89593 100644 --- a/sorts/recursive_bubble_sort.py +++ b/sorts/recursive_bubble_sort.py @@ -1,41 +1,42 @@ -def bubble_sort(list1): +def bubble_sort(list_data: list, length: int = 0) -> list: """ It is similar is bubble sort but recursive. - :param list1: mutable ordered sequence of elements + :param list_data: mutable ordered sequence of elements + :param length: length of list data :return: the same list in ascending order - >>> bubble_sort([0, 5, 2, 3, 2]) + >>> bubble_sort([0, 5, 2, 3, 2], 5) [0, 2, 2, 3, 5] - >>> bubble_sort([]) + >>> bubble_sort([], 0) [] - >>> bubble_sort([-2, -45, -5]) + >>> bubble_sort([-2, -45, -5], 3) [-45, -5, -2] - >>> bubble_sort([-23, 0, 6, -4, 34]) + >>> bubble_sort([-23, 0, 6, -4, 34], 5) [-23, -4, 0, 6, 34] - >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) + >>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34]) True - >>> bubble_sort(['z','a','y','b','x','c']) + >>> bubble_sort(['z','a','y','b','x','c'], 6) ['a', 'b', 'c', 'x', 'y', 'z'] + >>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) + [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] """ + length = length or len(list_data) + swapped = False + for i in range(length - 1): + if list_data[i] > list_data[i + 1]: + list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] + swapped = True - for i, num in enumerate(list1): - try: - if list1[i + 1] < num: - list1[i] = list1[i + 1] - list1[i + 1] = num - bubble_sort(list1) - except IndexError: - pass - return list1 + return list_data if not swapped else bubble_sort(list_data, length - 1) if __name__ == "__main__": - list1 = [33, 99, 22, 11, 66] - bubble_sort(list1) - print(list1) + import doctest + + doctest.testmod() diff --git a/strings/boyer_moore_search.py b/strings/boyer_moore_search.py index f340855d7..9d32a6943 100644 --- a/strings/boyer_moore_search.py +++ b/strings/boyer_moore_search.py @@ -25,7 +25,7 @@ class BoyerMooreSearch: self.textLen, self.patLen = len(text), len(pattern) def match_in_pattern(self, char): - """ finds the index of char in pattern in reverse order + """finds the index of char in pattern in reverse order Parameters : char (chr): character to be searched diff --git a/strings/capitalize.py b/strings/capitalize.py index 2a84a325b..63603aa07 100644 --- a/strings/capitalize.py +++ b/strings/capitalize.py @@ -16,7 +16,7 @@ def capitalize(sentence: str) -> str: '' """ if not sentence: - return '' + return "" lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)} return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] diff --git a/traversals/binary_tree_traversals.py b/traversals/binary_tree_traversals.py index 7f100e66f..50cdd5af7 100644 --- a/traversals/binary_tree_traversals.py +++ b/traversals/binary_tree_traversals.py @@ -53,11 +53,11 @@ def pre_order(node: TreeNode) -> None: >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order(root) - 1 2 4 5 3 6 7 + 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return - print(node.data, end=" ") + print(node.data, end=",") pre_order(node.left) pre_order(node.right) @@ -75,12 +75,12 @@ def in_order(node: TreeNode) -> None: >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order(root) - 4 2 5 1 6 3 7 + 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return in_order(node.left) - print(node.data, end=" ") + print(node.data, end=",") in_order(node.right) @@ -97,13 +97,13 @@ def post_order(node: TreeNode) -> None: >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order(root) - 4 5 2 6 7 3 1 + 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return post_order(node.left) post_order(node.right) - print(node.data, end=" ") + print(node.data, end=",") def level_order(node: TreeNode) -> None: @@ -119,7 +119,7 @@ def level_order(node: TreeNode) -> None: >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order(root) - 1 2 3 4 5 6 7 + 1,2,3,4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return @@ -127,7 +127,7 @@ def level_order(node: TreeNode) -> None: q.put(node) while not q.empty(): node_dequeued = q.get() - print(node_dequeued.data, end=" ") + print(node_dequeued.data, end=",") if node_dequeued.left: q.put(node_dequeued.left) if node_dequeued.right: @@ -146,10 +146,10 @@ def level_order_actual(node: TreeNode) -> None: >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 - >>> level_order_actual(root) - 1 - 2 3 - 4 5 6 7 + >>> level_order_actual(root) + 1, + 2,3, + 4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return @@ -159,7 +159,7 @@ def level_order_actual(node: TreeNode) -> None: list = [] while not q.empty(): node_dequeued = q.get() - print(node_dequeued.data, end=" ") + print(node_dequeued.data, end=",") if node_dequeued.left: list.append(node_dequeued.left) if node_dequeued.right: @@ -183,7 +183,7 @@ def pre_order_iter(node: TreeNode) -> None: >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order_iter(root) - 1 2 4 5 3 6 7 + 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return @@ -191,7 +191,7 @@ def pre_order_iter(node: TreeNode) -> None: n = node while n or stack: while n: # start from root node, find its left child - print(n.data, end=" ") + print(n.data, end=",") stack.append(n) n = n.left # end of while means current node doesn't have left child @@ -213,7 +213,7 @@ def in_order_iter(node: TreeNode) -> None: >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order_iter(root) - 4 2 5 1 6 3 7 + 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return @@ -224,7 +224,7 @@ def in_order_iter(node: TreeNode) -> None: stack.append(n) n = n.left n = stack.pop() - print(n.data, end=" ") + print(n.data, end=",") n = n.right @@ -241,7 +241,7 @@ def post_order_iter(node: TreeNode) -> None: >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order_iter(root) - 4 5 2 6 7 3 1 + 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return @@ -256,7 +256,7 @@ def post_order_iter(node: TreeNode) -> None: stack1.append(n.right) stack2.append(n) while stack2: # pop up from stack2 will be the post order - print(stack2.pop().data, end=" ") + print(stack2.pop().data, end=",") def prompt(s: str = "", width=50, char="*") -> str: