Skip to content

Commit fc33c50

Browse files
[pre-commit.ci] pre-commit autoupdate (TheAlgorithms#12398)
updates: - [github.com/astral-sh/ruff-pre-commit: v0.4.10 → v0.5.0](astral-sh/ruff-pre-commit@v0.4.10...v0.5.0) - [github.com/pre-commit/mirrors-mypy: v1.10.0 → v1.10.1](pre-commit/mirrors-mypy@v1.10.0...v1.10.1) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent f3f32ae commit fc33c50

30 files changed

+66
-78
lines changed

.pre-commit-config.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ repos:
1616
- id: auto-walrus
1717

1818
- repo: https://github.com/astral-sh/ruff-pre-commit
19-
rev: v0.7.4
19+
rev: v0.8.0
2020
hooks:
2121
- id: ruff
2222
- id: ruff-format

cellular_automata/conways_game_of_life.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,8 @@ def new_generation(cells: list[list[int]]) -> list[list[int]]:
5858
# 3. All other live cells die in the next generation.
5959
# Similarly, all other dead cells stay dead.
6060
alive = cells[i][j] == 1
61-
if (
62-
(alive and 2 <= neighbour_count <= 3)
63-
or not alive
64-
and neighbour_count == 3
61+
if (alive and 2 <= neighbour_count <= 3) or (
62+
not alive and neighbour_count == 3
6563
):
6664
next_generation_row.append(1)
6765
else:

ciphers/playfair_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from collections.abc import Generator, Iterable
2525

2626

27-
def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...], None, None]:
27+
def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...]]:
2828
it = iter(seq)
2929
while True:
3030
chunk = tuple(itertools.islice(it, size))

ciphers/simple_keyword_cypher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def remove_duplicates(key: str) -> str:
1010

1111
key_no_dups = ""
1212
for ch in key:
13-
if ch == " " or ch not in key_no_dups and ch.isalpha():
13+
if ch == " " or (ch not in key_no_dups and ch.isalpha()):
1414
key_no_dups += ch
1515
return key_no_dups
1616

ciphers/transposition_cipher.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,8 @@ def decrypt_message(key: int, message: str) -> str:
5252
plain_text[col] += symbol
5353
col += 1
5454

55-
if (
56-
(col == num_cols)
57-
or (col == num_cols - 1)
58-
and (row >= num_rows - num_shaded_boxes)
55+
if (col == num_cols) or (
56+
(col == num_cols - 1) and (row >= num_rows - num_shaded_boxes)
5957
):
6058
col = 0
6159
row += 1

compression/lempel_ziv.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ def add_key_to_lexicon(
3535
lexicon[curr_string + "0"] = last_match_id
3636

3737
if math.log2(index).is_integer():
38-
for curr_key in lexicon:
39-
lexicon[curr_key] = "0" + lexicon[curr_key]
38+
for curr_key, value in lexicon.items():
39+
lexicon[curr_key] = f"0{value}"
4040

4141
lexicon[curr_string + "1"] = bin(index)[2:]
4242

data_structures/arrays/sudoku_solver.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def time_solve(grid):
156156
times, results = zip(*[time_solve(grid) for grid in grids])
157157
if (n := len(grids)) > 1:
158158
print(
159-
"Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)."
159+
"Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)." # noqa: UP031
160160
% (sum(results), n, name, sum(times) / n, n / sum(times), max(times))
161161
)
162162

data_structures/binary_tree/binary_tree_traversals.py

+10-14
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def make_tree() -> Node | None:
3030
return tree
3131

3232

33-
def preorder(root: Node | None) -> Generator[int, None, None]:
33+
def preorder(root: Node | None) -> Generator[int]:
3434
"""
3535
Pre-order traversal visits root node, left subtree, right subtree.
3636
>>> list(preorder(make_tree()))
@@ -43,7 +43,7 @@ def preorder(root: Node | None) -> Generator[int, None, None]:
4343
yield from preorder(root.right)
4444

4545

46-
def postorder(root: Node | None) -> Generator[int, None, None]:
46+
def postorder(root: Node | None) -> Generator[int]:
4747
"""
4848
Post-order traversal visits left subtree, right subtree, root node.
4949
>>> list(postorder(make_tree()))
@@ -56,7 +56,7 @@ def postorder(root: Node | None) -> Generator[int, None, None]:
5656
yield root.data
5757

5858

59-
def inorder(root: Node | None) -> Generator[int, None, None]:
59+
def inorder(root: Node | None) -> Generator[int]:
6060
"""
6161
In-order traversal visits left subtree, root node, right subtree.
6262
>>> list(inorder(make_tree()))
@@ -69,7 +69,7 @@ def inorder(root: Node | None) -> Generator[int, None, None]:
6969
yield from inorder(root.right)
7070

7171

72-
def reverse_inorder(root: Node | None) -> Generator[int, None, None]:
72+
def reverse_inorder(root: Node | None) -> Generator[int]:
7373
"""
7474
Reverse in-order traversal visits right subtree, root node, left subtree.
7575
>>> list(reverse_inorder(make_tree()))
@@ -93,7 +93,7 @@ def height(root: Node | None) -> int:
9393
return (max(height(root.left), height(root.right)) + 1) if root else 0
9494

9595

96-
def level_order(root: Node | None) -> Generator[int, None, None]:
96+
def level_order(root: Node | None) -> Generator[int]:
9797
"""
9898
Returns a list of nodes value from a whole binary tree in Level Order Traverse.
9999
Level Order traverse: Visit nodes of the tree level-by-level.
@@ -116,9 +116,7 @@ def level_order(root: Node | None) -> Generator[int, None, None]:
116116
process_queue.append(node.right)
117117

118118

119-
def get_nodes_from_left_to_right(
120-
root: Node | None, level: int
121-
) -> Generator[int, None, None]:
119+
def get_nodes_from_left_to_right(root: Node | None, level: int) -> Generator[int]:
122120
"""
123121
Returns a list of nodes value from a particular level:
124122
Left to right direction of the binary tree.
@@ -128,7 +126,7 @@ def get_nodes_from_left_to_right(
128126
[2, 3]
129127
"""
130128

131-
def populate_output(root: Node | None, level: int) -> Generator[int, None, None]:
129+
def populate_output(root: Node | None, level: int) -> Generator[int]:
132130
if not root:
133131
return
134132
if level == 1:
@@ -140,9 +138,7 @@ def populate_output(root: Node | None, level: int) -> Generator[int, None, None]
140138
yield from populate_output(root, level)
141139

142140

143-
def get_nodes_from_right_to_left(
144-
root: Node | None, level: int
145-
) -> Generator[int, None, None]:
141+
def get_nodes_from_right_to_left(root: Node | None, level: int) -> Generator[int]:
146142
"""
147143
Returns a list of nodes value from a particular level:
148144
Right to left direction of the binary tree.
@@ -152,7 +148,7 @@ def get_nodes_from_right_to_left(
152148
[3, 2]
153149
"""
154150

155-
def populate_output(root: Node | None, level: int) -> Generator[int, None, None]:
151+
def populate_output(root: Node | None, level: int) -> Generator[int]:
156152
if not root:
157153
return
158154
if level == 1:
@@ -164,7 +160,7 @@ def populate_output(root: Node | None, level: int) -> Generator[int, None, None]
164160
yield from populate_output(root, level)
165161

166162

167-
def zigzag(root: Node | None) -> Generator[int, None, None]:
163+
def zigzag(root: Node | None) -> Generator[int]:
168164
"""
169165
ZigZag traverse:
170166
Returns a list of nodes value from left to right and right to left, alternatively.

data_structures/linked_list/deque_doubly.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class _DoublyLinkedBase:
1212
"""A Private class (to be inherited)"""
1313

1414
class _Node:
15-
__slots__ = "_prev", "_data", "_next"
15+
__slots__ = "_data", "_next", "_prev"
1616

1717
def __init__(self, link_p, element, link_n):
1818
self._prev = link_p

data_structures/queue/double_ended_queue.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class Deque:
3333
the number of nodes
3434
"""
3535

36-
__slots__ = ("_front", "_back", "_len")
36+
__slots__ = ("_back", "_front", "_len")
3737

3838
@dataclass
3939
class _Node:

docs/source/__init__.py

Whitespace-only changes.

electronics/electrical_impedance.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from __future__ import annotations
88

9-
from math import pow, sqrt
9+
from math import pow, sqrt # noqa: A004
1010

1111

1212
def electrical_impedance(

graphs/ant_colony_optimization_algorithms.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -194,10 +194,8 @@ def city_select(
194194
IndexError: list index out of range
195195
"""
196196
probabilities = []
197-
for city in unvisited_cities:
198-
city_distance = distance(
199-
unvisited_cities[city], next(iter(current_city.values()))
200-
)
197+
for city, value in unvisited_cities.items():
198+
city_distance = distance(value, next(iter(current_city.values())))
201199
probability = (pheromone[city][next(iter(current_city.keys()))] ** alpha) * (
202200
(1 / city_distance) ** beta
203201
)

graphs/basic_graphs.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -133,18 +133,18 @@ def dijk(g, s):
133133
if len(known) == len(g) - 1:
134134
break
135135
mini = 100000
136-
for i in dist:
137-
if i not in known and dist[i] < mini:
138-
mini = dist[i]
139-
u = i
136+
for key, value in dist:
137+
if key not in known and value < mini:
138+
mini = value
139+
u = key
140140
known.add(u)
141141
for v in g[u]:
142142
if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000):
143143
dist[v[0]] = dist[u] + v[1]
144144
path[v[0]] = u
145-
for i in dist:
146-
if i != s:
147-
print(dist[i])
145+
for key, value in dist.items():
146+
if key != s:
147+
print(value)
148148

149149

150150
"""
@@ -255,10 +255,10 @@ def prim(g, s):
255255
if len(known) == len(g) - 1:
256256
break
257257
mini = 100000
258-
for i in dist:
259-
if i not in known and dist[i] < mini:
260-
mini = dist[i]
261-
u = i
258+
for key, value in dist.items():
259+
if key not in known and value < mini:
260+
mini = value
261+
u = key
262262
known.add(u)
263263
for v in g[u]:
264264
if v[0] not in known and v[1] < dist.get(v[0], 100000):

graphs/minimum_spanning_tree_boruvka.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,12 @@ def boruvka_mst(graph):
185185

186186
if cheap_edge[set2] == -1 or cheap_edge[set2][2] > weight:
187187
cheap_edge[set2] = [head, tail, weight]
188-
for vertex in cheap_edge:
189-
if cheap_edge[vertex] != -1:
190-
head, tail, weight = cheap_edge[vertex]
188+
for head_tail_weight in cheap_edge.values():
189+
if head_tail_weight != -1:
190+
head, tail, weight = head_tail_weight
191191
if union_find.find(head) != union_find.find(tail):
192192
union_find.union(head, tail)
193-
mst_edges.append(cheap_edge[vertex])
193+
mst_edges.append(head_tail_weight)
194194
num_components = num_components - 1
195195
mst = Graph.build(edges=mst_edges)
196196
return mst

hashes/md5.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def preprocess(message: bytes) -> bytes:
131131
return bit_string
132132

133133

134-
def get_block_words(bit_string: bytes) -> Generator[list[int], None, None]:
134+
def get_block_words(bit_string: bytes) -> Generator[list[int]]:
135135
"""
136136
Splits bit string into blocks of 512 chars and yields each block as a list
137137
of 32-bit words

machine_learning/frequent_pattern_growth.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,8 @@ def create_tree(data_set: list, min_sup: int = 1) -> tuple[TreeNode, dict]:
107107
if not (freq_item_set := set(header_table)):
108108
return TreeNode("Null Set", 1, None), {}
109109

110-
for k in header_table:
111-
header_table[k] = [header_table[k], None]
110+
for key, value in header_table.items():
111+
header_table[key] = [value, None]
112112

113113
fp_tree = TreeNode("Null Set", 1, None) # Parent is None for the root node
114114
for tran_set in data_set:

maths/collatz_sequence.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from collections.abc import Generator
1818

1919

20-
def collatz_sequence(n: int) -> Generator[int, None, None]:
20+
def collatz_sequence(n: int) -> Generator[int]:
2121
"""
2222
Generate the Collatz sequence starting at n.
2323
>>> tuple(collatz_sequence(2.1))

maths/prime_numbers.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from collections.abc import Generator
33

44

5-
def slow_primes(max_n: int) -> Generator[int, None, None]:
5+
def slow_primes(max_n: int) -> Generator[int]:
66
"""
77
Return a list of all primes numbers up to max.
88
>>> list(slow_primes(0))
@@ -29,7 +29,7 @@ def slow_primes(max_n: int) -> Generator[int, None, None]:
2929
yield i
3030

3131

32-
def primes(max_n: int) -> Generator[int, None, None]:
32+
def primes(max_n: int) -> Generator[int]:
3333
"""
3434
Return a list of all primes numbers up to max.
3535
>>> list(primes(0))
@@ -58,7 +58,7 @@ def primes(max_n: int) -> Generator[int, None, None]:
5858
yield i
5959

6060

61-
def fast_primes(max_n: int) -> Generator[int, None, None]:
61+
def fast_primes(max_n: int) -> Generator[int]:
6262
"""
6363
Return a list of all primes numbers up to max.
6464
>>> list(fast_primes(0))

maths/volume.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from __future__ import annotations
88

9-
from math import pi, pow
9+
from math import pi, pow # noqa: A004
1010

1111

1212
def vol_cube(side_length: float) -> float:

neural_network/input_data.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,8 @@ def _extract_images(f):
6161
with gzip.GzipFile(fileobj=f) as bytestream:
6262
magic = _read32(bytestream)
6363
if magic != 2051:
64-
raise ValueError(
65-
"Invalid magic number %d in MNIST image file: %s" % (magic, f.name)
66-
)
64+
msg = f"Invalid magic number {magic} in MNIST image file: {f.name}"
65+
raise ValueError(msg)
6766
num_images = _read32(bytestream)
6867
rows = _read32(bytestream)
6968
cols = _read32(bytestream)
@@ -102,9 +101,8 @@ def _extract_labels(f, one_hot=False, num_classes=10):
102101
with gzip.GzipFile(fileobj=f) as bytestream:
103102
magic = _read32(bytestream)
104103
if magic != 2049:
105-
raise ValueError(
106-
"Invalid magic number %d in MNIST label file: %s" % (magic, f.name)
107-
)
104+
msg = f"Invalid magic number {magic} in MNIST label file: {f.name}"
105+
raise ValueError(msg)
108106
num_items = _read32(bytestream)
109107
buf = bytestream.read(num_items)
110108
labels = np.frombuffer(buf, dtype=np.uint8)

physics/basic_orbital_capture.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
from math import pow, sqrt
2-
3-
from scipy.constants import G, c, pi
4-
51
"""
62
These two functions will return the radii of impact for a target object
73
of mass M and radius R as well as it's effective cross sectional area sigma.
@@ -14,9 +10,12 @@
1410
cross section for capture as sigma=π*R_capture**2.
1511
1612
This algorithm does not account for an N-body problem.
17-
1813
"""
1914

15+
from math import pow, sqrt # noqa: A004
16+
17+
from scipy.constants import G, c, pi
18+
2019

2120
def capture_radii(
2221
target_body_radius: float, target_body_mass: float, projectile_velocity: float

physics/grahams_law.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
(Description adapted from https://en.wikipedia.org/wiki/Graham%27s_law)
1515
"""
1616

17-
from math import pow, sqrt
17+
from math import pow, sqrt # noqa: A004
1818

1919

2020
def validate(*values: float) -> bool:

project_euler/problem_025/sol2.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
from collections.abc import Generator
2828

2929

30-
def fibonacci_generator() -> Generator[int, None, None]:
30+
def fibonacci_generator() -> Generator[int]:
3131
"""
3232
A generator that produces numbers in the Fibonacci sequence
3333

0 commit comments

Comments
 (0)