Skip to content

Commit a652905

Browse files
authored
Add Flake8 comprehensions to pre-commit (TheAlgorithms#7235)
* ci(pre-commit): Add ``flake8-comprehensions`` to ``pre-commit`` (TheAlgorithms#7233) * refactor: Fix ``flake8-comprehensions`` errors * fix: Replace `map` with generator (TheAlgorithms#7233) * fix: Cast `range` objects to `list`
1 parent 98a4c24 commit a652905

File tree

20 files changed

+36
-37
lines changed

20 files changed

+36
-37
lines changed

.pre-commit-config.yaml

+1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ repos:
3939
additional_dependencies:
4040
- flake8-bugbear
4141
- flake8-builtins
42+
- flake8-comprehensions
4243
- pep8-naming
4344

4445
- repo: https://github.com/pre-commit/mirrors-mypy

ciphers/onepad_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def decrypt(cipher: list[int], key: list[int]) -> str:
2222
for i in range(len(key)):
2323
p = int((cipher[i] - (key[i]) ** 2) / key[i])
2424
plain.append(chr(p))
25-
return "".join([i for i in plain])
25+
return "".join(plain)
2626

2727

2828
if __name__ == "__main__":

ciphers/rail_fence_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def decrypt(input_string: str, key: int) -> str:
7272
counter = 0
7373
for row in temp_grid: # fills in the characters
7474
splice = input_string[counter : counter + len(row)]
75-
grid.append([character for character in splice])
75+
grid.append(list(splice))
7676
counter += len(row)
7777

7878
output_string = "" # reads as zigzag

data_structures/hashing/hash_table.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def hash_function(self, key):
3434
def _step_by_step(self, step_ord):
3535

3636
print(f"step {step_ord}")
37-
print([i for i in range(len(self.values))])
37+
print(list(range(len(self.values))))
3838
print(self.values)
3939

4040
def bulk_insert(self, values):

data_structures/linked_list/merge_two_lists.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class Node:
1919
class SortedLinkedList:
2020
def __init__(self, ints: Iterable[int]) -> None:
2121
self.head: Node | None = None
22-
for i in reversed(sorted(ints)):
22+
for i in sorted(ints, reverse=True):
2323
self.head = Node(i, self.head)
2424

2525
def __iter__(self) -> Iterator[int]:

dynamic_programming/fractional_knapsack.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def frac_knapsack(vl, wt, w, n):
88
240.0
99
"""
1010

11-
r = list(sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True))
11+
r = sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True)
1212
vl, wt = [i[0] for i in r], [i[1] for i in r]
1313
acc = list(accumulate(wt))
1414
k = bisect(acc, w)

graphs/bellman_ford.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def bellman_ford(
5858
V = int(input("Enter number of vertices: ").strip())
5959
E = int(input("Enter number of edges: ").strip())
6060

61-
graph: list[dict[str, int]] = [dict() for j in range(E)]
61+
graph: list[dict[str, int]] = [{} for _ in range(E)]
6262

6363
for i in range(E):
6464
print("Edge ", i + 1)

graphs/frequent_pattern_graph_miner.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -155,12 +155,12 @@ def construct_graph(cluster, nodes):
155155
cluster[max(cluster.keys()) + 1] = "Header"
156156
graph = {}
157157
for i in x:
158-
if tuple(["Header"]) in graph:
159-
graph[tuple(["Header"])].append(x[i])
158+
if (["Header"],) in graph:
159+
graph[(["Header"],)].append(x[i])
160160
else:
161-
graph[tuple(["Header"])] = [x[i]]
161+
graph[(["Header"],)] = [x[i]]
162162
for i in x:
163-
graph[tuple(x[i])] = [["Header"]]
163+
graph[(x[i],)] = [["Header"]]
164164
i = 1
165165
while i < max(cluster) - 1:
166166
create_edge(nodes, graph, cluster, i)
@@ -186,7 +186,7 @@ def find_freq_subgraph_given_support(s, cluster, graph):
186186
"""
187187
k = int(s / 100 * (len(cluster) - 1))
188188
for i in cluster[k].keys():
189-
my_dfs(graph, tuple(cluster[k][i]), tuple(["Header"]))
189+
my_dfs(graph, tuple(cluster[k][i]), (["Header"],))
190190

191191

192192
def freq_subgraphs_edge_list(paths):

hashes/enigma_machine.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
alphabets = [chr(i) for i in range(32, 126)]
2-
gear_one = [i for i in range(len(alphabets))]
3-
gear_two = [i for i in range(len(alphabets))]
4-
gear_three = [i for i in range(len(alphabets))]
5-
reflector = [i for i in reversed(range(len(alphabets)))]
2+
gear_one = list(range(len(alphabets)))
3+
gear_two = list(range(len(alphabets)))
4+
gear_three = list(range(len(alphabets)))
5+
reflector = list(reversed(range(len(alphabets))))
66
code = []
77
gear_one_pos = gear_two_pos = gear_three_pos = 0
88

maths/primelib.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def sieve_er(n):
8989
assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
9090

9191
# beginList: contains all natural numbers from 2 up to N
92-
begin_list = [x for x in range(2, n + 1)]
92+
begin_list = list(range(2, n + 1))
9393

9494
ans = [] # this list will be returns.
9595

matrix/spiral_print.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
def check_matrix(matrix: list[list[int]]) -> bool:
1111
# must be
12-
matrix = list(list(row) for row in matrix)
12+
matrix = [list(row) for row in matrix]
1313
if matrix and isinstance(matrix, list):
1414
if isinstance(matrix[0], list):
1515
prev_len = 0
@@ -44,7 +44,7 @@ def spiral_print_clockwise(a: list[list[int]]) -> None:
4444
7
4545
"""
4646
if check_matrix(a) and len(a) > 0:
47-
a = list(list(row) for row in a)
47+
a = [list(row) for row in a]
4848
mat_row = len(a)
4949
if isinstance(a[0], list):
5050
mat_col = len(a[0])

other/davisb_putnamb_logemannb_loveland.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ def dpll_algorithm(
317317
if p:
318318
tmp_model = model
319319
tmp_model[p] = value
320-
tmp_symbols = [i for i in symbols]
320+
tmp_symbols = list(symbols)
321321
if p in tmp_symbols:
322322
tmp_symbols.remove(p)
323323
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
@@ -329,7 +329,7 @@ def dpll_algorithm(
329329
if p:
330330
tmp_model = model
331331
tmp_model[p] = value
332-
tmp_symbols = [i for i in symbols]
332+
tmp_symbols = list(symbols)
333333
if p in tmp_symbols:
334334
tmp_symbols.remove(p)
335335
return dpll_algorithm(clauses, tmp_symbols, tmp_model)

project_euler/problem_042/solution42.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ def solution():
3333
with open(words_file_path) as f:
3434
words = f.readline()
3535

36-
words = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(",")))
36+
words = [word.strip('"') for word in words.strip("\r\n").split(",")]
3737
words = list(
3838
filter(
3939
lambda word: word in TRIANGULAR_NUMBERS,
40-
map(lambda word: sum(map(lambda x: ord(x) - 64, word)), words),
40+
(sum(ord(x) - 64 for x in word) for word in words),
4141
)
4242
)
4343
return len(words)

project_euler/problem_052/sol1.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@ def solution():
2121

2222
while True:
2323
if (
24-
sorted(list(str(i)))
25-
== sorted(list(str(2 * i)))
26-
== sorted(list(str(3 * i)))
27-
== sorted(list(str(4 * i)))
28-
== sorted(list(str(5 * i)))
29-
== sorted(list(str(6 * i)))
24+
sorted(str(i))
25+
== sorted(str(2 * i))
26+
== sorted(str(3 * i))
27+
== sorted(str(4 * i))
28+
== sorted(str(5 * i))
29+
== sorted(str(6 * i))
3030
):
3131
return i
3232

project_euler/problem_062/sol1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def get_digits(num: int) -> str:
5555
>>> get_digits(123)
5656
'0166788'
5757
"""
58-
return "".join(sorted(list(str(num**3))))
58+
return "".join(sorted(str(num**3)))
5959

6060

6161
if __name__ == "__main__":

project_euler/problem_067/sol1.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ def solution():
2828
with open(triangle) as f:
2929
triangle = f.readlines()
3030

31-
a = map(lambda x: x.rstrip("\r\n").split(" "), triangle)
32-
a = list(map(lambda x: list(map(int, x)), a))
31+
a = (x.rstrip("\r\n").split(" ") for x in triangle)
32+
a = [list(map(int, x)) for x in a]
3333

3434
for i in range(1, len(a)):
3535
for j in range(len(a[i])):

project_euler/problem_109/sol1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def solution(limit: int = 100) -> int:
6565
>>> solution(50)
6666
12577
6767
"""
68-
singles: list[int] = [x for x in range(1, 21)] + [25]
68+
singles: list[int] = list(range(1, 21)) + [25]
6969
doubles: list[int] = [2 * x for x in range(1, 21)] + [50]
7070
triples: list[int] = [3 * x for x in range(1, 21)]
7171
all_values: list[int] = singles + doubles + triples + [0]

project_euler/problem_551/sol1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
"""
1414

1515

16-
ks = [k for k in range(2, 20 + 1)]
16+
ks = range(2, 20 + 1)
1717
base = [10**k for k in range(ks[-1] + 1)]
1818
memo: dict[int, dict[int, list[list[int]]]] = {}
1919

sorts/radix_sort.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def radix_sort(list_of_ints: list[int]) -> list[int]:
2424
max_digit = max(list_of_ints)
2525
while placement <= max_digit:
2626
# declare and initialize empty buckets
27-
buckets: list[list] = [list() for _ in range(RADIX)]
27+
buckets: list[list] = [[] for _ in range(RADIX)]
2828
# split list_of_ints between the buckets
2929
for i in list_of_ints:
3030
tmp = int((i / placement) % RADIX)

strings/aho_corasick.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,7 @@ def search_in(self, string: str) -> dict[str, list[int]]:
7070
>>> A.search_in("whatever, err ... , wherever")
7171
{'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]}
7272
"""
73-
result: dict = (
74-
dict()
75-
) # returns a dict with keywords and list of its occurrences
73+
result: dict = {} # returns a dict with keywords and list of its occurrences
7674
current_state = 0
7775
for i in range(len(string)):
7876
while (

0 commit comments

Comments
 (0)