Skip to content

Commit

Permalink
Enable ruff SIM102 rule (TheAlgorithms#11341)
Browse files Browse the repository at this point in the history
* Enable ruff SIM102 rule

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix

* [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>
  • Loading branch information
MaximSmolskiy and pre-commit-ci[bot] authored Apr 2, 2024
1 parent f8a9489 commit 93fb555
Show file tree
Hide file tree
Showing 13 changed files with 73 additions and 50 deletions.
7 changes: 3 additions & 4 deletions data_structures/arrays/sudoku_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,9 @@ def eliminate(values, s, d):
dplaces = [s for s in u if d in values[s]]
if len(dplaces) == 0:
return False ## Contradiction: no place for this value
elif len(dplaces) == 1:
# d can only be in one place in unit; assign it there
if not assign(values, dplaces[0], d):
return False
# d can only be in one place in unit; assign it there
elif len(dplaces) == 1 and not assign(values, dplaces[0], d):
return False
return values


Expand Down
7 changes: 4 additions & 3 deletions data_structures/stacks/balanced_parentheses.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ def balanced_parentheses(parentheses: str) -> bool:
for bracket in parentheses:
if bracket in bracket_pairs:
stack.push(bracket)
elif bracket in (")", "]", "}"):
if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:
return False
elif bracket in (")", "]", "}") and (
stack.is_empty() or bracket_pairs[stack.pop()] != bracket
):
return False
return stack.is_empty()


Expand Down
20 changes: 13 additions & 7 deletions graphs/a_star.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,19 @@ def search(
for i in range(len(DIRECTIONS)): # to try out different valid actions
x2 = x + DIRECTIONS[i][0]
y2 = y + DIRECTIONS[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
f2 = g2 + heuristic[x2][y2]
cell.append([f2, g2, x2, y2])
closed[x2][y2] = 1
action[x2][y2] = i
if (
x2 >= 0
and x2 < len(grid)
and y2 >= 0
and y2 < len(grid[0])
and closed[x2][y2] == 0
and grid[x2][y2] == 0
):
g2 = g + cost
f2 = g2 + heuristic[x2][y2]
cell.append([f2, g2, x2, y2])
closed[x2][y2] = 1
action[x2][y2] = i
invpath = []
x = goal[0]
y = goal[1]
Expand Down
8 changes: 5 additions & 3 deletions graphs/bi_directional_dijkstra.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ def pass_and_relaxation(
queue.put((new_cost_f, nxt))
cst_fwd[nxt] = new_cost_f
parent[nxt] = v
if nxt in visited_backward:
if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance:
shortest_distance = cst_fwd[v] + d + cst_bwd[nxt]
if (
nxt in visited_backward
and cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance
):
shortest_distance = cst_fwd[v] + d + cst_bwd[nxt]
return shortest_distance


Expand Down
7 changes: 3 additions & 4 deletions other/davis_putnam_logemann_loveland.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,9 @@ def assign(self, model: dict[str, bool | None]) -> None:
value = model[symbol]
else:
continue
if value is not None:
# Complement assignment if literal is in complemented form
if literal.endswith("'"):
value = not value
# Complement assignment if literal is in complemented form
if value is not None and literal.endswith("'"):
value = not value
self.literals[literal] = value

def evaluate(self, model: dict[str, bool | None]) -> bool | None:
Expand Down
10 changes: 7 additions & 3 deletions project_euler/problem_033/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,13 @@ def fraction_list(digit_len: int) -> list[str]:
last_digit = int("1" + "0" * digit_len)
for num in range(den, last_digit):
while den <= 99:
if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
if is_digit_cancelling(num, den):
solutions.append(f"{num}/{den}")
if (
(num != den)
and (num % 10 == den // 10)
and (den % 10 != 0)
and is_digit_cancelling(num, den)
):
solutions.append(f"{num}/{den}")
den += 1
num += 1
den = 10
Expand Down
7 changes: 4 additions & 3 deletions project_euler/problem_037/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,10 @@ def validate(n: int) -> bool:
>>> validate(3797)
True
"""
if len(str(n)) > 3:
if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])):
return False
if len(str(n)) > 3 and (
not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3]))
):
return False
return True


Expand Down
9 changes: 5 additions & 4 deletions project_euler/problem_107/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,11 @@ def prims_algorithm(self) -> Graph:
while len(subgraph.vertices) < len(self.vertices):
min_weight = max(self.edges.values()) + 1
for edge, weight in self.edges.items():
if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices):
if weight < min_weight:
min_edge = edge
min_weight = weight
if (edge[0] in subgraph.vertices) ^ (
edge[1] in subgraph.vertices
) and weight < min_weight:
min_edge = edge
min_weight = weight

subgraph.add_edge(min_edge, min_weight)

Expand Down
8 changes: 5 additions & 3 deletions project_euler/problem_207/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,11 @@ def solution(max_proportion: float = 1 / 12345) -> int:
total_partitions += 1
if check_partition_perfect(partition_candidate):
perfect_partitions += 1
if perfect_partitions > 0:
if perfect_partitions / total_partitions < max_proportion:
return int(partition_candidate)
if (
perfect_partitions > 0
and perfect_partitions / total_partitions < max_proportion
):
return int(partition_candidate)
integer += 1


Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ lint.ignore = [ # `ruff rule S101` for a description of that rule
"S105", # Possible hardcoded password: 'password'
"S113", # Probable use of requests call without timeout -- FIX ME
"S311", # Standard pseudo-random generators are not suitable for cryptographic purposes -- FIX ME
"SIM102", # Use a single `if` statement instead of nested `if` statements -- FIX ME
"SLF001", # Private member accessed: `_Iterator` -- FIX ME
"UP038", # Use `X | Y` in `{}` call instead of `(X, Y)` -- DO NOT FIX
]
Expand Down
13 changes: 8 additions & 5 deletions scheduling/shortest_job_first.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,14 @@ def calculate_waitingtime(
# Process until all processes are completed
while complete != no_of_processes:
for j in range(no_of_processes):
if arrival_time[j] <= increment_time and remaining_time[j] > 0:
if remaining_time[j] < minm:
minm = remaining_time[j]
short = j
check = True
if (
arrival_time[j] <= increment_time
and remaining_time[j] > 0
and remaining_time[j] < minm
):
minm = remaining_time[j]
short = j
check = True

if not check:
increment_time += 1
Expand Down
11 changes: 7 additions & 4 deletions scripts/validate_solutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,13 @@ def added_solution_file_path() -> list[pathlib.Path]:


def collect_solution_file_paths() -> list[pathlib.Path]:
if os.environ.get("CI") and os.environ.get("GITHUB_EVENT_NAME") == "pull_request":
# Return only if there are any, otherwise default to all solutions
if filepaths := added_solution_file_path():
return filepaths
# Return only if there are any, otherwise default to all solutions
if (
os.environ.get("CI")
and os.environ.get("GITHUB_EVENT_NAME") == "pull_request"
and (filepaths := added_solution_file_path())
):
return filepaths
return all_solution_file_paths()


Expand Down
15 changes: 9 additions & 6 deletions web_programming/emails_from_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,15 @@ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in urls.
if value not in self.urls:
url = parse.urljoin(self.domain, value)
self.urls.append(url)
# If href is defined, not empty nor # print it and not already in urls.
if (
name == "href"
and value != "#"
and value != ""
and value not in self.urls
):
url = parse.urljoin(self.domain, value)
self.urls.append(url)


# Get main domain name (example.com)
Expand Down

0 comments on commit 93fb555

Please sign in to comment.