Skip to content

Commit

Permalink
Add Flake8 comprehensions to pre-commit (TheAlgorithms#7235)
Browse files Browse the repository at this point in the history
* 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`
  • Loading branch information
CaedenPH authored Oct 15, 2022
1 parent 98a4c24 commit a652905
Show file tree
Hide file tree
Showing 20 changed files with 36 additions and 37 deletions.
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ repos:
additional_dependencies:
- flake8-bugbear
- flake8-builtins
- flake8-comprehensions
- pep8-naming

- repo: https://github.com/pre-commit/mirrors-mypy
Expand Down
2 changes: 1 addition & 1 deletion ciphers/onepad_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def decrypt(cipher: list[int], key: list[int]) -> str:
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__":
Expand Down
2 changes: 1 addition & 1 deletion ciphers/rail_fence_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion data_structures/hashing/hash_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def hash_function(self, key):
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):
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/merge_two_lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/fractional_knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion graphs/bellman_ford.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def bellman_ford(
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)
Expand Down
10 changes: 5 additions & 5 deletions graphs/frequent_pattern_graph_miner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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):
Expand Down
8 changes: 4 additions & 4 deletions hashes/enigma_machine.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down
2 changes: 1 addition & 1 deletion maths/primelib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 2 additions & 2 deletions matrix/spiral_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

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
Expand Down Expand Up @@ -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])
Expand Down
4 changes: 2 additions & 2 deletions other/davisb_putnamb_logemannb_loveland.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions project_euler/problem_042/solution42.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 6 additions & 6 deletions project_euler/problem_052/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_062/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
4 changes: 2 additions & 2 deletions project_euler/problem_067/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])):
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_109/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_551/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""


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]]]] = {}

Expand Down
2 changes: 1 addition & 1 deletion sorts/radix_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions strings/aho_corasick.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ def search_in(self, string: str) -> dict[str, list[int]]:
>>> 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 (
Expand Down

0 comments on commit a652905

Please sign in to comment.