diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e0de70b01..d2558b90a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -40,7 +40,10 @@ repos: - --ignore=E203,W503 - --max-complexity=25 - --max-line-length=88 - additional_dependencies: [flake8-builtins, pep8-naming] + additional_dependencies: + - flake8-bugbear + - flake8-builtins + - pep8-naming - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.982 diff --git a/arithmetic_analysis/jacobi_iteration_method.py b/arithmetic_analysis/jacobi_iteration_method.py index 0aab4db20..3087309e8 100644 --- a/arithmetic_analysis/jacobi_iteration_method.py +++ b/arithmetic_analysis/jacobi_iteration_method.py @@ -110,7 +110,7 @@ def jacobi_iteration_method( strictly_diagonally_dominant(table) # Iterates the whole matrix for given number of times - for i in range(iterations): + for _ in range(iterations): new_val = [] for row in range(rows): temp = 0 diff --git a/arithmetic_analysis/newton_forward_interpolation.py b/arithmetic_analysis/newton_forward_interpolation.py index 490e0687f..466f6c18c 100644 --- a/arithmetic_analysis/newton_forward_interpolation.py +++ b/arithmetic_analysis/newton_forward_interpolation.py @@ -23,7 +23,7 @@ def ucal(u: float, p: int) -> float: def main() -> None: n = int(input("enter the numbers of values: ")) y: list[list[float]] = [] - for i in range(n): + for _ in range(n): y.append([]) for i in range(n): for j in range(n): diff --git a/arithmetic_analysis/secant_method.py b/arithmetic_analysis/secant_method.py index 45bcb185f..d28a46206 100644 --- a/arithmetic_analysis/secant_method.py +++ b/arithmetic_analysis/secant_method.py @@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float """ x0 = lower_bound x1 = upper_bound - for i in range(0, repeats): + for _ in range(0, repeats): x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)) return x1 diff --git a/audio_filters/butterworth_filter.py b/audio_filters/butterworth_filter.py index 409cfeb1d..cffedb7a6 100644 --- a/audio_filters/butterworth_filter.py +++ b/audio_filters/butterworth_filter.py @@ -11,7 +11,7 @@ Alternatively you can use scipy.signal.butter, which should yield the same resul def make_lowpass( - frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) + frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a low-pass filter @@ -39,7 +39,7 @@ def make_lowpass( def make_highpass( - frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) + frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a high-pass filter @@ -67,7 +67,7 @@ def make_highpass( def make_bandpass( - frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) + frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a band-pass filter @@ -96,7 +96,7 @@ def make_bandpass( def make_allpass( - frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) + frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates an all-pass filter @@ -121,7 +121,10 @@ def make_allpass( def make_peak( - frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) + frequency: int, + samplerate: int, + gain_db: float, + q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a peak filter @@ -150,7 +153,10 @@ def make_peak( def make_lowshelf( - frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) + frequency: int, + samplerate: int, + gain_db: float, + q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a low-shelf filter @@ -184,7 +190,10 @@ def make_lowshelf( def make_highshelf( - frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) + frequency: int, + samplerate: int, + gain_db: float, + q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a high-shelf filter diff --git a/backtracking/sum_of_subsets.py b/backtracking/sum_of_subsets.py index 8348544c0..128e29071 100644 --- a/backtracking/sum_of_subsets.py +++ b/backtracking/sum_of_subsets.py @@ -39,14 +39,14 @@ def create_state_space_tree( if sum(path) == max_sum: result.append(path) return - for num_index in range(num_index, len(nums)): + for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, - num_index + 1, - path + [nums[num_index]], + index + 1, + path + [nums[index]], result, - remaining_nums_sum - nums[num_index], + remaining_nums_sum - nums[index], ) diff --git a/boolean_algebra/quine_mc_cluskey.py b/boolean_algebra/quine_mc_cluskey.py index 9aa9b10c8..5bd7117bb 100644 --- a/boolean_algebra/quine_mc_cluskey.py +++ b/boolean_algebra/quine_mc_cluskey.py @@ -56,7 +56,7 @@ def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[st temp = [] for minterm in minterms: string = "" - for i in range(no_of_variable): + for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) diff --git a/ciphers/mixed_keyword_cypher.py b/ciphers/mixed_keyword_cypher.py index 178902173..f55c9c428 100644 --- a/ciphers/mixed_keyword_cypher.py +++ b/ciphers/mixed_keyword_cypher.py @@ -40,7 +40,7 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: k = 0 for _ in range(r): s = [] - for j in range(len_temp): + for _ in range(len_temp): s.append(temp[k]) if not (k < 25): break diff --git a/ciphers/rabin_miller.py b/ciphers/rabin_miller.py index 0aab80eb9..410d559d4 100644 --- a/ciphers/rabin_miller.py +++ b/ciphers/rabin_miller.py @@ -11,7 +11,7 @@ def rabin_miller(num: int) -> bool: s = s // 2 t += 1 - for trials in range(5): + for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: diff --git a/compression/burrows_wheeler.py b/compression/burrows_wheeler.py index 4ad99a642..0916b8a65 100644 --- a/compression/burrows_wheeler.py +++ b/compression/burrows_wheeler.py @@ -154,7 +154,7 @@ def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: ) ordered_rotations = [""] * len(bwt_string) - for x in range(len(bwt_string)): + for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() diff --git a/data_structures/binary_tree/binary_search_tree_recursive.py b/data_structures/binary_tree/binary_search_tree_recursive.py index 0d0ac8fd1..97eb8e25b 100644 --- a/data_structures/binary_tree/binary_search_tree_recursive.py +++ b/data_structures/binary_tree/binary_search_tree_recursive.py @@ -357,7 +357,7 @@ class BinarySearchTreeTest(unittest.TestCase): assert t.root.left.left.parent == t.root.left assert t.root.left.left.label == 1 - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 t.put(1) def test_search(self) -> None: @@ -369,7 +369,7 @@ class BinarySearchTreeTest(unittest.TestCase): node = t.search(13) assert node.label == 13 - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 t.search(2) def test_remove(self) -> None: @@ -515,7 +515,7 @@ class BinarySearchTreeTest(unittest.TestCase): assert t.get_max_label() == 14 t.empty() - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 t.get_max_label() def test_get_min_label(self) -> None: @@ -524,7 +524,7 @@ class BinarySearchTreeTest(unittest.TestCase): assert t.get_min_label() == 1 t.empty() - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 t.get_min_label() def test_inorder_traversal(self) -> None: diff --git a/data_structures/linked_list/circular_linked_list.py b/data_structures/linked_list/circular_linked_list.py index 6fec0a125..67a63cd55 100644 --- a/data_structures/linked_list/circular_linked_list.py +++ b/data_structures/linked_list/circular_linked_list.py @@ -94,25 +94,25 @@ def test_circular_linked_list() -> None: try: circular_linked_list.delete_front() - assert False # This should not happen + raise AssertionError() # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() - assert False # This should not happen + raise AssertionError() # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1) - assert False + raise AssertionError() except IndexError: assert True try: circular_linked_list.delete_nth(0) - assert False + raise AssertionError() except IndexError: assert True diff --git a/data_structures/linked_list/doubly_linked_list.py b/data_structures/linked_list/doubly_linked_list.py index 0eb3cf101..9e996ef0f 100644 --- a/data_structures/linked_list/doubly_linked_list.py +++ b/data_structures/linked_list/doubly_linked_list.py @@ -96,7 +96,7 @@ class DoublyLinkedList: self.tail = new_node else: temp = self.head - for i in range(0, index): + for _ in range(0, index): temp = temp.next temp.previous.next = new_node new_node.previous = temp.previous @@ -145,7 +145,7 @@ class DoublyLinkedList: self.tail.next = None else: temp = self.head - for i in range(0, index): + for _ in range(0, index): temp = temp.next delete_node = temp temp.next.previous = temp.previous @@ -194,13 +194,13 @@ def test_doubly_linked_list() -> None: try: linked_list.delete_head() - assert False # This should not happen. + raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() - assert False # This should not happen. + raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. diff --git a/data_structures/linked_list/middle_element_of_linked_list.py b/data_structures/linked_list/middle_element_of_linked_list.py index 0c6250f3b..86dad6b41 100644 --- a/data_structures/linked_list/middle_element_of_linked_list.py +++ b/data_structures/linked_list/middle_element_of_linked_list.py @@ -62,7 +62,7 @@ class LinkedList: if __name__ == "__main__": link = LinkedList() - for i in range(int(input().strip())): + for _ in range(int(input().strip())): data = int(input().strip()) link.push(data) print(link.middle_element()) diff --git a/data_structures/linked_list/singly_linked_list.py b/data_structures/linked_list/singly_linked_list.py index 59d7c512b..89a05ae81 100644 --- a/data_structures/linked_list/singly_linked_list.py +++ b/data_structures/linked_list/singly_linked_list.py @@ -132,7 +132,7 @@ class LinkedList: if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head - for i in range(index): + for _ in range(index): current = current.next current.data = data @@ -352,13 +352,13 @@ def test_singly_linked_list() -> None: try: linked_list.delete_head() - assert False # This should not happen. + raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() - assert False # This should not happen. + raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. diff --git a/data_structures/linked_list/skip_list.py b/data_structures/linked_list/skip_list.py index 176049120..a667e3e9b 100644 --- a/data_structures/linked_list/skip_list.py +++ b/data_structures/linked_list/skip_list.py @@ -205,7 +205,7 @@ class SkipList(Generic[KT, VT]): if level > self.level: # After level increase we have to add additional nodes to head. - for i in range(self.level - 1, level): + for _ in range(self.level - 1, level): update_vector.append(self.head) self.level = level @@ -407,7 +407,7 @@ def test_iter_always_yields_sorted_values(): def pytests(): - for i in range(100): + for _ in range(100): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() diff --git a/data_structures/queue/queue_on_list.py b/data_structures/queue/queue_on_list.py index 485cf0b6f..71fca6b2f 100644 --- a/data_structures/queue/queue_on_list.py +++ b/data_structures/queue/queue_on_list.py @@ -37,7 +37,7 @@ class Queue: number of times to rotate queue""" def rotate(self, rotation): - for i in range(rotation): + for _ in range(rotation): self.put(self.get()) """Enqueues {@code item} diff --git a/data_structures/queue/queue_on_pseudo_stack.py b/data_structures/queue/queue_on_pseudo_stack.py index 9a0c16f61..d98451000 100644 --- a/data_structures/queue/queue_on_pseudo_stack.py +++ b/data_structures/queue/queue_on_pseudo_stack.py @@ -37,7 +37,7 @@ class Queue: number of times to rotate queue""" def rotate(self, rotation: int) -> None: - for i in range(rotation): + for _ in range(rotation): temp = self.stack[0] self.stack = self.stack[1:] self.put(temp) diff --git a/data_structures/stacks/stack.py b/data_structures/stacks/stack.py index d1c73df43..55d424d50 100644 --- a/data_structures/stacks/stack.py +++ b/data_structures/stacks/stack.py @@ -92,13 +92,13 @@ def test_stack() -> None: try: _ = stack.pop() - assert False # This should not happen + raise AssertionError() # This should not happen except StackUnderflowError: assert True # This should happen try: _ = stack.peek() - assert False # This should not happen + raise AssertionError() # This should not happen except StackUnderflowError: assert True # This should happen @@ -118,7 +118,7 @@ def test_stack() -> None: try: stack.push(200) - assert False # This should not happen + raise AssertionError() # This should not happen except StackOverflowError: assert True # This should happen diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index 72da11639..39e78be04 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -458,16 +458,16 @@ def convex_hull_melkman(points: list[Point]) -> list[Point]: convex_hull[1] = points[i] i += 1 - for i in range(i, n): + for j in range(i, n): if ( - _det(convex_hull[0], convex_hull[-1], points[i]) > 0 + _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): # The point lies within the convex hull continue - convex_hull.insert(0, points[i]) - convex_hull.append(points[i]) + convex_hull.insert(0, points[j]) + convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: diff --git a/divide_and_conquer/strassen_matrix_multiplication.py b/divide_and_conquer/strassen_matrix_multiplication.py index 17efcfc7c..0ee426e4b 100644 --- a/divide_and_conquer/strassen_matrix_multiplication.py +++ b/divide_and_conquer/strassen_matrix_multiplication.py @@ -132,12 +132,12 @@ def strassen(matrix1: list, matrix2: list) -> list: # power of 2 for i in range(0, maxim): if i < dimension1[0]: - for j in range(dimension1[1], maxim): + for _ in range(dimension1[1], maxim): new_matrix1[i].append(0) else: new_matrix1.append([0] * maxim) if i < dimension2[0]: - for j in range(dimension2[1], maxim): + for _ in range(dimension2[1], maxim): new_matrix2[i].append(0) else: new_matrix2.append([0] * maxim) @@ -147,7 +147,7 @@ def strassen(matrix1: list, matrix2: list) -> list: # Removing the additional zeros for i in range(0, maxim): if i < dimension1[0]: - for j in range(dimension2[1], maxim): + for _ in range(dimension2[1], maxim): final_matrix[i].pop() else: final_matrix.pop() diff --git a/dynamic_programming/all_construct.py b/dynamic_programming/all_construct.py index 5ffed2caa..3839d01e6 100644 --- a/dynamic_programming/all_construct.py +++ b/dynamic_programming/all_construct.py @@ -21,7 +21,7 @@ def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[ table_size: int = len(target) + 1 table: list[list[list[str]]] = [] - for i in range(table_size): + for _ in range(table_size): table.append([]) # seed value table[0] = [[]] # because empty string has empty combination diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index 9efb60bab..093e15f49 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -30,13 +30,13 @@ def knapsack(w, wt, val, n): dp = [[0 for i in range(w + 1)] for j in range(n + 1)] for i in range(1, n + 1): - for w in range(1, w + 1): - if wt[i - 1] <= w: - dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]) + for w_ in range(1, w + 1): + if wt[i - 1] <= w_: + dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_]) else: - dp[i][w] = dp[i - 1][w] + dp[i][w_] = dp[i - 1][w_] - return dp[n][w], dp + return dp[n][w_], dp def knapsack_with_example_solution(w: int, wt: list, val: list): diff --git a/fractals/julia_sets.py b/fractals/julia_sets.py index f27394385..28c675c75 100644 --- a/fractals/julia_sets.py +++ b/fractals/julia_sets.py @@ -118,7 +118,7 @@ def iterate_function( """ z_n = z_0.astype("complex64") - for i in range(nb_iterations): + for _ in range(nb_iterations): z_n = eval_function(function_params, z_n) if infinity is not None: numpy.nan_to_num(z_n, copy=False, nan=infinity) diff --git a/fractals/koch_snowflake.py b/fractals/koch_snowflake.py index 07c1835b4..b0aaa86b1 100644 --- a/fractals/koch_snowflake.py +++ b/fractals/koch_snowflake.py @@ -46,7 +46,7 @@ def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndar 0.28867513]), array([0.66666667, 0. ]), array([1, 0])] """ vectors = initial_vectors - for i in range(steps): + for _ in range(steps): vectors = iteration_step(vectors) return vectors diff --git a/fractals/mandelbrot.py b/fractals/mandelbrot.py index 5d61b72e1..f97bcd170 100644 --- a/fractals/mandelbrot.py +++ b/fractals/mandelbrot.py @@ -36,7 +36,7 @@ def get_distance(x: float, y: float, max_step: int) -> float: """ a = x b = y - for step in range(max_step): + for step in range(max_step): # noqa: B007 a_new = a * a - b * b + x b = 2 * a * b + y a = a_new diff --git a/genetic_algorithm/basic_string.py b/genetic_algorithm/basic_string.py index 97dbe182b..bd7d80268 100644 --- a/genetic_algorithm/basic_string.py +++ b/genetic_algorithm/basic_string.py @@ -80,7 +80,7 @@ def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, score = len( [g for position, g in enumerate(item) if g == main_target[position]] ) - return (item, float(score)) + return (item, float(score)) # noqa: B023 # Adding a bit of concurrency can make everything faster, # @@ -129,7 +129,10 @@ def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, child_n = int(parent_1[1] * 100) + 1 child_n = 10 if child_n >= 10 else child_n for _ in range(child_n): - parent_2 = population_score[random.randint(0, N_SELECTED)][0] + parent_2 = population_score[ # noqa: B023 + random.randint(0, N_SELECTED) + ][0] + child_1, child_2 = crossover(parent_1[0], parent_2) # Append new string to the population list pop.append(mutate(child_1)) diff --git a/graphs/basic_graphs.py b/graphs/basic_graphs.py index b02e9af65..298a97bf0 100644 --- a/graphs/basic_graphs.py +++ b/graphs/basic_graphs.py @@ -188,7 +188,7 @@ def topo(g, ind=None, q=None): def adjm(): n = input().strip() a = [] - for i in range(n): + for _ in range(n): a.append(map(int, input().strip().split())) return a, n @@ -264,7 +264,7 @@ def prim(g, s): def edglist(): n, m = map(int, input().split(" ")) edges = [] - for i in range(m): + for _ in range(m): edges.append(map(int, input().split(" "))) return edges, n diff --git a/graphs/bellman_ford.py b/graphs/bellman_ford.py index 0f654a510..eb2cd25bf 100644 --- a/graphs/bellman_ford.py +++ b/graphs/bellman_ford.py @@ -36,7 +36,7 @@ def bellman_ford( distance = [float("inf")] * vertex_count distance[src] = 0.0 - for i in range(vertex_count - 1): + for _ in range(vertex_count - 1): for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) diff --git a/graphs/dijkstra_2.py b/graphs/dijkstra_2.py index 3170765bc..f548463ff 100644 --- a/graphs/dijkstra_2.py +++ b/graphs/dijkstra_2.py @@ -19,23 +19,23 @@ def min_dist(mdist, vset, v): def dijkstra(graph, v, src): - mdist = [float("inf") for i in range(v)] - vset = [False for i in range(v)] + mdist = [float("inf") for _ in range(v)] + vset = [False for _ in range(v)] mdist[src] = 0.0 - for i in range(v - 1): + for _ in range(v - 1): u = min_dist(mdist, vset, v) vset[u] = True - for v in range(v): + for i in range(v): if ( - (not vset[v]) - and graph[u][v] != float("inf") - and mdist[u] + graph[u][v] < mdist[v] + (not vset[i]) + and graph[u][i] != float("inf") + and mdist[u] + graph[u][i] < mdist[i] ): - mdist[v] = mdist[u] + graph[u][v] + mdist[i] = mdist[u] + graph[u][i] - print_dist(mdist, v) + print_dist(mdist, i) if __name__ == "__main__": diff --git a/graphs/frequent_pattern_graph_miner.py b/graphs/frequent_pattern_graph_miner.py index 50081afa6..a5ecbe6e8 100644 --- a/graphs/frequent_pattern_graph_miner.py +++ b/graphs/frequent_pattern_graph_miner.py @@ -79,7 +79,7 @@ def get_nodes(frequency_table): {'11111': ['ab', 'ac', 'df', 'bd', 'bc']} """ nodes = {} - for i, item in enumerate(frequency_table): + for _, item in enumerate(frequency_table): nodes.setdefault(item[2], []).append(item[0]) return nodes diff --git a/graphs/kahns_algorithm_long.py b/graphs/kahns_algorithm_long.py index 776ae3a2f..63cbeb909 100644 --- a/graphs/kahns_algorithm_long.py +++ b/graphs/kahns_algorithm_long.py @@ -4,7 +4,7 @@ def longest_distance(graph): queue = [] long_dist = [1] * len(graph) - for key, values in graph.items(): + for values in graph.values(): for i in values: indegree[i] += 1 diff --git a/graphs/kahns_algorithm_topo.py b/graphs/kahns_algorithm_topo.py index 6879b047f..b1260bd5b 100644 --- a/graphs/kahns_algorithm_topo.py +++ b/graphs/kahns_algorithm_topo.py @@ -8,7 +8,7 @@ def topological_sort(graph): topo = [] cnt = 0 - for key, values in graph.items(): + for values in graph.values(): for i in values: indegree[i] += 1 diff --git a/graphs/minimum_spanning_tree_prims.py b/graphs/minimum_spanning_tree_prims.py index 9b2c645f1..5b2eaa4bf 100644 --- a/graphs/minimum_spanning_tree_prims.py +++ b/graphs/minimum_spanning_tree_prims.py @@ -91,7 +91,7 @@ def prisms_algorithm(l): # noqa: E741 distance_tv[x[0]] = x[1] heapify(distance_tv, positions) - for i in range(1, len(l)): + for _ in range(1, len(l)): vertex = delete_minimum(distance_tv, positions) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex)) diff --git a/graphs/page_rank.py b/graphs/page_rank.py index 672405b73..e1af35b34 100644 --- a/graphs/page_rank.py +++ b/graphs/page_rank.py @@ -41,7 +41,7 @@ def page_rank(nodes, limit=3, d=0.85): for i in range(limit): print(f"======= Iteration {i + 1} =======") - for j, node in enumerate(nodes): + for _, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( ranks[ib] / outbounds[ib] for ib in node.inbound ) diff --git a/graphs/scc_kosaraju.py b/graphs/scc_kosaraju.py index ea9d35282..39211c64b 100644 --- a/graphs/scc_kosaraju.py +++ b/graphs/scc_kosaraju.py @@ -39,10 +39,10 @@ if __name__ == "__main__": # n - no of nodes, m - no of edges n, m = list(map(int, input().strip().split())) - graph: list[list[int]] = [[] for i in range(n)] # graph + graph: list[list[int]] = [[] for _ in range(n)] # graph reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph # input graph data (edges) - for i in range(m): + for _ in range(m): u, v = list(map(int, input().strip().split())) graph[u].append(v) reversed_graph[v].append(u) diff --git a/greedy_methods/optimal_merge_pattern.py b/greedy_methods/optimal_merge_pattern.py index 911e1966f..a1c934f84 100644 --- a/greedy_methods/optimal_merge_pattern.py +++ b/greedy_methods/optimal_merge_pattern.py @@ -41,7 +41,7 @@ def optimal_merge_pattern(files: list) -> float: while len(files) > 1: temp = 0 # Consider two files with minimum cost to be merged - for i in range(2): + for _ in range(2): min_index = files.index(min(files)) temp += files[min_index] files.pop(min_index) diff --git a/hashes/chaos_machine.py b/hashes/chaos_machine.py index 69313fbb2..238fdb1c0 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -53,7 +53,7 @@ def pull(): key = machine_time % m # Evolution (Time Length) - for i in range(0, t): + for _ in range(0, t): # Variables (Position + Parameters) r = params_space[key] value = buffer_space[key] diff --git a/hashes/enigma_machine.py b/hashes/enigma_machine.py index b0d45718e..0194f7da7 100644 --- a/hashes/enigma_machine.py +++ b/hashes/enigma_machine.py @@ -48,7 +48,7 @@ if __name__ == "__main__": break except Exception as error: print(error) - for i in range(token): + for _ in range(token): rotator() for j in decode: engine(j) diff --git a/machine_learning/self_organizing_map.py b/machine_learning/self_organizing_map.py index bd3d388f9..057c2a76b 100644 --- a/machine_learning/self_organizing_map.py +++ b/machine_learning/self_organizing_map.py @@ -47,7 +47,7 @@ def main() -> None: epochs = 3 alpha = 0.5 - for i in range(epochs): + for _ in range(epochs): for j in range(len(training_samples)): # training sample diff --git a/maths/area_under_curve.py b/maths/area_under_curve.py index d345398b4..b557b2029 100644 --- a/maths/area_under_curve.py +++ b/maths/area_under_curve.py @@ -35,7 +35,7 @@ def trapezoidal_area( x1 = x_start fx1 = fnc(x_start) area = 0.0 - for i in range(steps): + 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/line_length.py b/maths/line_length.py index ad12a816b..ea27ee904 100644 --- a/maths/line_length.py +++ b/maths/line_length.py @@ -40,7 +40,7 @@ def line_length( fx1 = fnc(x_start) length = 0.0 - for i in range(steps): + for _ in range(steps): # Approximates curve as a sequence of linear lines and sums their length x2 = (x_end - x_start) / steps + x1 diff --git a/maths/lucas_lehmer_primality_test.py b/maths/lucas_lehmer_primality_test.py index 916abfcc1..0a5621aac 100644 --- a/maths/lucas_lehmer_primality_test.py +++ b/maths/lucas_lehmer_primality_test.py @@ -31,7 +31,7 @@ def lucas_lehmer_test(p: int) -> bool: s = 4 m = (1 << p) - 1 - for i in range(p - 2): + for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0 diff --git a/maths/lucas_series.py b/maths/lucas_series.py index 6b32c2022..cae6c2815 100644 --- a/maths/lucas_series.py +++ b/maths/lucas_series.py @@ -50,7 +50,7 @@ def dynamic_lucas_number(n_th_number: int) -> int: if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 - for i in range(n_th_number): + for _ in range(n_th_number): a, b = b, a + b return a diff --git a/maths/miller_rabin.py b/maths/miller_rabin.py index b4dfed129..9f2668dba 100644 --- a/maths/miller_rabin.py +++ b/maths/miller_rabin.py @@ -33,7 +33,7 @@ def is_prime_big(n, prec=1000): b = bin_exp_mod(a, d, n) if b != 1: flag = True - for i in range(exp): + for _ in range(exp): if b == n - 1: flag = False break diff --git a/maths/monte_carlo_dice.py b/maths/monte_carlo_dice.py index 17cedbdbc..c4150b88f 100644 --- a/maths/monte_carlo_dice.py +++ b/maths/monte_carlo_dice.py @@ -35,7 +35,7 @@ def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]: """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) - for i in range(num_throws): + for _ in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear diff --git a/maths/numerical_integration.py b/maths/numerical_integration.py index a2bfce5b9..8f32fd356 100644 --- a/maths/numerical_integration.py +++ b/maths/numerical_integration.py @@ -39,7 +39,7 @@ def trapezoidal_area( fx1 = fnc(x_start) area = 0.0 - for i in range(steps): + for _ in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area diff --git a/maths/pi_monte_carlo_estimation.py b/maths/pi_monte_carlo_estimation.py index 81be08378..29b679907 100644 --- a/maths/pi_monte_carlo_estimation.py +++ b/maths/pi_monte_carlo_estimation.py @@ -47,7 +47,7 @@ def estimate_pi(number_of_simulations: int) -> float: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 - for simulation_index in range(number_of_simulations): + for _ in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): diff --git a/maths/pollard_rho.py b/maths/pollard_rho.py index 0fc80cd42..5082f54f7 100644 --- a/maths/pollard_rho.py +++ b/maths/pollard_rho.py @@ -73,7 +73,7 @@ def pollard_rho( """ return (pow(value, 2) + step) % modulus - for attempt in range(attempts): + for _ in range(attempts): # These track the position within the cycle detection logic. tortoise = seed hare = seed diff --git a/maths/primelib.py b/maths/primelib.py index 7d2a22f39..eb72a9f8a 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -406,14 +406,14 @@ def kg_v(number1, number2): count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) - for i in range(max(count1, count2)): + for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) - for i in range(count1): + for _ in range(count1): ans *= n done.append(n) @@ -425,7 +425,7 @@ def kg_v(number1, number2): count2 = prime_fac_2.count(n) - for i in range(count2): + for _ in range(count2): ans *= n done.append(n) @@ -637,7 +637,7 @@ def fib(n): fib1 = 1 ans = 1 # this will be return - for i in range(n - 1): + for _ in range(n - 1): tmp = ans ans += fib1 diff --git a/maths/proth_number.py b/maths/proth_number.py index e17503143..6b1519024 100644 --- a/maths/proth_number.py +++ b/maths/proth_number.py @@ -49,7 +49,7 @@ def proth(number: int) -> int: proth_index = 2 increment = 3 for block in range(1, block_index): - for move in range(increment): + for _ in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 diff --git a/maths/square_root.py b/maths/square_root.py index b324c7230..2cbf14bea 100644 --- a/maths/square_root.py +++ b/maths/square_root.py @@ -49,7 +49,7 @@ def square_root_iterative( value = get_initial_point(a) - for i in range(max_iter): + for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: diff --git a/maths/ugly_numbers.py b/maths/ugly_numbers.py index 4451a68cd..81bd928c6 100644 --- a/maths/ugly_numbers.py +++ b/maths/ugly_numbers.py @@ -32,7 +32,7 @@ def ugly_numbers(n: int) -> int: next_3 = ugly_nums[i3] * 3 next_5 = ugly_nums[i5] * 5 - for i in range(1, n): + for _ in range(1, n): next_num = min(next_2, next_3, next_5) ugly_nums.append(next_num) if next_num == next_2: diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index 305cad0a5..6495bd8fc 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -351,7 +351,7 @@ class Matrix: "Only invertable matrices can be raised to a negative power" ) result = self - for i in range(other - 1): + for _ in range(other - 1): result *= self return result diff --git a/matrix/nth_fibonacci_using_matrix_exponentiation.py b/matrix/nth_fibonacci_using_matrix_exponentiation.py index 7c964d884..65f10c90d 100644 --- a/matrix/nth_fibonacci_using_matrix_exponentiation.py +++ b/matrix/nth_fibonacci_using_matrix_exponentiation.py @@ -65,7 +65,7 @@ def nth_fibonacci_bruteforce(n: int) -> int: return n fib0 = 0 fib1 = 1 - for i in range(2, n + 1): + for _ in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 diff --git a/neural_network/back_propagation_neural_network.py b/neural_network/back_propagation_neural_network.py index 43e796e77..23b818b0f 100644 --- a/neural_network/back_propagation_neural_network.py +++ b/neural_network/back_propagation_neural_network.py @@ -128,7 +128,7 @@ class BPNN: self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) - for round_i in range(train_round): + for _ in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row, :]).T diff --git a/neural_network/perceptron.py b/neural_network/perceptron.py index a2bfdb326..f04c81424 100644 --- a/neural_network/perceptron.py +++ b/neural_network/perceptron.py @@ -69,7 +69,7 @@ class Perceptron: for sample in self.sample: sample.insert(0, self.bias) - for i in range(self.col_sample): + for _ in range(self.col_sample): self.weight.append(random.random()) self.weight.insert(0, self.bias) diff --git a/other/lfu_cache.py b/other/lfu_cache.py index 072d00ab5..2f26bb6cc 100644 --- a/other/lfu_cache.py +++ b/other/lfu_cache.py @@ -303,7 +303,7 @@ class LFUCache(Generic[T, U]): def cache_info() -> LFUCache[T, U]: return cls.decorator_function_to_instance_map[func] - setattr(cache_decorator_wrapper, "cache_info", cache_info) + setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010 return cache_decorator_wrapper diff --git a/other/lru_cache.py b/other/lru_cache.py index b68ae0a8e..aa910e487 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -321,7 +321,7 @@ class LRUCache(Generic[T, U]): def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] - setattr(cache_decorator_wrapper, "cache_info", cache_info) + setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010 return cache_decorator_wrapper diff --git a/other/magicdiamondpattern.py b/other/magicdiamondpattern.py index 71bc50b51..0fc41d7a2 100644 --- a/other/magicdiamondpattern.py +++ b/other/magicdiamondpattern.py @@ -8,9 +8,9 @@ def floyd(n): n : size of pattern """ for i in range(0, n): - for j in range(0, n - i - 1): # printing spaces + for _ in range(0, n - i - 1): # printing spaces print(" ", end="") - for k in range(0, i + 1): # printing stars + for _ in range(0, i + 1): # printing stars print("* ", end="") print() @@ -22,10 +22,10 @@ def reverse_floyd(n): n : size of pattern """ for i in range(n, 0, -1): - for j in range(i, 0, -1): # printing stars + for _ in range(i, 0, -1): # printing stars print("* ", end="") print() - for k in range(n - i + 1, 0, -1): # printing spaces + for _ in range(n - i + 1, 0, -1): # printing spaces print(" ", end="") diff --git a/other/scoring_algorithm.py b/other/scoring_algorithm.py index aecd19c55..1e6293f84 100644 --- a/other/scoring_algorithm.py +++ b/other/scoring_algorithm.py @@ -77,7 +77,7 @@ def procentual_proximity( final_scores: list[float] = [0 for i in range(len(score_lists[0]))] # generate final scores - for i, slist in enumerate(score_lists): + for slist in score_lists: for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele diff --git a/physics/lorentz_transformation_four_vector.py b/physics/lorentz_transformation_four_vector.py index bda852c25..f58b40e59 100644 --- a/physics/lorentz_transformation_four_vector.py +++ b/physics/lorentz_transformation_four_vector.py @@ -145,7 +145,7 @@ def transformation_matrix(velocity: float) -> np.array: def transform( - velocity: float, event: np.array = np.zeros(4), symbolic: bool = True + velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008 ) -> np.array: """ >>> transform(29979245,np.array([1,2,3,4]), False) diff --git a/physics/n_body_simulation.py b/physics/n_body_simulation.py index 7e9fc1642..2f8153782 100644 --- a/physics/n_body_simulation.py +++ b/physics/n_body_simulation.py @@ -310,7 +310,7 @@ def example_3() -> BodySystem: """ bodies = [] - for i in range(10): + for _ in range(10): velocity_x = random.uniform(-0.5, 0.5) velocity_y = random.uniform(-0.5, 0.5) diff --git a/project_euler/problem_011/sol2.py b/project_euler/problem_011/sol2.py index 839ca6717..9ea0db991 100644 --- a/project_euler/problem_011/sol2.py +++ b/project_euler/problem_011/sol2.py @@ -36,7 +36,7 @@ def solution(): """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 - for i in range(20): + for _ in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 diff --git a/project_euler/problem_025/sol3.py b/project_euler/problem_025/sol3.py index c66411dc5..0b9f3a0c8 100644 --- a/project_euler/problem_025/sol3.py +++ b/project_euler/problem_025/sol3.py @@ -45,7 +45,7 @@ def solution(n: int = 1000) -> int: f = f1 + f2 f1, f2 = f2, f index += 1 - for j in str(f): + for _ in str(f): i += 1 if i == n: break diff --git a/project_euler/problem_026/sol1.py b/project_euler/problem_026/sol1.py index 75d48df79..ccf2c111d 100644 --- a/project_euler/problem_026/sol1.py +++ b/project_euler/problem_026/sol1.py @@ -41,7 +41,7 @@ def solution(numerator: int = 1, digit: int = 1000) -> int: for divide_by_number in range(numerator, digit + 1): has_been_divided: list[int] = [] now_divide = numerator - for division_cycle in range(1, digit + 1): + for _ in range(1, digit + 1): if now_divide in has_been_divided: if longest_list_length < len(has_been_divided): longest_list_length = len(has_been_divided) diff --git a/project_euler/problem_188/sol1.py b/project_euler/problem_188/sol1.py index dd4360adb..88bd1327e 100644 --- a/project_euler/problem_188/sol1.py +++ b/project_euler/problem_188/sol1.py @@ -58,7 +58,7 @@ def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: # calculate base↑↑height by right-assiciative repeated modular # exponentiation result = base - for i in range(1, height): + for _ in range(1, height): result = _modexpt(base, result, 10**digits) return result diff --git a/project_euler/problem_203/sol1.py b/project_euler/problem_203/sol1.py index dc93683da..713b530b6 100644 --- a/project_euler/problem_203/sol1.py +++ b/project_euler/problem_203/sol1.py @@ -49,7 +49,7 @@ def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: """ coefficients = {1} previous_coefficients = [1] - for step in range(2, depth + 1): + for _ in range(2, depth + 1): coefficients_begins_one = previous_coefficients + [0] coefficients_ends_one = [0] + previous_coefficients previous_coefficients = [] diff --git a/scheduling/multi_level_feedback_queue.py b/scheduling/multi_level_feedback_queue.py index b54cc8719..a3ba1b340 100644 --- a/scheduling/multi_level_feedback_queue.py +++ b/scheduling/multi_level_feedback_queue.py @@ -205,7 +205,7 @@ class MLFQ: """ finished: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue - for i in range(len(ready_queue)): + for _ in range(len(ready_queue)): cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time diff --git a/sorts/double_sort.py b/sorts/double_sort.py index 4e08e27b3..5ca88a674 100644 --- a/sorts/double_sort.py +++ b/sorts/double_sort.py @@ -15,7 +15,7 @@ def double_sort(lst): True """ no_of_elements = len(lst) - for i in range( + for _ in range( 0, int(((no_of_elements - 1) / 2) + 1) ): # we don't need to traverse to end of list as for j in range(0, no_of_elements - 1): diff --git a/web_programming/open_google_results.py b/web_programming/open_google_results.py index 0e1dba8c5..2685bf621 100644 --- a/web_programming/open_google_results.py +++ b/web_programming/open_google_results.py @@ -1,10 +1,10 @@ import webbrowser from sys import argv -from urllib.parse import quote, parse_qs -from fake_useragent import UserAgent +from urllib.parse import parse_qs, quote import requests from bs4 import BeautifulSoup +from fake_useragent import UserAgent if __name__ == "__main__": if len(argv) > 1: @@ -18,9 +18,7 @@ if __name__ == "__main__": res = requests.get( url, - headers={ - "User-Agent": str(UserAgent().random) - }, + headers={"User-Agent": str(UserAgent().random)}, ) try: