Skip to content

Commit 516a302

Browse files
MaximSmolskiypre-commit-ci[bot]
andauthoredMar 28, 2024
Enable ruff PLR5501 rule (TheAlgorithms#11332)
* Enable ruff PLR5501 rule * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 19fd435 commit 516a302

24 files changed

+211
-239
lines changed
 

‎backtracking/crossword_puzzle_solver.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,8 @@ def is_valid(
2828
if vertical:
2929
if row + i >= len(puzzle) or puzzle[row + i][col] != "":
3030
return False
31-
else:
32-
if col + i >= len(puzzle[0]) or puzzle[row][col + i] != "":
33-
return False
31+
elif col + i >= len(puzzle[0]) or puzzle[row][col + i] != "":
32+
return False
3433
return True
3534

3635

‎cellular_automata/game_of_life.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,8 @@ def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool:
101101
state = True
102102
elif alive > 3:
103103
state = False
104-
else:
105-
if alive == 3:
106-
state = True
104+
elif alive == 3:
105+
state = True
107106

108107
return state
109108

‎ciphers/decrypt_caesar_with_chi_squared.py

+10-11
Original file line numberDiff line numberDiff line change
@@ -206,20 +206,19 @@ def decrypt_caesar_with_chi_squared(
206206

207207
# Add the margin of error to the total chi squared statistic
208208
chi_squared_statistic += chi_letter_value
209-
else:
210-
if letter.lower() in frequencies:
211-
# Get the amount of times the letter occurs in the message
212-
occurrences = decrypted_with_shift.count(letter)
209+
elif letter.lower() in frequencies:
210+
# Get the amount of times the letter occurs in the message
211+
occurrences = decrypted_with_shift.count(letter)
213212

214-
# Get the excepcted amount of times the letter should appear based
215-
# on letter frequencies
216-
expected = frequencies[letter] * occurrences
213+
# Get the excepcted amount of times the letter should appear based
214+
# on letter frequencies
215+
expected = frequencies[letter] * occurrences
217216

218-
# Complete the chi squared statistic formula
219-
chi_letter_value = ((occurrences - expected) ** 2) / expected
217+
# Complete the chi squared statistic formula
218+
chi_letter_value = ((occurrences - expected) ** 2) / expected
220219

221-
# Add the margin of error to the total chi squared statistic
222-
chi_squared_statistic += chi_letter_value
220+
# Add the margin of error to the total chi squared statistic
221+
chi_squared_statistic += chi_letter_value
223222

224223
# Add the data to the chi_squared_statistic_values dictionary
225224
chi_squared_statistic_values[shift] = (

‎data_structures/binary_tree/avl_tree.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -215,11 +215,11 @@ def del_node(root: MyNode, data: Any) -> MyNode | None:
215215
return root
216216
else:
217217
root.set_left(del_node(left_child, data))
218-
else: # root.get_data() < data
219-
if right_child is None:
220-
return root
221-
else:
222-
root.set_right(del_node(right_child, data))
218+
# root.get_data() < data
219+
elif right_child is None:
220+
return root
221+
else:
222+
root.set_right(del_node(right_child, data))
223223

224224
if get_height(right_child) - get_height(left_child) == 2:
225225
assert right_child is not None

‎data_structures/binary_tree/binary_search_tree.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,11 @@ def __insert(self, value) -> None:
185185
break
186186
else:
187187
parent_node = parent_node.left
188+
elif parent_node.right is None:
189+
parent_node.right = new_node
190+
break
188191
else:
189-
if parent_node.right is None:
190-
parent_node.right = new_node
191-
break
192-
else:
193-
parent_node = parent_node.right
192+
parent_node = parent_node.right
194193
new_node.parent = parent_node
195194

196195
def insert(self, *values) -> Self:

‎data_structures/binary_tree/binary_search_tree_recursive.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,13 @@ def put(self, label: int) -> None:
7474
def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node:
7575
if node is None:
7676
node = Node(label, parent)
77+
elif label < node.label:
78+
node.left = self._put(node.left, label, node)
79+
elif label > node.label:
80+
node.right = self._put(node.right, label, node)
7781
else:
78-
if label < node.label:
79-
node.left = self._put(node.left, label, node)
80-
elif label > node.label:
81-
node.right = self._put(node.right, label, node)
82-
else:
83-
msg = f"Node with label {label} already exists"
84-
raise ValueError(msg)
82+
msg = f"Node with label {label} already exists"
83+
raise ValueError(msg)
8584

8685
return node
8786

@@ -106,11 +105,10 @@ def _search(self, node: Node | None, label: int) -> Node:
106105
if node is None:
107106
msg = f"Node with label {label} does not exist"
108107
raise ValueError(msg)
109-
else:
110-
if label < node.label:
111-
node = self._search(node.left, label)
112-
elif label > node.label:
113-
node = self._search(node.right, label)
108+
elif label < node.label:
109+
node = self._search(node.left, label)
110+
elif label > node.label:
111+
node = self._search(node.right, label)
114112

115113
return node
116114

‎data_structures/binary_tree/red_black_tree.py

+31-35
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,11 @@ def insert(self, label: int) -> RedBlackTree:
107107
else:
108108
self.left = RedBlackTree(label, 1, self)
109109
self.left._insert_repair()
110+
elif self.right:
111+
self.right.insert(label)
110112
else:
111-
if self.right:
112-
self.right.insert(label)
113-
else:
114-
self.right = RedBlackTree(label, 1, self)
115-
self.right._insert_repair()
113+
self.right = RedBlackTree(label, 1, self)
114+
self.right._insert_repair()
116115
return self.parent or self
117116

118117
def _insert_repair(self) -> None:
@@ -178,36 +177,34 @@ def remove(self, label: int) -> RedBlackTree: # noqa: PLR0912
178177
self.parent.left = None
179178
else:
180179
self.parent.right = None
181-
else:
182-
# The node is black
183-
if child is None:
184-
# This node and its child are black
185-
if self.parent is None:
186-
# The tree is now empty
187-
return RedBlackTree(None)
188-
else:
189-
self._remove_repair()
190-
if self.is_left():
191-
self.parent.left = None
192-
else:
193-
self.parent.right = None
194-
self.parent = None
180+
# The node is black
181+
elif child is None:
182+
# This node and its child are black
183+
if self.parent is None:
184+
# The tree is now empty
185+
return RedBlackTree(None)
195186
else:
196-
# This node is black and its child is red
197-
# Move the child node here and make it black
198-
self.label = child.label
199-
self.left = child.left
200-
self.right = child.right
201-
if self.left:
202-
self.left.parent = self
203-
if self.right:
204-
self.right.parent = self
187+
self._remove_repair()
188+
if self.is_left():
189+
self.parent.left = None
190+
else:
191+
self.parent.right = None
192+
self.parent = None
193+
else:
194+
# This node is black and its child is red
195+
# Move the child node here and make it black
196+
self.label = child.label
197+
self.left = child.left
198+
self.right = child.right
199+
if self.left:
200+
self.left.parent = self
201+
if self.right:
202+
self.right.parent = self
205203
elif self.label is not None and self.label > label:
206204
if self.left:
207205
self.left.remove(label)
208-
else:
209-
if self.right:
210-
self.right.remove(label)
206+
elif self.right:
207+
self.right.remove(label)
211208
return self.parent or self
212209

213210
def _remove_repair(self) -> None:
@@ -369,11 +366,10 @@ def search(self, label: int) -> RedBlackTree | None:
369366
return None
370367
else:
371368
return self.right.search(label)
369+
elif self.left is None:
370+
return None
372371
else:
373-
if self.left is None:
374-
return None
375-
else:
376-
return self.left.search(label)
372+
return self.left.search(label)
377373

378374
def floor(self, label: int) -> int | None:
379375
"""Returns the largest element in this tree which is at most label.

‎data_structures/binary_tree/treap.py

+14-15
Original file line numberDiff line numberDiff line change
@@ -43,22 +43,21 @@ def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]:
4343
return None, None
4444
elif root.value is None:
4545
return None, None
46+
elif value < root.value:
47+
"""
48+
Right tree's root will be current node.
49+
Now we split(with the same value) current node's left son
50+
Left tree: left part of that split
51+
Right tree's left son: right part of that split
52+
"""
53+
left, root.left = split(root.left, value)
54+
return left, root
4655
else:
47-
if value < root.value:
48-
"""
49-
Right tree's root will be current node.
50-
Now we split(with the same value) current node's left son
51-
Left tree: left part of that split
52-
Right tree's left son: right part of that split
53-
"""
54-
left, root.left = split(root.left, value)
55-
return left, root
56-
else:
57-
"""
58-
Just symmetric to previous case
59-
"""
60-
root.right, right = split(root.right, value)
61-
return root, right
56+
"""
57+
Just symmetric to previous case
58+
"""
59+
root.right, right = split(root.right, value)
60+
return root, right
6261

6362

6463
def merge(left: Node | None, right: Node | None) -> Node | None:

‎data_structures/heap/max_heap.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,10 @@ def __swap_down(self, i: int) -> None:
4040
while self.__size >= 2 * i:
4141
if 2 * i + 1 > self.__size:
4242
bigger_child = 2 * i
43+
elif self.__heap[2 * i] > self.__heap[2 * i + 1]:
44+
bigger_child = 2 * i
4345
else:
44-
if self.__heap[2 * i] > self.__heap[2 * i + 1]:
45-
bigger_child = 2 * i
46-
else:
47-
bigger_child = 2 * i + 1
46+
bigger_child = 2 * i + 1
4847
temporary = self.__heap[i]
4948
if self.__heap[i] < self.__heap[bigger_child]:
5049
self.__heap[i] = self.__heap[bigger_child]

‎data_structures/stacks/infix_to_prefix_conversion.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -95,13 +95,12 @@ def infix_2_postfix(infix: str) -> str:
9595
while stack[-1] != "(":
9696
post_fix.append(stack.pop()) # Pop stack & add the content to Postfix
9797
stack.pop()
98-
else:
99-
if len(stack) == 0:
100-
stack.append(x) # If stack is empty, push x to stack
101-
else: # while priority of x is not > priority of element in the stack
102-
while stack and stack[-1] != "(" and priority[x] <= priority[stack[-1]]:
103-
post_fix.append(stack.pop()) # pop stack & add to Postfix
104-
stack.append(x) # push x to stack
98+
elif len(stack) == 0:
99+
stack.append(x) # If stack is empty, push x to stack
100+
else: # while priority of x is not > priority of element in the stack
101+
while stack and stack[-1] != "(" and priority[x] <= priority[stack[-1]]:
102+
post_fix.append(stack.pop()) # pop stack & add to Postfix
103+
stack.append(x) # push x to stack
105104

106105
print(
107106
x.center(8),

‎data_structures/trie/radix_tree.py

+22-23
Original file line numberDiff line numberDiff line change
@@ -153,31 +153,30 @@ def delete(self, word: str) -> bool:
153153
# We have word remaining so we check the next node
154154
elif remaining_word != "":
155155
return incoming_node.delete(remaining_word)
156+
# If it is not a leaf, we don't have to delete
157+
elif not incoming_node.is_leaf:
158+
return False
156159
else:
157-
# If it is not a leaf, we don't have to delete
158-
if not incoming_node.is_leaf:
159-
return False
160+
# We delete the nodes if no edges go from it
161+
if len(incoming_node.nodes) == 0:
162+
del self.nodes[word[0]]
163+
# We merge the current node with its only child
164+
if len(self.nodes) == 1 and not self.is_leaf:
165+
merging_node = next(iter(self.nodes.values()))
166+
self.is_leaf = merging_node.is_leaf
167+
self.prefix += merging_node.prefix
168+
self.nodes = merging_node.nodes
169+
# If there is more than 1 edge, we just mark it as non-leaf
170+
elif len(incoming_node.nodes) > 1:
171+
incoming_node.is_leaf = False
172+
# If there is 1 edge, we merge it with its child
160173
else:
161-
# We delete the nodes if no edges go from it
162-
if len(incoming_node.nodes) == 0:
163-
del self.nodes[word[0]]
164-
# We merge the current node with its only child
165-
if len(self.nodes) == 1 and not self.is_leaf:
166-
merging_node = next(iter(self.nodes.values()))
167-
self.is_leaf = merging_node.is_leaf
168-
self.prefix += merging_node.prefix
169-
self.nodes = merging_node.nodes
170-
# If there is more than 1 edge, we just mark it as non-leaf
171-
elif len(incoming_node.nodes) > 1:
172-
incoming_node.is_leaf = False
173-
# If there is 1 edge, we merge it with its child
174-
else:
175-
merging_node = next(iter(incoming_node.nodes.values()))
176-
incoming_node.is_leaf = merging_node.is_leaf
177-
incoming_node.prefix += merging_node.prefix
178-
incoming_node.nodes = merging_node.nodes
179-
180-
return True
174+
merging_node = next(iter(incoming_node.nodes.values()))
175+
incoming_node.is_leaf = merging_node.is_leaf
176+
incoming_node.prefix += merging_node.prefix
177+
incoming_node.nodes = merging_node.nodes
178+
179+
return True
181180

182181
def print_tree(self, height: int = 0) -> None:
183182
"""Print the tree

‎divide_and_conquer/convex_hull.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -274,14 +274,13 @@ def convex_hull_bf(points: list[Point]) -> list[Point]:
274274
points_left_of_ij = True
275275
elif det_k < 0:
276276
points_right_of_ij = True
277-
else:
278-
# point[i], point[j], point[k] all lie on a straight line
279-
# if point[k] is to the left of point[i] or it's to the
280-
# right of point[j], then point[i], point[j] cannot be
281-
# part of the convex hull of A
282-
if points[k] < points[i] or points[k] > points[j]:
283-
ij_part_of_convex_hull = False
284-
break
277+
# point[i], point[j], point[k] all lie on a straight line
278+
# if point[k] is to the left of point[i] or it's to the
279+
# right of point[j], then point[i], point[j] cannot be
280+
# part of the convex hull of A
281+
elif points[k] < points[i] or points[k] > points[j]:
282+
ij_part_of_convex_hull = False
283+
break
285284

286285
if points_left_of_ij and points_right_of_ij:
287286
ij_part_of_convex_hull = False

‎graphs/graph_list.py

+23-23
Original file line numberDiff line numberDiff line change
@@ -120,29 +120,29 @@ def add_edge(
120120
else:
121121
self.adj_list[source_vertex] = [destination_vertex]
122122
self.adj_list[destination_vertex] = [source_vertex]
123-
else: # For directed graphs
124-
# if both source vertex and destination vertex are present in adjacency
125-
# list, add destination vertex to source vertex list of adjacent vertices.
126-
if source_vertex in self.adj_list and destination_vertex in self.adj_list:
127-
self.adj_list[source_vertex].append(destination_vertex)
128-
# if only source vertex is present in adjacency list, add destination
129-
# vertex to source vertex list of adjacent vertices and create a new vertex
130-
# with destination vertex as key, which has no adjacent vertex
131-
elif source_vertex in self.adj_list:
132-
self.adj_list[source_vertex].append(destination_vertex)
133-
self.adj_list[destination_vertex] = []
134-
# if only destination vertex is present in adjacency list, create a new
135-
# vertex with source vertex as key and assign a list containing destination
136-
# vertex as first adjacent vertex
137-
elif destination_vertex in self.adj_list:
138-
self.adj_list[source_vertex] = [destination_vertex]
139-
# if both source vertex and destination vertex are not present in adjacency
140-
# list, create a new vertex with source vertex as key and a list containing
141-
# destination vertex as it's first adjacent vertex. Then create a new vertex
142-
# with destination vertex as key, which has no adjacent vertex
143-
else:
144-
self.adj_list[source_vertex] = [destination_vertex]
145-
self.adj_list[destination_vertex] = []
123+
# For directed graphs
124+
# if both source vertex and destination vertex are present in adjacency
125+
# list, add destination vertex to source vertex list of adjacent vertices.
126+
elif source_vertex in self.adj_list and destination_vertex in self.adj_list:
127+
self.adj_list[source_vertex].append(destination_vertex)
128+
# if only source vertex is present in adjacency list, add destination
129+
# vertex to source vertex list of adjacent vertices and create a new vertex
130+
# with destination vertex as key, which has no adjacent vertex
131+
elif source_vertex in self.adj_list:
132+
self.adj_list[source_vertex].append(destination_vertex)
133+
self.adj_list[destination_vertex] = []
134+
# if only destination vertex is present in adjacency list, create a new
135+
# vertex with source vertex as key and assign a list containing destination
136+
# vertex as first adjacent vertex
137+
elif destination_vertex in self.adj_list:
138+
self.adj_list[source_vertex] = [destination_vertex]
139+
# if both source vertex and destination vertex are not present in adjacency
140+
# list, create a new vertex with source vertex as key and a list containing
141+
# destination vertex as it's first adjacent vertex. Then create a new vertex
142+
# with destination vertex as key, which has no adjacent vertex
143+
else:
144+
self.adj_list[source_vertex] = [destination_vertex]
145+
self.adj_list[destination_vertex] = []
146146

147147
return self
148148

‎graphs/minimum_spanning_tree_prims.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,10 @@ def top_to_bottom(self, heap, start, size, positions):
1818
else:
1919
if 2 * start + 2 >= size:
2020
smallest_child = 2 * start + 1
21+
elif heap[2 * start + 1] < heap[2 * start + 2]:
22+
smallest_child = 2 * start + 1
2123
else:
22-
if heap[2 * start + 1] < heap[2 * start + 2]:
23-
smallest_child = 2 * start + 1
24-
else:
25-
smallest_child = 2 * start + 2
24+
smallest_child = 2 * start + 2
2625
if heap[smallest_child] < heap[start]:
2726
temp, temp1 = heap[smallest_child], positions[smallest_child]
2827
heap[smallest_child], positions[smallest_child] = (

‎graphs/multi_heuristic_astar.py

+16-17
Original file line numberDiff line numberDiff line change
@@ -270,24 +270,23 @@ def multi_a_star(start: TPos, goal: TPos, n_heuristic: int):
270270
back_pointer,
271271
)
272272
close_list_inad.append(get_s)
273+
elif g_function[goal] <= open_list[0].minkey():
274+
if g_function[goal] < float("inf"):
275+
do_something(back_pointer, goal, start)
273276
else:
274-
if g_function[goal] <= open_list[0].minkey():
275-
if g_function[goal] < float("inf"):
276-
do_something(back_pointer, goal, start)
277-
else:
278-
get_s = open_list[0].top_show()
279-
visited.add(get_s)
280-
expand_state(
281-
get_s,
282-
0,
283-
visited,
284-
g_function,
285-
close_list_anchor,
286-
close_list_inad,
287-
open_list,
288-
back_pointer,
289-
)
290-
close_list_anchor.append(get_s)
277+
get_s = open_list[0].top_show()
278+
visited.add(get_s)
279+
expand_state(
280+
get_s,
281+
0,
282+
visited,
283+
g_function,
284+
close_list_anchor,
285+
close_list_inad,
286+
open_list,
287+
back_pointer,
288+
)
289+
close_list_anchor.append(get_s)
291290
print("No path found to goal")
292291
print()
293292
for i in range(n - 1, -1, -1):

‎machine_learning/forecasting/run.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -113,11 +113,10 @@ def data_safety_checker(list_vote: list, actual_result: float) -> bool:
113113
for i in list_vote:
114114
if i > actual_result:
115115
safe = not_safe + 1
116+
elif abs(abs(i) - abs(actual_result)) <= 0.1:
117+
safe += 1
116118
else:
117-
if abs(abs(i) - abs(actual_result)) <= 0.1:
118-
safe += 1
119-
else:
120-
not_safe += 1
119+
not_safe += 1
121120
return safe > not_safe
122121

123122

‎maths/largest_of_very_large_numbers.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,10 @@ def res(x, y):
2020
if 0 not in (x, y):
2121
# We use the relation x^y = y*log10(x), where 10 is the base.
2222
return y * math.log10(x)
23-
else:
24-
if x == 0: # 0 raised to any number is 0
25-
return 0
26-
elif y == 0:
27-
return 1 # any number raised to 0 is 1
23+
elif x == 0: # 0 raised to any number is 0
24+
return 0
25+
elif y == 0:
26+
return 1 # any number raised to 0 is 1
2827
raise AssertionError("This should never happen")
2928

3029

‎maths/pollard_rho.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,13 @@ def rand_fn(value: int, step: int, modulus: int) -> int:
9494
if divisor == 1:
9595
# No common divisor yet, just keep searching.
9696
continue
97+
# We found a common divisor!
98+
elif divisor == num:
99+
# Unfortunately, the divisor is ``num`` itself and is useless.
100+
break
97101
else:
98-
# We found a common divisor!
99-
if divisor == num:
100-
# Unfortunately, the divisor is ``num`` itself and is useless.
101-
break
102-
else:
103-
# The divisor is a nontrivial factor of ``num``!
104-
return divisor
102+
# The divisor is a nontrivial factor of ``num``!
103+
return divisor
105104

106105
# If we made it here, then this attempt failed.
107106
# We need to pick a new starting seed for the tortoise and hare

‎matrix/cramers_rule_2x2.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,11 @@ def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> tuple[float,
7373
raise ValueError("Infinite solutions. (Consistent system)")
7474
else:
7575
raise ValueError("No solution. (Inconsistent system)")
76+
elif determinant_x == determinant_y == 0:
77+
# Trivial solution (Inconsistent system)
78+
return (0.0, 0.0)
7679
else:
77-
if determinant_x == determinant_y == 0:
78-
# Trivial solution (Inconsistent system)
79-
return (0.0, 0.0)
80-
else:
81-
x = determinant_x / determinant
82-
y = determinant_y / determinant
83-
# Non-Trivial Solution (Consistent system)
84-
return (x, y)
80+
x = determinant_x / determinant
81+
y = determinant_y / determinant
82+
# Non-Trivial Solution (Consistent system)
83+
return (x, y)

‎project_euler/problem_019/sol1.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,9 @@ def solution():
4646
elif day > 29 and month == 2:
4747
month += 1
4848
day = day - 29
49-
else:
50-
if day > days_per_month[month - 1]:
51-
month += 1
52-
day = day - days_per_month[month - 2]
49+
elif day > days_per_month[month - 1]:
50+
month += 1
51+
day = day - days_per_month[month - 2]
5352

5453
if month > 12:
5554
year += 1

‎pyproject.toml

-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ lint.ignore = [ # `ruff rule S101` for a description of that rule
1212
"NPY002", # Replace legacy `np.random.choice` call with `np.random.Generator` -- FIX ME
1313
"PGH003", # Use specific rule codes when ignoring type issues -- FIX ME
1414
"PLC1901", # `{}` can be simplified to `{}` as an empty string is falsey
15-
"PLR5501", # Consider using `elif` instead of `else` -- FIX ME
1615
"PLW0120", # `else` clause on loop without a `break` statement -- FIX ME
1716
"PLW060", # Using global for `{name}` but no assignment is done -- DO NOT FIX
1817
"PLW2901", # PLW2901: Redefined loop variable -- FIX ME

‎searches/hill_climbing.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,10 @@ def hill_climbing(
137137
if change > max_change and change > 0:
138138
max_change = change
139139
next_state = neighbor
140-
else: # finding min
140+
elif change < min_change and change < 0: # finding min
141141
# to direction with greatest descent
142-
if change < min_change and change < 0:
143-
min_change = change
144-
next_state = neighbor
142+
min_change = change
143+
next_state = neighbor
145144
if next_state is not None:
146145
# we found at least one neighbor which improved the current state
147146
current_state = next_state

‎searches/interpolation_search.py

+16-19
Original file line numberDiff line numberDiff line change
@@ -33,18 +33,16 @@ def interpolation_search(sorted_collection, item):
3333
current_item = sorted_collection[point]
3434
if current_item == item:
3535
return point
36+
elif point < left:
37+
right = left
38+
left = point
39+
elif point > right:
40+
left = right
41+
right = point
42+
elif item < current_item:
43+
right = point - 1
3644
else:
37-
if point < left:
38-
right = left
39-
left = point
40-
elif point > right:
41-
left = right
42-
right = point
43-
else:
44-
if item < current_item:
45-
right = point - 1
46-
else:
47-
left = point + 1
45+
left = point + 1
4846
return None
4947

5048

@@ -79,15 +77,14 @@ def interpolation_search_by_recursion(sorted_collection, item, left, right):
7977
return interpolation_search_by_recursion(sorted_collection, item, point, left)
8078
elif point > right:
8179
return interpolation_search_by_recursion(sorted_collection, item, right, left)
80+
elif sorted_collection[point] > item:
81+
return interpolation_search_by_recursion(
82+
sorted_collection, item, left, point - 1
83+
)
8284
else:
83-
if sorted_collection[point] > item:
84-
return interpolation_search_by_recursion(
85-
sorted_collection, item, left, point - 1
86-
)
87-
else:
88-
return interpolation_search_by_recursion(
89-
sorted_collection, item, point + 1, right
90-
)
85+
return interpolation_search_by_recursion(
86+
sorted_collection, item, point + 1, right
87+
)
9188

9289

9390
def __assert_sorted(collection):

‎strings/min_cost_string_conversion.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -60,19 +60,18 @@ def compute_transform_tables(
6060
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
6161
if i == 0 and j == 0:
6262
return []
63+
elif ops[i][j][0] in {"C", "R"}:
64+
seq = assemble_transformation(ops, i - 1, j - 1)
65+
seq.append(ops[i][j])
66+
return seq
67+
elif ops[i][j][0] == "D":
68+
seq = assemble_transformation(ops, i - 1, j)
69+
seq.append(ops[i][j])
70+
return seq
6371
else:
64-
if ops[i][j][0] in {"C", "R"}:
65-
seq = assemble_transformation(ops, i - 1, j - 1)
66-
seq.append(ops[i][j])
67-
return seq
68-
elif ops[i][j][0] == "D":
69-
seq = assemble_transformation(ops, i - 1, j)
70-
seq.append(ops[i][j])
71-
return seq
72-
else:
73-
seq = assemble_transformation(ops, i, j - 1)
74-
seq.append(ops[i][j])
75-
return seq
72+
seq = assemble_transformation(ops, i, j - 1)
73+
seq.append(ops[i][j])
74+
return seq
7675

7776

7877
if __name__ == "__main__":

0 commit comments

Comments
 (0)
Please sign in to comment.