Skip to content

Commit 64543fa

Browse files
authored
Make some ruff fixes (TheAlgorithms#8154)
* Make some ruff fixes * Undo manual fix * Undo manual fix * Updates from ruff=0.0.251
1 parent 1c15cdf commit 64543fa

File tree

73 files changed

+151
-203
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+151
-203
lines changed

audio_filters/iir_filter.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None
4747
>>> filt.set_coefficients(a_coeffs, b_coeffs)
4848
"""
4949
if len(a_coeffs) < self.order:
50-
a_coeffs = [1.0] + a_coeffs
50+
a_coeffs = [1.0, *a_coeffs]
5151

5252
if len(a_coeffs) != self.order + 1:
5353
raise ValueError(

backtracking/n_queens_math.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,9 @@ def depth_first_search(
129129

130130
# If it is False we call dfs function again and we update the inputs
131131
depth_first_search(
132-
possible_board + [col],
133-
diagonal_right_collisions + [row - col],
134-
diagonal_left_collisions + [row + col],
132+
[*possible_board, col],
133+
[*diagonal_right_collisions, row - col],
134+
[*diagonal_left_collisions, row + col],
135135
boards,
136136
n,
137137
)

backtracking/sum_of_subsets.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def create_state_space_tree(
4444
nums,
4545
max_sum,
4646
index + 1,
47-
path + [nums[index]],
47+
[*path, nums[index]],
4848
result,
4949
remaining_nums_sum - nums[index],
5050
)

ciphers/bifid.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def letter_to_numbers(self, letter: str) -> np.ndarray:
3333
>>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5])
3434
True
3535
"""
36-
index1, index2 = np.where(self.SQUARE == letter)
36+
index1, index2 = np.where(letter == self.SQUARE)
3737
indexes = np.concatenate([index1 + 1, index2 + 1])
3838
return indexes
3939

ciphers/diffie_hellman.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -228,10 +228,10 @@ def generate_public_key(self) -> str:
228228

229229
def is_valid_public_key(self, key: int) -> bool:
230230
# check if the other public key is valid based on NIST SP800-56
231-
if 2 <= key and key <= self.prime - 2:
232-
if pow(key, (self.prime - 1) // 2, self.prime) == 1:
233-
return True
234-
return False
231+
return (
232+
2 <= key <= self.prime - 2
233+
and pow(key, (self.prime - 1) // 2, self.prime) == 1
234+
)
235235

236236
def generate_shared_key(self, other_key_str: str) -> str:
237237
other_key = int(other_key_str, base=16)
@@ -243,10 +243,10 @@ def generate_shared_key(self, other_key_str: str) -> str:
243243
@staticmethod
244244
def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool:
245245
# check if the other public key is valid based on NIST SP800-56
246-
if 2 <= remote_public_key_str and remote_public_key_str <= prime - 2:
247-
if pow(remote_public_key_str, (prime - 1) // 2, prime) == 1:
248-
return True
249-
return False
246+
return (
247+
2 <= remote_public_key_str <= prime - 2
248+
and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1
249+
)
250250

251251
@staticmethod
252252
def generate_shared_key_static(

ciphers/polybius.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def letter_to_numbers(self, letter: str) -> np.ndarray:
3131
>>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5])
3232
True
3333
"""
34-
index1, index2 = np.where(self.SQUARE == letter)
34+
index1, index2 = np.where(letter == self.SQUARE)
3535
indexes = np.concatenate([index1 + 1, index2 + 1])
3636
return indexes
3737

ciphers/xor_cipher.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -128,11 +128,10 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
128128
assert isinstance(file, str) and isinstance(key, int)
129129

130130
try:
131-
with open(file) as fin:
132-
with open("encrypt.out", "w+") as fout:
133-
# actual encrypt-process
134-
for line in fin:
135-
fout.write(self.encrypt_string(line, key))
131+
with open(file) as fin, open("encrypt.out", "w+") as fout:
132+
# actual encrypt-process
133+
for line in fin:
134+
fout.write(self.encrypt_string(line, key))
136135

137136
except OSError:
138137
return False
@@ -152,11 +151,10 @@ def decrypt_file(self, file: str, key: int) -> bool:
152151
assert isinstance(file, str) and isinstance(key, int)
153152

154153
try:
155-
with open(file) as fin:
156-
with open("decrypt.out", "w+") as fout:
157-
# actual encrypt-process
158-
for line in fin:
159-
fout.write(self.decrypt_string(line, key))
154+
with open(file) as fin, open("decrypt.out", "w+") as fout:
155+
# actual encrypt-process
156+
for line in fin:
157+
fout.write(self.decrypt_string(line, key))
160158

161159
except OSError:
162160
return False

computer_vision/mosaic_augmentation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def update_image_and_anno(
159159
new_anno.append([bbox[0], xmin, ymin, xmax, ymax])
160160

161161
# Remove bounding box small than scale of filter
162-
if 0 < filter_scale:
162+
if filter_scale > 0:
163163
new_anno = [
164164
anno
165165
for anno in new_anno

data_structures/binary_tree/binary_search_tree.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def __insert(self, value) -> None:
6060
else: # Tree is not empty
6161
parent_node = self.root # from root
6262
if parent_node is None:
63-
return None
63+
return
6464
while True: # While we don't get to a leaf
6565
if value < parent_node.value: # We go left
6666
if parent_node.left is None:

data_structures/binary_tree/binary_tree_traversals.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def preorder(root: Node | None) -> list[int]:
3737
>>> preorder(make_tree())
3838
[1, 2, 4, 5, 3]
3939
"""
40-
return [root.data] + preorder(root.left) + preorder(root.right) if root else []
40+
return [root.data, *preorder(root.left), *preorder(root.right)] if root else []
4141

4242

4343
def postorder(root: Node | None) -> list[int]:
@@ -55,7 +55,7 @@ def inorder(root: Node | None) -> list[int]:
5555
>>> inorder(make_tree())
5656
[4, 2, 5, 1, 3]
5757
"""
58-
return inorder(root.left) + [root.data] + inorder(root.right) if root else []
58+
return [*inorder(root.left), root.data, *inorder(root.right)] if root else []
5959

6060

6161
def height(root: Node | None) -> int:

data_structures/binary_tree/inorder_tree_traversal_2022.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return
5050
"""
5151
if node:
5252
inorder_array = inorder(node.left_child)
53-
inorder_array = inorder_array + [node.data]
53+
inorder_array = [*inorder_array, node.data]
5454
inorder_array = inorder_array + inorder(node.right_child)
5555
else:
5656
inorder_array = []

data_structures/binary_tree/red_black_tree.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -319,9 +319,8 @@ def check_coloring(self) -> bool:
319319
"""A helper function to recursively check Property 4 of a
320320
Red-Black Tree. See check_color_properties for more info.
321321
"""
322-
if self.color == 1:
323-
if color(self.left) == 1 or color(self.right) == 1:
324-
return False
322+
if self.color == 1 and 1 in (color(self.left), color(self.right)):
323+
return False
325324
if self.left and not self.left.check_coloring():
326325
return False
327326
if self.right and not self.right.check_coloring():

data_structures/hashing/number_theory/prime_numbers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def next_prime(value, factor=1, **kwargs):
5252
first_value_val = value
5353

5454
while not is_prime(value):
55-
value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1
55+
value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1
5656

5757
if value == first_value_val:
5858
return next_prime(value + 1, **kwargs)

data_structures/heap/binomial_heap.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -136,12 +136,12 @@ def merge_heaps(self, other):
136136

137137
# Empty heaps corner cases
138138
if other.size == 0:
139-
return
139+
return None
140140
if self.size == 0:
141141
self.size = other.size
142142
self.bottom_root = other.bottom_root
143143
self.min_node = other.min_node
144-
return
144+
return None
145145
# Update size
146146
self.size = self.size + other.size
147147

data_structures/linked_list/doubly_linked_list_two.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def insert_at_position(self, position: int, value: int) -> None:
128128
while node:
129129
if current_position == position:
130130
self.insert_before_node(node, new_node)
131-
return None
131+
return
132132
current_position += 1
133133
node = node.next
134134
self.insert_after_node(self.tail, new_node)

data_structures/linked_list/singly_linked_list.py

+1
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ def __getitem__(self, index: int) -> Any:
107107
for i, node in enumerate(self):
108108
if i == index:
109109
return node
110+
return None
110111

111112
# Used to change the data of a particular node
112113
def __setitem__(self, index: int, data: Any) -> None:

data_structures/linked_list/skip_list.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -388,10 +388,7 @@ def traverse_keys(node):
388388

389389
def test_iter_always_yields_sorted_values():
390390
def is_sorted(lst):
391-
for item, next_item in zip(lst, lst[1:]):
392-
if next_item < item:
393-
return False
394-
return True
391+
return all(next_item >= item for item, next_item in zip(lst, lst[1:]))
395392

396393
skip_list = SkipList()
397394
for i in range(10):

data_structures/queue/circular_queue_linked_list.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def dequeue(self) -> Any:
127127
"""
128128
self.check_can_perform_operation()
129129
if self.rear is None or self.front is None:
130-
return
130+
return None
131131
if self.front == self.rear:
132132
data = self.front.data
133133
self.front.data = None

digital_image_processing/morphological_operations/dilation_operation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def gray2binary(gray: np.array) -> np.array:
3232
[False, True, False],
3333
[False, True, False]])
3434
"""
35-
return (127 < gray) & (gray <= 255)
35+
return (gray > 127) & (gray <= 255)
3636

3737

3838
def dilation(image: np.array, kernel: np.array) -> np.array:

digital_image_processing/morphological_operations/erosion_operation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def gray2binary(gray: np.array) -> np.array:
3232
[False, True, False],
3333
[False, True, False]])
3434
"""
35-
return (127 < gray) & (gray <= 255)
35+
return (gray > 127) & (gray <= 255)
3636

3737

3838
def erosion(image: np.array, kernel: np.array) -> np.array:

dynamic_programming/all_construct.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[
3434
# slice condition
3535
if target[i : i + len(word)] == word:
3636
new_combinations: list[list[str]] = [
37-
[word] + way for way in table[i]
37+
[word, *way] for way in table[i]
3838
]
3939
# adds the word to every combination the current position holds
4040
# now,push that combination to the table[i+len(word)]

dynamic_programming/fizz_buzz.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def fizz_buzz(number: int, iterations: int) -> str:
4949
out += "Fizz"
5050
if number % 5 == 0:
5151
out += "Buzz"
52-
if not number % 3 == 0 and not number % 5 == 0:
52+
if 0 not in (number % 3, number % 5):
5353
out += str(number)
5454

5555
# print(out)

dynamic_programming/longest_common_subsequence.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -42,20 +42,14 @@ def longest_common_subsequence(x: str, y: str):
4242

4343
for i in range(1, m + 1):
4444
for j in range(1, n + 1):
45-
if x[i - 1] == y[j - 1]:
46-
match = 1
47-
else:
48-
match = 0
45+
match = 1 if x[i - 1] == y[j - 1] else 0
4946

5047
l[i][j] = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match)
5148

5249
seq = ""
5350
i, j = m, n
5451
while i > 0 and j > 0:
55-
if x[i - 1] == y[j - 1]:
56-
match = 1
57-
else:
58-
match = 0
52+
match = 1 if x[i - 1] == y[j - 1] else 0
5953

6054
if l[i][j] == l[i - 1][j - 1] + match:
6155
if match == 1:

dynamic_programming/longest_increasing_subsequence.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
4848
i += 1
4949

5050
temp_array = [element for element in array[1:] if element >= pivot]
51-
temp_array = [pivot] + longest_subsequence(temp_array)
51+
temp_array = [pivot, *longest_subsequence(temp_array)]
5252
if len(temp_array) > len(longest_subseq):
5353
return temp_array
5454
else:

graphs/basic_graphs.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,9 @@ def dijk(g, s):
139139
u = i
140140
known.add(u)
141141
for v in g[u]:
142-
if v[0] not in known:
143-
if dist[u] + v[1] < dist.get(v[0], 100000):
144-
dist[v[0]] = dist[u] + v[1]
145-
path[v[0]] = u
142+
if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000):
143+
dist[v[0]] = dist[u] + v[1]
144+
path[v[0]] = u
146145
for i in dist:
147146
if i != s:
148147
print(dist[i])
@@ -243,10 +242,9 @@ def prim(g, s):
243242
u = i
244243
known.add(u)
245244
for v in g[u]:
246-
if v[0] not in known:
247-
if v[1] < dist.get(v[0], 100000):
248-
dist[v[0]] = v[1]
249-
path[v[0]] = u
245+
if v[0] not in known and v[1] < dist.get(v[0], 100000):
246+
dist[v[0]] = v[1]
247+
path[v[0]] = u
250248
return dist
251249

252250

graphs/check_cycle.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,10 @@ def check_cycle(graph: dict) -> bool:
1515
visited: set[int] = set()
1616
# To detect a back edge, keep track of vertices currently in the recursion stack
1717
rec_stk: set[int] = set()
18-
for node in graph:
19-
if node not in visited:
20-
if depth_first_search(graph, node, visited, rec_stk):
21-
return True
22-
return False
18+
return any(
19+
node not in visited and depth_first_search(graph, node, visited, rec_stk)
20+
for node in graph
21+
)
2322

2423

2524
def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool:

graphs/connected_components.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def dfs(graph: dict, vert: int, visited: list) -> list:
2727
if not visited[neighbour]:
2828
connected_verts += dfs(graph, neighbour, visited)
2929

30-
return [vert] + connected_verts
30+
return [vert, *connected_verts]
3131

3232

3333
def connected_components(graph: dict) -> list:

graphs/dijkstra_algorithm.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def dijkstra(self, src):
112112
self.dist[src] = 0
113113
q = PriorityQueue()
114114
q.insert((0, src)) # (dist from src, node)
115-
for u in self.adjList.keys():
115+
for u in self.adjList:
116116
if u != src:
117117
self.dist[u] = sys.maxsize # Infinity
118118
self.par[u] = -1

graphs/edmonds_karp_multiple_source_and_sink.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,8 @@ def relabel(self, vertex_index):
163163
self.graph[vertex_index][to_index]
164164
- self.preflow[vertex_index][to_index]
165165
> 0
166-
):
167-
if min_height is None or self.heights[to_index] < min_height:
168-
min_height = self.heights[to_index]
166+
) and (min_height is None or self.heights[to_index] < min_height):
167+
min_height = self.heights[to_index]
169168

170169
if min_height is not None:
171170
self.heights[vertex_index] = min_height + 1

graphs/frequent_pattern_graph_miner.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,11 @@ def create_edge(nodes, graph, cluster, c1):
130130
"""
131131
create edge between the nodes
132132
"""
133-
for i in cluster[c1].keys():
133+
for i in cluster[c1]:
134134
count = 0
135135
c2 = c1 + 1
136136
while c2 < max(cluster.keys()):
137-
for j in cluster[c2].keys():
137+
for j in cluster[c2]:
138138
"""
139139
creates edge only if the condition satisfies
140140
"""
@@ -185,7 +185,7 @@ def find_freq_subgraph_given_support(s, cluster, graph):
185185
find edges of multiple frequent subgraphs
186186
"""
187187
k = int(s / 100 * (len(cluster) - 1))
188-
for i in cluster[k].keys():
188+
for i in cluster[k]:
189189
my_dfs(graph, tuple(cluster[k][i]), (["Header"],))
190190

191191

0 commit comments

Comments
 (0)