From a652905b605ddcc43626072366d1130315801dc9 Mon Sep 17 00:00:00 2001 From: Caeden Date: Sat, 15 Oct 2022 18:29:42 +0100 Subject: [PATCH] Add Flake8 comprehensions to pre-commit (#7235) * ci(pre-commit): Add ``flake8-comprehensions`` to ``pre-commit`` (#7233) * refactor: Fix ``flake8-comprehensions`` errors * fix: Replace `map` with generator (#7233) * fix: Cast `range` objects to `list` --- .pre-commit-config.yaml | 1 + ciphers/onepad_cipher.py | 2 +- ciphers/rail_fence_cipher.py | 2 +- data_structures/hashing/hash_table.py | 2 +- data_structures/linked_list/merge_two_lists.py | 2 +- dynamic_programming/fractional_knapsack.py | 2 +- graphs/bellman_ford.py | 2 +- graphs/frequent_pattern_graph_miner.py | 10 +++++----- hashes/enigma_machine.py | 8 ++++---- maths/primelib.py | 2 +- matrix/spiral_print.py | 4 ++-- other/davisb_putnamb_logemannb_loveland.py | 4 ++-- project_euler/problem_042/solution42.py | 4 ++-- project_euler/problem_052/sol1.py | 12 ++++++------ project_euler/problem_062/sol1.py | 2 +- project_euler/problem_067/sol1.py | 4 ++-- project_euler/problem_109/sol1.py | 2 +- project_euler/problem_551/sol1.py | 2 +- sorts/radix_sort.py | 2 +- strings/aho_corasick.py | 4 +--- 20 files changed, 36 insertions(+), 37 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d3ea9722f..345513565 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -39,6 +39,7 @@ repos: additional_dependencies: - flake8-bugbear - flake8-builtins + - flake8-comprehensions - pep8-naming - repo: https://github.com/pre-commit/mirrors-mypy diff --git a/ciphers/onepad_cipher.py b/ciphers/onepad_cipher.py index 3ace9b098..4bfe35b71 100644 --- a/ciphers/onepad_cipher.py +++ b/ciphers/onepad_cipher.py @@ -22,7 +22,7 @@ class Onepad: for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) - return "".join([i for i in plain]) + return "".join(plain) if __name__ == "__main__": diff --git a/ciphers/rail_fence_cipher.py b/ciphers/rail_fence_cipher.py index cba593ca7..47ee7db89 100644 --- a/ciphers/rail_fence_cipher.py +++ b/ciphers/rail_fence_cipher.py @@ -72,7 +72,7 @@ def decrypt(input_string: str, key: int) -> str: counter = 0 for row in temp_grid: # fills in the characters splice = input_string[counter : counter + len(row)] - grid.append([character for character in splice]) + grid.append(list(splice)) counter += len(row) output_string = "" # reads as zigzag diff --git a/data_structures/hashing/hash_table.py b/data_structures/hashing/hash_table.py index 1cd71cc4b..607454c82 100644 --- a/data_structures/hashing/hash_table.py +++ b/data_structures/hashing/hash_table.py @@ -34,7 +34,7 @@ class HashTable: def _step_by_step(self, step_ord): print(f"step {step_ord}") - print([i for i in range(len(self.values))]) + print(list(range(len(self.values)))) print(self.values) def bulk_insert(self, values): diff --git a/data_structures/linked_list/merge_two_lists.py b/data_structures/linked_list/merge_two_lists.py index 43dd46186..93cf7a7e1 100644 --- a/data_structures/linked_list/merge_two_lists.py +++ b/data_structures/linked_list/merge_two_lists.py @@ -19,7 +19,7 @@ class Node: class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None - for i in reversed(sorted(ints)): + for i in sorted(ints, reverse=True): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: diff --git a/dynamic_programming/fractional_knapsack.py b/dynamic_programming/fractional_knapsack.py index 6f7a2a08c..58976d40c 100644 --- a/dynamic_programming/fractional_knapsack.py +++ b/dynamic_programming/fractional_knapsack.py @@ -8,7 +8,7 @@ def frac_knapsack(vl, wt, w, n): 240.0 """ - r = list(sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True)) + r = sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True) vl, wt = [i[0] for i in r], [i[1] for i in r] acc = list(accumulate(wt)) k = bisect(acc, w) diff --git a/graphs/bellman_ford.py b/graphs/bellman_ford.py index eb2cd25bf..9ac8bae85 100644 --- a/graphs/bellman_ford.py +++ b/graphs/bellman_ford.py @@ -58,7 +58,7 @@ if __name__ == "__main__": V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) - graph: list[dict[str, int]] = [dict() for j in range(E)] + graph: list[dict[str, int]] = [{} for _ in range(E)] for i in range(E): print("Edge ", i + 1) diff --git a/graphs/frequent_pattern_graph_miner.py b/graphs/frequent_pattern_graph_miner.py index 1d26702a4..87d5605a0 100644 --- a/graphs/frequent_pattern_graph_miner.py +++ b/graphs/frequent_pattern_graph_miner.py @@ -155,12 +155,12 @@ def construct_graph(cluster, nodes): cluster[max(cluster.keys()) + 1] = "Header" graph = {} for i in x: - if tuple(["Header"]) in graph: - graph[tuple(["Header"])].append(x[i]) + if (["Header"],) in graph: + graph[(["Header"],)].append(x[i]) else: - graph[tuple(["Header"])] = [x[i]] + graph[(["Header"],)] = [x[i]] for i in x: - graph[tuple(x[i])] = [["Header"]] + graph[(x[i],)] = [["Header"]] i = 1 while i < max(cluster) - 1: create_edge(nodes, graph, cluster, i) @@ -186,7 +186,7 @@ def find_freq_subgraph_given_support(s, cluster, graph): """ k = int(s / 100 * (len(cluster) - 1)) for i in cluster[k].keys(): - my_dfs(graph, tuple(cluster[k][i]), tuple(["Header"])) + my_dfs(graph, tuple(cluster[k][i]), (["Header"],)) def freq_subgraphs_edge_list(paths): diff --git a/hashes/enigma_machine.py b/hashes/enigma_machine.py index 0194f7da7..d95437d12 100644 --- a/hashes/enigma_machine.py +++ b/hashes/enigma_machine.py @@ -1,8 +1,8 @@ alphabets = [chr(i) for i in range(32, 126)] -gear_one = [i for i in range(len(alphabets))] -gear_two = [i for i in range(len(alphabets))] -gear_three = [i for i in range(len(alphabets))] -reflector = [i for i in reversed(range(len(alphabets)))] +gear_one = list(range(len(alphabets))) +gear_two = list(range(len(alphabets))) +gear_three = list(range(len(alphabets))) +reflector = list(reversed(range(len(alphabets)))) code = [] gear_one_pos = gear_two_pos = gear_three_pos = 0 diff --git a/maths/primelib.py b/maths/primelib.py index eb72a9f8a..9586227ea 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -89,7 +89,7 @@ def sieve_er(n): assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N - begin_list = [x for x in range(2, n + 1)] + begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. diff --git a/matrix/spiral_print.py b/matrix/spiral_print.py index 2441f05d1..0cf732d60 100644 --- a/matrix/spiral_print.py +++ b/matrix/spiral_print.py @@ -9,7 +9,7 @@ This problem has been solved through recursive way. def check_matrix(matrix: list[list[int]]) -> bool: # must be - matrix = list(list(row) for row in matrix) + matrix = [list(row) for row in matrix] if matrix and isinstance(matrix, list): if isinstance(matrix[0], list): prev_len = 0 @@ -44,7 +44,7 @@ def spiral_print_clockwise(a: list[list[int]]) -> None: 7 """ if check_matrix(a) and len(a) > 0: - a = list(list(row) for row in a) + a = [list(row) for row in a] mat_row = len(a) if isinstance(a[0], list): mat_col = len(a[0]) diff --git a/other/davisb_putnamb_logemannb_loveland.py b/other/davisb_putnamb_logemannb_loveland.py index 3110515d5..a1bea5b39 100644 --- a/other/davisb_putnamb_logemannb_loveland.py +++ b/other/davisb_putnamb_logemannb_loveland.py @@ -317,7 +317,7 @@ def dpll_algorithm( if p: tmp_model = model tmp_model[p] = value - tmp_symbols = [i for i in symbols] + tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) @@ -329,7 +329,7 @@ def dpll_algorithm( if p: tmp_model = model tmp_model[p] = value - tmp_symbols = [i for i in symbols] + tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) diff --git a/project_euler/problem_042/solution42.py b/project_euler/problem_042/solution42.py index 6d22a8dfb..c0fb2ad50 100644 --- a/project_euler/problem_042/solution42.py +++ b/project_euler/problem_042/solution42.py @@ -33,11 +33,11 @@ def solution(): with open(words_file_path) as f: words = f.readline() - words = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(","))) + words = [word.strip('"') for word in words.strip("\r\n").split(",")] words = list( filter( lambda word: word in TRIANGULAR_NUMBERS, - map(lambda word: sum(map(lambda x: ord(x) - 64, word)), words), + (sum(ord(x) - 64 for x in word) for word in words), ) ) return len(words) diff --git a/project_euler/problem_052/sol1.py b/project_euler/problem_052/sol1.py index df5c46ae0..21acfb633 100644 --- a/project_euler/problem_052/sol1.py +++ b/project_euler/problem_052/sol1.py @@ -21,12 +21,12 @@ def solution(): while True: if ( - sorted(list(str(i))) - == sorted(list(str(2 * i))) - == sorted(list(str(3 * i))) - == sorted(list(str(4 * i))) - == sorted(list(str(5 * i))) - == sorted(list(str(6 * i))) + sorted(str(i)) + == sorted(str(2 * i)) + == sorted(str(3 * i)) + == sorted(str(4 * i)) + == sorted(str(5 * i)) + == sorted(str(6 * i)) ): return i diff --git a/project_euler/problem_062/sol1.py b/project_euler/problem_062/sol1.py index 0c9baf880..3efdb3513 100644 --- a/project_euler/problem_062/sol1.py +++ b/project_euler/problem_062/sol1.py @@ -55,7 +55,7 @@ def get_digits(num: int) -> str: >>> get_digits(123) '0166788' """ - return "".join(sorted(list(str(num**3)))) + return "".join(sorted(str(num**3))) if __name__ == "__main__": diff --git a/project_euler/problem_067/sol1.py b/project_euler/problem_067/sol1.py index 527d4dc59..ab305684d 100644 --- a/project_euler/problem_067/sol1.py +++ b/project_euler/problem_067/sol1.py @@ -28,8 +28,8 @@ def solution(): with open(triangle) as f: triangle = f.readlines() - a = map(lambda x: x.rstrip("\r\n").split(" "), triangle) - a = list(map(lambda x: list(map(int, x)), a)) + a = (x.rstrip("\r\n").split(" ") for x in triangle) + a = [list(map(int, x)) for x in a] for i in range(1, len(a)): for j in range(len(a[i])): diff --git a/project_euler/problem_109/sol1.py b/project_euler/problem_109/sol1.py index 91c71eb9f..852f001d3 100644 --- a/project_euler/problem_109/sol1.py +++ b/project_euler/problem_109/sol1.py @@ -65,7 +65,7 @@ def solution(limit: int = 100) -> int: >>> solution(50) 12577 """ - singles: list[int] = [x for x in range(1, 21)] + [25] + singles: list[int] = list(range(1, 21)) + [25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] diff --git a/project_euler/problem_551/sol1.py b/project_euler/problem_551/sol1.py index c15445e4d..2cd75efbb 100644 --- a/project_euler/problem_551/sol1.py +++ b/project_euler/problem_551/sol1.py @@ -13,7 +13,7 @@ Find a(10^15) """ -ks = [k for k in range(2, 20 + 1)] +ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} diff --git a/sorts/radix_sort.py b/sorts/radix_sort.py index afe62bc7e..a496cdc0c 100644 --- a/sorts/radix_sort.py +++ b/sorts/radix_sort.py @@ -24,7 +24,7 @@ def radix_sort(list_of_ints: list[int]) -> list[int]: max_digit = max(list_of_ints) while placement <= max_digit: # declare and initialize empty buckets - buckets: list[list] = [list() for _ in range(RADIX)] + buckets: list[list] = [[] for _ in range(RADIX)] # split list_of_ints between the buckets for i in list_of_ints: tmp = int((i / placement) % RADIX) diff --git a/strings/aho_corasick.py b/strings/aho_corasick.py index 2d2f562df..25ed649ce 100644 --- a/strings/aho_corasick.py +++ b/strings/aho_corasick.py @@ -70,9 +70,7 @@ class Automaton: >>> A.search_in("whatever, err ... , wherever") {'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]} """ - result: dict = ( - dict() - ) # returns a dict with keywords and list of its occurrences + result: dict = {} # returns a dict with keywords and list of its occurrences current_state = 0 for i in range(len(string)): while (