diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b97ef2889..f8d1a65db 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,7 +15,7 @@ repos: - id: auto-walrus - repo: https://github.com/psf/black - rev: 22.12.0 + rev: 23.1.0 hooks: - id: black @@ -26,6 +26,16 @@ repos: args: - --profile=black + - repo: https://github.com/tox-dev/pyproject-fmt + rev: "0.6.0" + hooks: + - id: pyproject-fmt + + - repo: https://github.com/abravalheri/validate-pyproject + rev: v0.12.1 + hooks: + - id: validate-pyproject + - repo: https://github.com/asottile/pyupgrade rev: v3.3.1 hooks: diff --git a/arithmetic_analysis/newton_raphson_new.py b/arithmetic_analysis/newton_raphson_new.py index dd1d7e092..472cb5b5a 100644 --- a/arithmetic_analysis/newton_raphson_new.py +++ b/arithmetic_analysis/newton_raphson_new.py @@ -59,7 +59,6 @@ def newton_raphson( # Let's Execute if __name__ == "__main__": - # Find root of trigonometric function # Find value of pi print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") diff --git a/backtracking/n_queens_math.py b/backtracking/n_queens_math.py index 2de784ded..23bd15906 100644 --- a/backtracking/n_queens_math.py +++ b/backtracking/n_queens_math.py @@ -107,7 +107,6 @@ def depth_first_search( # We iterate each column in the row to find all possible results in each row for col in range(n): - # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we diff --git a/blockchain/chinese_remainder_theorem.py b/blockchain/chinese_remainder_theorem.py index 54d861dd9..d3e75e779 100644 --- a/blockchain/chinese_remainder_theorem.py +++ b/blockchain/chinese_remainder_theorem.py @@ -53,6 +53,7 @@ def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- + # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: """ diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index a877256eb..07d21893f 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -230,7 +230,6 @@ def enigma( # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: - # 1st plugboard -------------------------- if symbol in plugboard: symbol = plugboard[symbol] diff --git a/ciphers/playfair_cipher.py b/ciphers/playfair_cipher.py index 89aedb7af..7279fb23e 100644 --- a/ciphers/playfair_cipher.py +++ b/ciphers/playfair_cipher.py @@ -39,7 +39,6 @@ def prepare_input(dirty: str) -> str: def generate_table(key: str) -> list[str]: - # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" diff --git a/ciphers/polybius.py b/ciphers/polybius.py index c81c1d395..3539ab70c 100644 --- a/ciphers/polybius.py +++ b/ciphers/polybius.py @@ -19,7 +19,6 @@ SQUARE = [ class PolybiusCipher: def __init__(self) -> None: - self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index ca9dfe20f..379ef0ef7 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -130,7 +130,6 @@ class XORCipher: try: with open(file) as fin: with open("encrypt.out", "w+") as fout: - # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) @@ -155,7 +154,6 @@ class XORCipher: try: with open(file) as fin: with open("decrypt.out", "w+") as fout: - # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) diff --git a/compression/lz77.py b/compression/lz77.py index 7c1a6f6a4..1b201c59f 100644 --- a/compression/lz77.py +++ b/compression/lz77.py @@ -89,7 +89,6 @@ class LZ77Compressor: # while there are still characters in text to compress while text: - # find the next encoding phrase # - triplet with offset, length, indicator (the next encoding character) token = self._find_encoding_token(text, search_buffer) diff --git a/computer_vision/cnn_classification.py b/computer_vision/cnn_classification.py index 59e4556e0..1c193fcbb 100644 --- a/computer_vision/cnn_classification.py +++ b/computer_vision/cnn_classification.py @@ -28,7 +28,6 @@ import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": - # Initialising the CNN # (Sequential- Building the model layer by layer) classifier = models.Sequential() diff --git a/computer_vision/harris_corner.py b/computer_vision/harris_corner.py index c8905bb6a..0cc7522bc 100644 --- a/computer_vision/harris_corner.py +++ b/computer_vision/harris_corner.py @@ -9,7 +9,6 @@ https://en.wikipedia.org/wiki/Harris_Corner_Detector class HarrisCorner: def __init__(self, k: float, window_size: int): - """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered @@ -25,7 +24,6 @@ class HarrisCorner: return str(self.k) def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: - """ Returns the image with corners identified img_path : path of the image @@ -68,7 +66,6 @@ class HarrisCorner: if __name__ == "__main__": - edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img) diff --git a/conversions/decimal_to_binary.py b/conversions/decimal_to_binary.py index cfda57ca7..973c47c8a 100644 --- a/conversions/decimal_to_binary.py +++ b/conversions/decimal_to_binary.py @@ -2,7 +2,6 @@ def decimal_to_binary(num: int) -> str: - """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary(0) diff --git a/conversions/molecular_chemistry.py b/conversions/molecular_chemistry.py index 0024eb5cb..51ffe534d 100644 --- a/conversions/molecular_chemistry.py +++ b/conversions/molecular_chemistry.py @@ -86,7 +86,6 @@ def pressure_and_volume_to_temperature( if __name__ == "__main__": - import doctest doctest.testmod() diff --git a/conversions/roman_numerals.py b/conversions/roman_numerals.py index 61215a0c0..75af2ac72 100644 --- a/conversions/roman_numerals.py +++ b/conversions/roman_numerals.py @@ -47,7 +47,7 @@ def int_to_roman(number: int) -> str: True """ result = [] - for (arabic, roman) in ROMAN: + for arabic, roman in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: diff --git a/conversions/temperature_conversions.py b/conversions/temperature_conversions.py index e5af46556..f7af6c8f1 100644 --- a/conversions/temperature_conversions.py +++ b/conversions/temperature_conversions.py @@ -380,7 +380,6 @@ def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: if __name__ == "__main__": - import doctest doctest.testmod() diff --git a/conversions/weight_conversion.py b/conversions/weight_conversion.py index 18c403731..5c032a497 100644 --- a/conversions/weight_conversion.py +++ b/conversions/weight_conversion.py @@ -307,7 +307,6 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float: if __name__ == "__main__": - import doctest doctest.testmod() diff --git a/data_structures/binary_tree/binary_tree_traversals.py b/data_structures/binary_tree/binary_tree_traversals.py index 54b1dc536..24dd1bd8c 100644 --- a/data_structures/binary_tree/binary_tree_traversals.py +++ b/data_structures/binary_tree/binary_tree_traversals.py @@ -105,7 +105,6 @@ def get_nodes_from_left_to_right( if not root: return if level == 1: - output.append(root.data) elif level > 1: populate_output(root.left, level - 1) diff --git a/data_structures/binary_tree/inorder_tree_traversal_2022.py b/data_structures/binary_tree/inorder_tree_traversal_2022.py index 08001738f..e94ba7013 100644 --- a/data_structures/binary_tree/inorder_tree_traversal_2022.py +++ b/data_structures/binary_tree/inorder_tree_traversal_2022.py @@ -58,7 +58,6 @@ def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return def make_tree() -> BinaryTreeNode | None: - root = insert(None, 15) insert(root, 10) insert(root, 25) diff --git a/data_structures/hashing/double_hash.py b/data_structures/hashing/double_hash.py index 453e0d131..be21e74ca 100644 --- a/data_structures/hashing/double_hash.py +++ b/data_structures/hashing/double_hash.py @@ -24,7 +24,6 @@ class DoubleHash(HashTable): super().__init__(*args, **kwargs) def __hash_function_2(self, value, data): - next_prime_gt = ( next_prime(value % self.size_table) if not is_prime(value % self.size_table) diff --git a/data_structures/hashing/hash_table.py b/data_structures/hashing/hash_table.py index 607454c82..7ca2f7c40 100644 --- a/data_structures/hashing/hash_table.py +++ b/data_structures/hashing/hash_table.py @@ -32,7 +32,6 @@ class HashTable: return key % self.size_table def _step_by_step(self, step_ord): - print(f"step {step_ord}") print(list(range(len(self.values)))) print(self.values) @@ -53,7 +52,6 @@ class HashTable: new_key = self.hash_function(key + 1) while self.values[new_key] is not None and self.values[new_key] != key: - if self.values.count(None) > 0: new_key = self.hash_function(new_key + 1) else: diff --git a/data_structures/heap/binomial_heap.py b/data_structures/heap/binomial_heap.py index d79fac7a9..2e05c5c80 100644 --- a/data_structures/heap/binomial_heap.py +++ b/data_structures/heap/binomial_heap.py @@ -174,7 +174,6 @@ class BinomialHeap: i.left_tree_size == i.parent.left_tree_size and i.left_tree_size != i.parent.parent.left_tree_size ): - # Neighbouring Nodes previous_node = i.left next_node = i.parent.parent @@ -233,7 +232,6 @@ class BinomialHeap: and self.bottom_root.left_tree_size == self.bottom_root.parent.left_tree_size ): - # Next node next_node = self.bottom_root.parent.parent diff --git a/data_structures/heap/skew_heap.py b/data_structures/heap/skew_heap.py index 490db061d..c4c13b082 100644 --- a/data_structures/heap/skew_heap.py +++ b/data_structures/heap/skew_heap.py @@ -71,7 +71,6 @@ class SkewHeap(Generic[T]): """ def __init__(self, data: Iterable[T] | None = ()) -> None: - """ >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) diff --git a/data_structures/linked_list/doubly_linked_list_two.py b/data_structures/linked_list/doubly_linked_list_two.py index 94b916a62..c19309c9f 100644 --- a/data_structures/linked_list/doubly_linked_list_two.py +++ b/data_structures/linked_list/doubly_linked_list_two.py @@ -80,7 +80,6 @@ class LinkedList: return None def set_head(self, node: Node) -> None: - if self.head is None: self.head = node self.tail = node @@ -143,7 +142,6 @@ class LinkedList: raise Exception("Node not found") def delete_value(self, value): - if (node := self.get_node(value)) is not None: if node == self.head: self.head = self.head.get_next() diff --git a/data_structures/stacks/prefix_evaluation.py b/data_structures/stacks/prefix_evaluation.py index 00df2c1e6..f48eca23d 100644 --- a/data_structures/stacks/prefix_evaluation.py +++ b/data_structures/stacks/prefix_evaluation.py @@ -36,7 +36,6 @@ def evaluate(expression): # iterate over the string in reverse order for c in expression.split()[::-1]: - # push operand to stack if is_operand(c): stack.append(int(c)) diff --git a/data_structures/stacks/stack_with_doubly_linked_list.py b/data_structures/stacks/stack_with_doubly_linked_list.py index a129665f2..50c5236e0 100644 --- a/data_structures/stacks/stack_with_doubly_linked_list.py +++ b/data_structures/stacks/stack_with_doubly_linked_list.py @@ -92,7 +92,6 @@ class Stack(Generic[T]): # Code execution starts here if __name__ == "__main__": - # Start with the empty stack stack: Stack[int] = Stack() diff --git a/data_structures/stacks/stock_span_problem.py b/data_structures/stacks/stock_span_problem.py index 19a81bd36..de423c1eb 100644 --- a/data_structures/stacks/stock_span_problem.py +++ b/data_structures/stacks/stock_span_problem.py @@ -9,7 +9,6 @@ on the current day is less than or equal to its price on the given day. def calculation_span(price, s): - n = len(price) # Create a stack and push index of fist element to it st = [] @@ -20,7 +19,6 @@ def calculation_span(price, s): # Calculate span values for rest of the elements for i in range(1, n): - # Pop elements from stack while stack is not # empty and top of stack is smaller than price[i] while len(st) > 0 and price[st[0]] <= price[i]: diff --git a/digital_image_processing/filters/bilateral_filter.py b/digital_image_processing/filters/bilateral_filter.py index 1afa01d3f..565da73f6 100644 --- a/digital_image_processing/filters/bilateral_filter.py +++ b/digital_image_processing/filters/bilateral_filter.py @@ -50,7 +50,6 @@ def bilateral_filter( size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): - img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) diff --git a/digital_image_processing/filters/local_binary_pattern.py b/digital_image_processing/filters/local_binary_pattern.py index e92e554a3..907fe2cb0 100644 --- a/digital_image_processing/filters/local_binary_pattern.py +++ b/digital_image_processing/filters/local_binary_pattern.py @@ -61,7 +61,6 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) if __name__ == "__main__": - # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE diff --git a/dynamic_programming/bitmask.py b/dynamic_programming/bitmask.py index f45250c9c..56bb8e96b 100644 --- a/dynamic_programming/bitmask.py +++ b/dynamic_programming/bitmask.py @@ -13,7 +13,6 @@ from collections import defaultdict class AssignmentUsingBitmask: def __init__(self, task_performed, total): - self.total_tasks = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N @@ -29,7 +28,6 @@ class AssignmentUsingBitmask: self.final_mask = (1 << len(task_performed)) - 1 def count_ways_until(self, mask, task_no): - # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 @@ -49,7 +47,6 @@ class AssignmentUsingBitmask: # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: - # if p is already given a task if mask & (1 << p): continue @@ -64,7 +61,6 @@ class AssignmentUsingBitmask: return self.dp[mask][task_no] def count_no_of_ways(self, task_performed): - # Store the list of persons for each task for i in range(len(task_performed)): for j in task_performed[i]: @@ -75,7 +71,6 @@ class AssignmentUsingBitmask: if __name__ == "__main__": - total_tasks = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. diff --git a/dynamic_programming/iterating_through_submasks.py b/dynamic_programming/iterating_through_submasks.py index 21c64dba4..4d0a250e8 100644 --- a/dynamic_programming/iterating_through_submasks.py +++ b/dynamic_programming/iterating_through_submasks.py @@ -9,7 +9,6 @@ from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: - """ Args: mask : number which shows mask ( always integer > 0, zero does not have any diff --git a/electronics/coulombs_law.py b/electronics/coulombs_law.py index e41c0410c..18c1a8179 100644 --- a/electronics/coulombs_law.py +++ b/electronics/coulombs_law.py @@ -8,7 +8,6 @@ COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2 def couloumbs_law( force: float, charge1: float, charge2: float, distance: float ) -> dict[str, float]: - """ Apply Coulomb's Law on any three given values. These can be force, charge1, charge2, or distance, and then in a Python dict return name/value pair of diff --git a/fractals/julia_sets.py b/fractals/julia_sets.py index 77d1d7c04..482e1eddf 100644 --- a/fractals/julia_sets.py +++ b/fractals/julia_sets.py @@ -170,7 +170,6 @@ def ignore_overflow_warnings() -> None: if __name__ == "__main__": - z_0 = prepare_grid(window_size, nb_pixels) ignore_overflow_warnings() # See file header for explanations diff --git a/fractals/mandelbrot.py b/fractals/mandelbrot.py index f97bcd170..84dbda997 100644 --- a/fractals/mandelbrot.py +++ b/fractals/mandelbrot.py @@ -114,7 +114,6 @@ def get_image( # loop through the image-coordinates for image_x in range(image_width): for image_y in range(image_height): - # determine the figure-coordinates based on the image-coordinates figure_height = figure_width / image_width * image_height figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width diff --git a/geodesy/lamberts_ellipsoidal_distance.py b/geodesy/lamberts_ellipsoidal_distance.py index 62ce59bb4..4805674e5 100644 --- a/geodesy/lamberts_ellipsoidal_distance.py +++ b/geodesy/lamberts_ellipsoidal_distance.py @@ -10,7 +10,6 @@ EQUATORIAL_RADIUS = 6378137 def lamberts_ellipsoidal_distance( lat1: float, lon1: float, lat2: float, lon2: float ) -> float: - """ Calculate the shortest distance along the surface of an ellipsoid between two points on the surface of earth given longitudes and latitudes diff --git a/graphs/a_star.py b/graphs/a_star.py index 793ba3bda..e8735179e 100644 --- a/graphs/a_star.py +++ b/graphs/a_star.py @@ -16,7 +16,6 @@ def search( cost: int, heuristic: list[list[int]], ) -> tuple[list[list[int]], list[list[int]]]: - closed = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the reference grid diff --git a/graphs/check_bipartite_graph_bfs.py b/graphs/check_bipartite_graph_bfs.py index 552b7eee2..7fc57cbc7 100644 --- a/graphs/check_bipartite_graph_bfs.py +++ b/graphs/check_bipartite_graph_bfs.py @@ -20,7 +20,6 @@ def check_bipartite(graph): visited[u] = True for neighbour in graph[u]: - if neighbour == u: return False diff --git a/graphs/graph_matrix.py b/graphs/graph_matrix.py index 987168426..4adc6c0bb 100644 --- a/graphs/graph_matrix.py +++ b/graphs/graph_matrix.py @@ -8,7 +8,6 @@ class Graph: self.graph[v - 1][u - 1] = 1 def show(self): - for i in self.graph: for j in i: print(j, end=" ") diff --git a/graphs/karger.py b/graphs/karger.py index f72128c81..3ef65c0d6 100644 --- a/graphs/karger.py +++ b/graphs/karger.py @@ -47,7 +47,6 @@ def partition_graph(graph: dict[str, list[str]]) -> set[tuple[str, str]]: graph_copy = {node: graph[node][:] for node in graph} while len(graph_copy) > 2: - # Choose a random edge. u = random.choice(list(graph_copy.keys())) v = random.choice(graph_copy[u]) diff --git a/graphs/minimum_spanning_tree_boruvka.py b/graphs/minimum_spanning_tree_boruvka.py index 6c72615cc..663d8e26c 100644 --- a/graphs/minimum_spanning_tree_boruvka.py +++ b/graphs/minimum_spanning_tree_boruvka.py @@ -4,7 +4,6 @@ class Graph: """ def __init__(self): - self.num_vertices = 0 self.num_edges = 0 self.adjacency = {} diff --git a/graphs/multi_heuristic_astar.py b/graphs/multi_heuristic_astar.py index cd8e37b00..0a18ede6e 100644 --- a/graphs/multi_heuristic_astar.py +++ b/graphs/multi_heuristic_astar.py @@ -33,7 +33,7 @@ class PriorityQueue: temp.append((pri, x)) (pri, x) = heapq.heappop(self.elements) temp.append((priority, item)) - for (pro, xxx) in temp: + for pro, xxx in temp: heapq.heappush(self.elements, (pro, xxx)) def remove_element(self, item): @@ -44,7 +44,7 @@ class PriorityQueue: while x != item: temp.append((pro, x)) (pro, x) = heapq.heappop(self.elements) - for (prito, yyy) in temp: + for prito, yyy in temp: heapq.heappush(self.elements, (prito, yyy)) def top_show(self): diff --git a/knapsack/recursive_approach_knapsack.py b/knapsack/recursive_approach_knapsack.py index d813981cb..9a8ed1886 100644 --- a/knapsack/recursive_approach_knapsack.py +++ b/knapsack/recursive_approach_knapsack.py @@ -46,7 +46,6 @@ def knapsack( if __name__ == "__main__": - import doctest doctest.testmod() diff --git a/linear_algebra/src/conjugate_gradient.py b/linear_algebra/src/conjugate_gradient.py index 418ae88a5..4cf566ec9 100644 --- a/linear_algebra/src/conjugate_gradient.py +++ b/linear_algebra/src/conjugate_gradient.py @@ -115,7 +115,6 @@ def conjugate_gradient( iterations = 0 while error > tol: - # Save this value so we only calculate the matrix-vector product once. w = np.dot(spd_matrix, p0) diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 5dc2b7118..b6305469e 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -74,7 +74,6 @@ def centroid_pairwise_dist(x, centroids): def assign_clusters(data, centroids): - # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data, centroids) @@ -100,10 +99,8 @@ def revise_centroids(data, k, cluster_assignment): def compute_heterogeneity(data, k, centroids, cluster_assignment): - heterogeneity = 0.0 for i in range(k): - # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i, :] diff --git a/machine_learning/self_organizing_map.py b/machine_learning/self_organizing_map.py index 057c2a76b..32fdf1d2b 100644 --- a/machine_learning/self_organizing_map.py +++ b/machine_learning/self_organizing_map.py @@ -49,7 +49,6 @@ def main() -> None: for _ in range(epochs): for j in range(len(training_samples)): - # training sample sample = training_samples[j] diff --git a/machine_learning/sequential_minimum_optimization.py b/machine_learning/sequential_minimum_optimization.py index f5185e1d9..9c45c3512 100644 --- a/machine_learning/sequential_minimum_optimization.py +++ b/machine_learning/sequential_minimum_optimization.py @@ -82,7 +82,6 @@ class SmoSVM: k = self._k state = None while True: - # 1: Find alpha1, alpha2 try: i1, i2 = self.choose_alpha.send(state) @@ -146,7 +145,6 @@ class SmoSVM: # Predict test samples def predict(self, test_samples, classify=True): - if test_samples.shape[1] > self.samples.shape[1]: raise ValueError( "Test samples' feature length does not equal to that of train samples" diff --git a/machine_learning/xgboost_classifier.py b/machine_learning/xgboost_classifier.py index 08967f171..1da933cf6 100644 --- a/machine_learning/xgboost_classifier.py +++ b/machine_learning/xgboost_classifier.py @@ -41,7 +41,6 @@ def xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier: def main() -> None: - """ >>> main() diff --git a/maths/armstrong_numbers.py b/maths/armstrong_numbers.py index f62991b74..26709b428 100644 --- a/maths/armstrong_numbers.py +++ b/maths/armstrong_numbers.py @@ -62,7 +62,7 @@ def pluperfect_number(n: int) -> bool: digit_histogram[rem] += 1 digit_total += 1 - for (cnt, i) in zip(digit_histogram, range(len(digit_histogram))): + for cnt, i in zip(digit_histogram, range(len(digit_histogram))): total += cnt * i**digit_total return n == total diff --git a/maths/binary_exponentiation.py b/maths/binary_exponentiation.py index 8dda5245c..147b4285f 100644 --- a/maths/binary_exponentiation.py +++ b/maths/binary_exponentiation.py @@ -5,7 +5,6 @@ def binary_exponentiation(a, n): - if n == 0: return 1 diff --git a/maths/combinations.py b/maths/combinations.py index 6db1d773f..a2324012c 100644 --- a/maths/combinations.py +++ b/maths/combinations.py @@ -39,7 +39,6 @@ def combinations(n: int, k: int) -> int: if __name__ == "__main__": - print( "The number of five-card hands possible from a standard", f"fifty-two card deck is: {combinations(52, 5)}\n", diff --git a/maths/decimal_isolate.py b/maths/decimal_isolate.py index cdf43ea5d..058ed1bb9 100644 --- a/maths/decimal_isolate.py +++ b/maths/decimal_isolate.py @@ -5,7 +5,6 @@ https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-poi def decimal_isolate(number: float, digit_amount: int) -> float: - """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. diff --git a/maths/fermat_little_theorem.py b/maths/fermat_little_theorem.py index 73af3e28c..eea03be24 100644 --- a/maths/fermat_little_theorem.py +++ b/maths/fermat_little_theorem.py @@ -6,7 +6,6 @@ def binary_exponentiation(a, n, mod): - if n == 0: return 1 diff --git a/maths/greedy_coin_change.py b/maths/greedy_coin_change.py index 29c2f1803..7cf669bcb 100644 --- a/maths/greedy_coin_change.py +++ b/maths/greedy_coin_change.py @@ -62,7 +62,6 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]: # Traverse through all denomination for denomination in reversed(denominations): - # Find denominations while int(total_value) >= int(denomination): total_value -= int(denomination) @@ -73,7 +72,6 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]: # Driver Code if __name__ == "__main__": - denominations = [] value = "0" diff --git a/maths/integration_by_simpson_approx.py b/maths/integration_by_simpson_approx.py index 408041de9..f77ae7613 100644 --- a/maths/integration_by_simpson_approx.py +++ b/maths/integration_by_simpson_approx.py @@ -35,7 +35,6 @@ xn = b def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: - """ Args: function : the function which's integration is desired diff --git a/maths/jaccard_similarity.py b/maths/jaccard_similarity.py index b299a8147..eab25188b 100644 --- a/maths/jaccard_similarity.py +++ b/maths/jaccard_similarity.py @@ -51,7 +51,6 @@ def jaccard_similarity(set_a, set_b, alternative_union=False): """ if isinstance(set_a, set) and isinstance(set_b, set): - intersection = len(set_a.intersection(set_b)) if alternative_union: @@ -62,7 +61,6 @@ def jaccard_similarity(set_a, set_b, alternative_union=False): return intersection / union if isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)): - intersection = [element for element in set_a if element in set_b] if alternative_union: diff --git a/maths/least_common_multiple.py b/maths/least_common_multiple.py index 0d087643e..621d93720 100644 --- a/maths/least_common_multiple.py +++ b/maths/least_common_multiple.py @@ -67,7 +67,6 @@ def benchmark(): class TestLeastCommonMultiple(unittest.TestCase): - test_inputs = [ (10, 20), (13, 15), diff --git a/maths/line_length.py b/maths/line_length.py index ea27ee904..b810f2d9a 100644 --- a/maths/line_length.py +++ b/maths/line_length.py @@ -10,7 +10,6 @@ def line_length( x_end: int | float, steps: int = 100, ) -> float: - """ Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths @@ -41,7 +40,6 @@ def line_length( length = 0.0 for _ in range(steps): - # Approximates curve as a sequence of linear lines and sums their length x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) diff --git a/maths/monte_carlo.py b/maths/monte_carlo.py index c13b8d0a4..474f1f65d 100644 --- a/maths/monte_carlo.py +++ b/maths/monte_carlo.py @@ -18,6 +18,7 @@ def pi_estimator(iterations: int): 5. Multiply this value by 4 to get your estimate of pi. 6. Print the estimated and numpy value of pi """ + # A local function to see if a dot lands in the circle. def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x**2) + (y**2)) diff --git a/maths/newton_raphson.py b/maths/newton_raphson.py index f2b7cb976..2c9cd1de9 100644 --- a/maths/newton_raphson.py +++ b/maths/newton_raphson.py @@ -19,7 +19,6 @@ def calc_derivative(f, a, h=0.001): def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False): - a = x0 # set the initial guess steps = [a] error = abs(f(a)) diff --git a/maths/numerical_integration.py b/maths/numerical_integration.py index 8f32fd356..f2d65f89e 100644 --- a/maths/numerical_integration.py +++ b/maths/numerical_integration.py @@ -12,7 +12,6 @@ def trapezoidal_area( x_end: int | float, steps: int = 100, ) -> float: - """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form @@ -40,7 +39,6 @@ def trapezoidal_area( area = 0.0 for _ in range(steps): - # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 diff --git a/maths/primelib.py b/maths/primelib.py index 9586227ea..81d573706 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -59,7 +59,6 @@ def is_prime(number: int) -> bool: status = False for divisor in range(2, int(round(sqrt(number))) + 1): - # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: @@ -95,9 +94,7 @@ def sieve_er(n): # actual sieve of erathostenes for i in range(len(begin_list)): - for j in range(i + 1, len(begin_list)): - if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 @@ -128,9 +125,7 @@ def get_prime_numbers(n): # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1): - if is_prime(number): - ans.append(number) # precondition @@ -160,14 +155,11 @@ def prime_factorization(number): quotient = number if number == 0 or number == 1: - ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(number): - while quotient != 1: - if is_prime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor @@ -298,11 +290,9 @@ def goldbach(number): loop = True while i < len_pn and loop: - j = i + 1 while j < len_pn and loop: - if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) @@ -345,7 +335,6 @@ def gcd(number1, number2): rest = 0 while number2 != 0: - rest = number1 % number2 number1 = number2 number2 = rest @@ -380,13 +369,11 @@ def kg_v(number1, number2): # for kgV (x,1) if number1 > 1 and number2 > 1: - # builds the prime factorization of 'number1' and 'number2' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: - prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) @@ -398,11 +385,8 @@ def kg_v(number1, number2): # iterates through primeFac1 for n in prime_fac_1: - if n not in done: - if n in prime_fac_2: - count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) @@ -410,7 +394,6 @@ def kg_v(number1, number2): ans *= n else: - count1 = prime_fac_1.count(n) for _ in range(count1): @@ -420,9 +403,7 @@ def kg_v(number1, number2): # iterates through primeFac2 for n in prime_fac_2: - if n not in done: - count2 = prime_fac_2.count(n) for _ in range(count2): @@ -455,7 +436,6 @@ def get_prime(n): ans = 2 # this variable holds the answer while index < n: - index += 1 ans += 1 # counts to the next number @@ -499,7 +479,6 @@ def get_primes_between(p_number_1, p_number_2): number += 1 while number < p_number_2: - ans.append(number) number += 1 @@ -534,7 +513,6 @@ def get_divisors(n): ans = [] # will be returned. for divisor in range(1, n + 1): - if n % divisor == 0: ans.append(divisor) @@ -638,7 +616,6 @@ def fib(n): ans = 1 # this will be return for _ in range(n - 1): - tmp = ans ans += fib1 fib1 = tmp diff --git a/maths/segmented_sieve.py b/maths/segmented_sieve.py index 35ed9702b..e950a83b7 100644 --- a/maths/segmented_sieve.py +++ b/maths/segmented_sieve.py @@ -25,7 +25,6 @@ def sieve(n: int) -> list[int]: while low <= n: temp = [True] * (high - low + 1) for each in in_prime: - t = math.floor(low / each) * each if t < low: t += each diff --git a/maths/two_pointer.py b/maths/two_pointer.py index ff234cddc..d0fb0fc9c 100644 --- a/maths/two_pointer.py +++ b/maths/two_pointer.py @@ -43,7 +43,6 @@ def two_pointer(nums: list[int], target: int) -> list[int]: j = len(nums) - 1 while i < j: - if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: diff --git a/maths/zellers_congruence.py b/maths/zellers_congruence.py index 624bbfe10..483fb000f 100644 --- a/maths/zellers_congruence.py +++ b/maths/zellers_congruence.py @@ -3,7 +3,6 @@ import datetime def zeller(date_input: str) -> str: - """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date diff --git a/matrix/largest_square_area_in_matrix.py b/matrix/largest_square_area_in_matrix.py index cf975cb7c..a93369c56 100644 --- a/matrix/largest_square_area_in_matrix.py +++ b/matrix/largest_square_area_in_matrix.py @@ -59,7 +59,6 @@ def largest_square_area_in_matrix_top_down_approch( """ def update_area_of_max_square(row: int, col: int) -> int: - # BASE CASE if row >= rows or col >= cols: return 0 @@ -138,7 +137,6 @@ def largest_square_area_in_matrix_bottom_up( largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): - right = dp_array[row][col + 1] diagonal = dp_array[row + 1][col + 1] bottom = dp_array[row + 1][col] @@ -169,7 +167,6 @@ def largest_square_area_in_matrix_bottom_up_space_optimization( largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): - right = current_row[col + 1] diagonal = next_row[col + 1] bottom = next_row[col] diff --git a/other/activity_selection.py b/other/activity_selection.py index 18ff6a24c..2cc08d959 100644 --- a/other/activity_selection.py +++ b/other/activity_selection.py @@ -25,7 +25,6 @@ def print_max_activities(start: list[int], finish: list[int]) -> None: # Consider rest of the activities for j in range(n): - # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it diff --git a/other/nested_brackets.py b/other/nested_brackets.py index 9dd9a0f04..3f61a4e70 100644 --- a/other/nested_brackets.py +++ b/other/nested_brackets.py @@ -15,14 +15,12 @@ brackets and returns true if S is nested and false otherwise. def is_balanced(s): - stack = [] open_brackets = set({"(", "[", "{"}) closed_brackets = set({")", "]", "}"}) open_to_closed = dict({"{": "}", "[": "]", "(": ")"}) for i in range(len(s)): - if s[i] in open_brackets: stack.append(s[i]) diff --git a/other/scoring_algorithm.py b/other/scoring_algorithm.py index 1e6293f84..00d87cfc0 100644 --- a/other/scoring_algorithm.py +++ b/other/scoring_algorithm.py @@ -26,7 +26,6 @@ Thus the weights for each column are as follows: def procentual_proximity( source_data: list[list[float]], weights: list[int] ) -> list[list[float]]: - """ weights - int list possible values - 0 / 1 diff --git a/other/sdes.py b/other/sdes.py index 695675000..31105984b 100644 --- a/other/sdes.py +++ b/other/sdes.py @@ -54,7 +54,6 @@ def function(expansion, s0, s1, key, message): if __name__ == "__main__": - key = input("Enter 10 bit key: ") message = input("Enter 8 bit message: ") diff --git a/physics/casimir_effect.py b/physics/casimir_effect.py index ee8a6c1eb..e4a77e5b5 100644 --- a/physics/casimir_effect.py +++ b/physics/casimir_effect.py @@ -47,7 +47,6 @@ SPEED_OF_LIGHT = 3e8 # unit of c : m * s^-1 def casimir_force(force: float, area: float, distance: float) -> dict[str, float]: - """ Input Parameters ---------------- diff --git a/physics/hubble_parameter.py b/physics/hubble_parameter.py index 798564722..6bc62e713 100644 --- a/physics/hubble_parameter.py +++ b/physics/hubble_parameter.py @@ -34,7 +34,6 @@ def hubble_parameter( dark_energy: float, redshift: float, ) -> float: - """ Input Parameters ---------------- diff --git a/physics/newtons_law_of_gravitation.py b/physics/newtons_law_of_gravitation.py index 0bb27bb24..4bbeddd61 100644 --- a/physics/newtons_law_of_gravitation.py +++ b/physics/newtons_law_of_gravitation.py @@ -28,7 +28,6 @@ GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: - """ Input Parameters ---------------- diff --git a/project_euler/problem_004/sol1.py b/project_euler/problem_004/sol1.py index b1e229289..f237afdd9 100644 --- a/project_euler/problem_004/sol1.py +++ b/project_euler/problem_004/sol1.py @@ -32,12 +32,10 @@ def solution(n: int = 998001) -> int: # fetches the next number for number in range(n - 1, 9999, -1): - str_number = str(number) # checks whether 'str_number' is a palindrome. if str_number == str_number[::-1]: - divisor = 999 # if 'number' is a product of two 3-digit numbers diff --git a/project_euler/problem_074/sol2.py b/project_euler/problem_074/sol2.py index d76bb014d..b54bc023e 100644 --- a/project_euler/problem_074/sol2.py +++ b/project_euler/problem_074/sol2.py @@ -111,7 +111,6 @@ def solution(chain_length: int = 60, number_limit: int = 1000000) -> int: chain_sets_lengths: dict[int, int] = {} for start_chain_element in range(1, number_limit): - # The temporary set will contain the elements of the chain chain_set = set() chain_set_length = 0 diff --git a/project_euler/problem_089/sol1.py b/project_euler/problem_089/sol1.py index 83609cd23..123159bdc 100644 --- a/project_euler/problem_089/sol1.py +++ b/project_euler/problem_089/sol1.py @@ -138,5 +138,4 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int: if __name__ == "__main__": - print(f"{solution() = }") diff --git a/project_euler/problem_092/sol1.py b/project_euler/problem_092/sol1.py index 33a6c0694..8d3f0c9dd 100644 --- a/project_euler/problem_092/sol1.py +++ b/project_euler/problem_092/sol1.py @@ -15,7 +15,6 @@ DIGITS_SQUARED = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10000 def next_number(number: int) -> int: - """ Returns the next number of the chain by adding the square of each digit to form a new number. @@ -31,7 +30,6 @@ def next_number(number: int) -> int: sum_of_digits_squared = 0 while number: - # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 diff --git a/quantum/q_fourier_transform.py b/quantum/q_fourier_transform.py index 07a257579..762ac4081 100644 --- a/quantum/q_fourier_transform.py +++ b/quantum/q_fourier_transform.py @@ -72,7 +72,6 @@ def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts counter = number_of_qubits for i in range(counter): - quantum_circuit.h(number_of_qubits - i - 1) counter -= 1 for j in range(counter): diff --git a/quantum/quantum_teleportation.py b/quantum/quantum_teleportation.py index d04b44d15..5da79ed20 100644 --- a/quantum/quantum_teleportation.py +++ b/quantum/quantum_teleportation.py @@ -18,7 +18,6 @@ from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, exec def quantum_teleportation( theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2 ) -> qiskit.result.counts.Counts: - """ # >>> quantum_teleportation() #{'00': 500, '11': 500} # ideally diff --git a/scheduling/highest_response_ratio_next.py b/scheduling/highest_response_ratio_next.py index a5c62ddbe..9c999ec65 100644 --- a/scheduling/highest_response_ratio_next.py +++ b/scheduling/highest_response_ratio_next.py @@ -37,7 +37,6 @@ def calculate_turn_around_time( arrival_time.sort() while no_of_process > finished_process_count: - """ If the current time is less than the arrival time of the process that arrives first among the processes that have not been performed, @@ -94,7 +93,6 @@ def calculate_waiting_time( if __name__ == "__main__": - no_of_process = 5 process_name = ["A", "B", "C", "D", "E"] arrival_time = [1, 2, 3, 4, 5] diff --git a/searches/binary_search.py b/searches/binary_search.py index 88fee4715..05dadd4fe 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -261,7 +261,6 @@ def binary_search_std_lib(sorted_collection: list[int], item: int) -> int | None def binary_search_by_recursion( sorted_collection: list[int], item: int, left: int, right: int ) -> int | None: - """Pure implementation of binary search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be diff --git a/searches/interpolation_search.py b/searches/interpolation_search.py index 35e6bc506..49194c260 100644 --- a/searches/interpolation_search.py +++ b/searches/interpolation_search.py @@ -49,7 +49,6 @@ def interpolation_search(sorted_collection, item): def interpolation_search_by_recursion(sorted_collection, item, left, right): - """Pure implementation of interpolation search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable diff --git a/searches/tabu_search.py b/searches/tabu_search.py index 3e1728286..d998ddc55 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -220,7 +220,6 @@ def tabu_search( while not found: i = 0 while i < len(best_solution): - if best_solution[i] != solution[i]: first_exchange_node = best_solution[i] second_exchange_node = solution[i] diff --git a/searches/ternary_search.py b/searches/ternary_search.py index 9830cce36..cb36e72fa 100644 --- a/searches/ternary_search.py +++ b/searches/ternary_search.py @@ -103,7 +103,6 @@ def ite_ternary_search(array: list[int], target: int) -> int: left = two_third + 1 else: - left = one_third + 1 right = two_third - 1 else: diff --git a/sorts/comb_sort.py b/sorts/comb_sort.py index 16bd10c78..3c8b1e99a 100644 --- a/sorts/comb_sort.py +++ b/sorts/comb_sort.py @@ -37,7 +37,6 @@ def comb_sort(data: list) -> list: completed = False while not completed: - # Update the gap value for a next comb gap = int(gap / shrink_factor) if gap <= 1: diff --git a/sorts/odd_even_sort.py b/sorts/odd_even_sort.py index 9ef4462c7..7dfe03054 100644 --- a/sorts/odd_even_sort.py +++ b/sorts/odd_even_sort.py @@ -30,7 +30,6 @@ def odd_even_sort(input_list: list) -> list: is_sorted = True for i in range(0, len(input_list) - 1, 2): # iterating over all even indices if input_list[i] > input_list[i + 1]: - input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order is_sorted = False diff --git a/sorts/odd_even_transposition_parallel.py b/sorts/odd_even_transposition_parallel.py index b656df3a3..87b0e4d1e 100644 --- a/sorts/odd_even_transposition_parallel.py +++ b/sorts/odd_even_transposition_parallel.py @@ -34,7 +34,6 @@ def oe_process(position, value, l_send, r_send, lr_cv, rr_cv, result_pipe): # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0, 10): - if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() diff --git a/sorts/random_normal_distribution_quicksort.py b/sorts/random_normal_distribution_quicksort.py index 5777d5cb2..f7f60903c 100644 --- a/sorts/random_normal_distribution_quicksort.py +++ b/sorts/random_normal_distribution_quicksort.py @@ -19,7 +19,6 @@ def _in_place_quick_sort(a, start, end): def _in_place_partition(a, start, end): - count = 0 pivot = randint(start, end) temp = a[end] @@ -27,7 +26,6 @@ def _in_place_partition(a, start, end): a[pivot] = temp new_pivot_index = start - 1 for index in range(start, end): - count += 1 if a[index] < a[end]: # check if current val is less than pivot value new_pivot_index = new_pivot_index + 1 diff --git a/sorts/shrink_shell_sort.py b/sorts/shrink_shell_sort.py index 69992bfb7..f77b73d01 100644 --- a/sorts/shrink_shell_sort.py +++ b/sorts/shrink_shell_sort.py @@ -44,7 +44,6 @@ def shell_sort(collection: list) -> list: # Continue sorting until the gap is 1 while gap > 1: - # Decrease the gap value gap = int(gap / shrink) diff --git a/sorts/stooge_sort.py b/sorts/stooge_sort.py index de997a85d..9a5bedeae 100644 --- a/sorts/stooge_sort.py +++ b/sorts/stooge_sort.py @@ -12,7 +12,6 @@ def stooge_sort(arr): def stooge(arr, i, h): - if i >= h: return diff --git a/sorts/tim_sort.py b/sorts/tim_sort.py index b95ff34cf..c90c7e803 100644 --- a/sorts/tim_sort.py +++ b/sorts/tim_sort.py @@ -73,7 +73,6 @@ def tim_sort(lst): def main(): - lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) diff --git a/strings/dna.py b/strings/dna.py index c2b96110b..33e1063f4 100644 --- a/strings/dna.py +++ b/strings/dna.py @@ -2,7 +2,6 @@ import re def dna(dna: str) -> str: - """ https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand diff --git a/strings/hamming_distance.py b/strings/hamming_distance.py index 5de27dc77..a28949172 100644 --- a/strings/hamming_distance.py +++ b/strings/hamming_distance.py @@ -35,7 +35,6 @@ def hamming_distance(string1: str, string2: str) -> int: if __name__ == "__main__": - import doctest doctest.testmod() diff --git a/strings/levenshtein_distance.py b/strings/levenshtein_distance.py index 9f7a7e3e6..7be4074dc 100644 --- a/strings/levenshtein_distance.py +++ b/strings/levenshtein_distance.py @@ -44,11 +44,9 @@ def levenshtein_distance(first_word: str, second_word: str) -> int: previous_row = list(range(len(second_word) + 1)) for i, c1 in enumerate(first_word): - current_row = [i + 1] for j, c2 in enumerate(second_word): - # Calculate insertions, deletions and substitutions insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 diff --git a/strings/prefix_function.py b/strings/prefix_function.py index 6eca01635..65bbe9100 100644 --- a/strings/prefix_function.py +++ b/strings/prefix_function.py @@ -29,7 +29,6 @@ def prefix_function(input_string: str) -> list: prefix_result = [0] * len(input_string) for i in range(1, len(input_string)): - # use last results for better performance - dynamic programming j = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: diff --git a/strings/text_justification.py b/strings/text_justification.py index 5e86456c2..b0ef12231 100644 --- a/strings/text_justification.py +++ b/strings/text_justification.py @@ -33,7 +33,6 @@ def text_justification(word: str, max_width: int) -> list: words = word.split() def justify(line: list, width: int, max_width: int) -> str: - overall_spaces_count = max_width - width words_count = len(line) if len(line) == 1: diff --git a/web_programming/fetch_anime_and_play.py b/web_programming/fetch_anime_and_play.py index e11948d0a..3bd4f704d 100644 --- a/web_programming/fetch_anime_and_play.py +++ b/web_programming/fetch_anime_and_play.py @@ -8,7 +8,6 @@ BASE_URL = "https://ww1.gogoanime2.org" def search_scraper(anime_name: str) -> list: - """[summary] Take an url and @@ -66,7 +65,6 @@ def search_scraper(anime_name: str) -> list: def search_anime_episode_list(episode_endpoint: str) -> list: - """[summary] Take an url and @@ -116,7 +114,6 @@ def search_anime_episode_list(episode_endpoint: str) -> list: def get_anime_episode(episode_endpoint: str) -> list: - """[summary] Get click url and download url from episode url @@ -153,7 +150,6 @@ def get_anime_episode(episode_endpoint: str) -> list: if __name__ == "__main__": - anime_name = input("Enter anime name: ").strip() anime_list = search_scraper(anime_name) print("\n") @@ -161,9 +157,8 @@ if __name__ == "__main__": if len(anime_list) == 0: print("No anime found with this name") else: - print(f"Found {len(anime_list)} results: ") - for (i, anime) in enumerate(anime_list): + for i, anime in enumerate(anime_list): anime_title = anime["title"] print(f"{i+1}. {anime_title}") @@ -176,7 +171,7 @@ if __name__ == "__main__": print("No episode found for this anime") else: print(f"Found {len(episode_list)} results: ") - for (i, episode) in enumerate(episode_list): + for i, episode in enumerate(episode_list): print(f"{i+1}. {episode['title']}") episode_choice = int(input("\nChoose an episode by serial no: ").strip()) diff --git a/web_programming/fetch_well_rx_price.py b/web_programming/fetch_well_rx_price.py index 5174f39f9..ee51b9a50 100644 --- a/web_programming/fetch_well_rx_price.py +++ b/web_programming/fetch_well_rx_price.py @@ -37,7 +37,6 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None: """ try: - # Has user provided both inputs? if not drug_name or not zip_code: return None @@ -58,7 +57,6 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None: grid_list = soup.find_all("div", {"class": "grid-x pharmCard"}) if grid_list and len(grid_list) > 0: for grid in grid_list: - # Get the pharmacy price. pharmacy_name = grid.find("p", {"class": "list-title"}).text @@ -79,7 +77,6 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None: if __name__ == "__main__": - # Enter a drug name and a zip code drug_name = input("Enter drug name: ").strip() zip_code = input("Enter zip code: ").strip() @@ -89,10 +86,8 @@ if __name__ == "__main__": ) if pharmacy_price_list: - print(f"\nSearch results for {drug_name} at location {zip_code}:") for pharmacy_price in pharmacy_price_list: - name = pharmacy_price["pharmacy_name"] price = pharmacy_price["price"] diff --git a/web_programming/get_user_tweets.py b/web_programming/get_user_tweets.py index 28cf85541..3abc69715 100644 --- a/web_programming/get_user_tweets.py +++ b/web_programming/get_user_tweets.py @@ -10,7 +10,6 @@ access_secret = "" def get_all_tweets(screen_name: str) -> None: - # authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret)