Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make some ruff fixes #8154

Merged
merged 4 commits into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion audio_filters/iir_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None
>>> filt.set_coefficients(a_coeffs, b_coeffs)
"""
if len(a_coeffs) < self.order:
a_coeffs = [1.0] + a_coeffs
a_coeffs = [1.0, *a_coeffs]

if len(a_coeffs) != self.order + 1:
raise ValueError(
Expand Down
6 changes: 3 additions & 3 deletions backtracking/n_queens_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,9 @@ def depth_first_search(

# If it is False we call dfs function again and we update the inputs
depth_first_search(
possible_board + [col],
diagonal_right_collisions + [row - col],
diagonal_left_collisions + [row + col],
[*possible_board, col],
[*diagonal_right_collisions, row - col],
[*diagonal_left_collisions, row + col],
boards,
n,
)
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sum_of_subsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def create_state_space_tree(
nums,
max_sum,
index + 1,
path + [nums[index]],
[*path, nums[index]],
result,
remaining_nums_sum - nums[index],
)
Expand Down
2 changes: 1 addition & 1 deletion ciphers/bifid.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def letter_to_numbers(self, letter: str) -> np.ndarray:
>>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5])
True
"""
index1, index2 = np.where(self.SQUARE == letter)
index1, index2 = np.where(letter == self.SQUARE)
indexes = np.concatenate([index1 + 1, index2 + 1])
return indexes

Expand Down
16 changes: 8 additions & 8 deletions ciphers/diffie_hellman.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,10 @@ def generate_public_key(self) -> str:

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

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

@staticmethod
def generate_shared_key_static(
Expand Down
2 changes: 1 addition & 1 deletion ciphers/polybius.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def letter_to_numbers(self, letter: str) -> np.ndarray:
>>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5])
True
"""
index1, index2 = np.where(self.SQUARE == letter)
index1, index2 = np.where(letter == self.SQUARE)
indexes = np.concatenate([index1 + 1, index2 + 1])
return indexes

Expand Down
18 changes: 8 additions & 10 deletions ciphers/xor_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,10 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
assert isinstance(file, str) and isinstance(key, int)

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

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

try:
with open(file) as fin:
with open("decrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.decrypt_string(line, key))
with open(file) as fin, open("decrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.decrypt_string(line, key))

except OSError:
return False
Expand Down
2 changes: 1 addition & 1 deletion computer_vision/mosaic_augmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def update_image_and_anno(
new_anno.append([bbox[0], xmin, ymin, xmax, ymax])

# Remove bounding box small than scale of filter
if 0 < filter_scale:
if filter_scale > 0:
new_anno = [
anno
for anno in new_anno
Expand Down
2 changes: 1 addition & 1 deletion data_structures/binary_tree/binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __insert(self, value) -> None:
else: # Tree is not empty
parent_node = self.root # from root
if parent_node is None:
return None
return
while True: # While we don't get to a leaf
if value < parent_node.value: # We go left
if parent_node.left is None:
Expand Down
4 changes: 2 additions & 2 deletions data_structures/binary_tree/binary_tree_traversals.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def preorder(root: Node | None) -> list[int]:
>>> preorder(make_tree())
[1, 2, 4, 5, 3]
"""
return [root.data] + preorder(root.left) + preorder(root.right) if root else []
return [root.data, *preorder(root.left), *preorder(root.right)] if root else []


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


def height(root: Node | None) -> int:
Expand Down
2 changes: 1 addition & 1 deletion data_structures/binary_tree/inorder_tree_traversal_2022.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return
"""
if node:
inorder_array = inorder(node.left_child)
inorder_array = inorder_array + [node.data]
inorder_array = [*inorder_array, node.data]
inorder_array = inorder_array + inorder(node.right_child)
else:
inorder_array = []
Expand Down
5 changes: 2 additions & 3 deletions data_structures/binary_tree/red_black_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,8 @@ def check_coloring(self) -> bool:
"""A helper function to recursively check Property 4 of a
Red-Black Tree. See check_color_properties for more info.
"""
if self.color == 1:
if color(self.left) == 1 or color(self.right) == 1:
return False
if self.color == 1 and 1 in (color(self.left), color(self.right)):
return False
if self.left and not self.left.check_coloring():
return False
if self.right and not self.right.check_coloring():
Expand Down
2 changes: 1 addition & 1 deletion data_structures/hashing/number_theory/prime_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def next_prime(value, factor=1, **kwargs):
first_value_val = value

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

if value == first_value_val:
return next_prime(value + 1, **kwargs)
Expand Down
4 changes: 2 additions & 2 deletions data_structures/heap/binomial_heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,12 @@ def merge_heaps(self, other):

# Empty heaps corner cases
if other.size == 0:
return
return None
if self.size == 0:
self.size = other.size
self.bottom_root = other.bottom_root
self.min_node = other.min_node
return
return None
# Update size
self.size = self.size + other.size

Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/doubly_linked_list_two.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def insert_at_position(self, position: int, value: int) -> None:
while node:
if current_position == position:
self.insert_before_node(node, new_node)
return None
return
current_position += 1
node = node.next
self.insert_after_node(self.tail, new_node)
Expand Down
1 change: 1 addition & 0 deletions data_structures/linked_list/singly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def __getitem__(self, index: int) -> Any:
for i, node in enumerate(self):
if i == index:
return node
return None

# Used to change the data of a particular node
def __setitem__(self, index: int, data: Any) -> None:
Expand Down
5 changes: 1 addition & 4 deletions data_structures/linked_list/skip_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,10 +388,7 @@ def traverse_keys(node):

def test_iter_always_yields_sorted_values():
def is_sorted(lst):
for item, next_item in zip(lst, lst[1:]):
if next_item < item:
return False
return True
return all(next_item >= item for item, next_item in zip(lst, lst[1:]))

skip_list = SkipList()
for i in range(10):
Expand Down
2 changes: 1 addition & 1 deletion data_structures/queue/circular_queue_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def dequeue(self) -> Any:
"""
self.check_can_perform_operation()
if self.rear is None or self.front is None:
return
return None
if self.front == self.rear:
data = self.front.data
self.front.data = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def gray2binary(gray: np.array) -> np.array:
[False, True, False],
[False, True, False]])
"""
return (127 < gray) & (gray <= 255)
return (gray > 127) & (gray <= 255)


def dilation(image: np.array, kernel: np.array) -> np.array:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def gray2binary(gray: np.array) -> np.array:
[False, True, False],
[False, True, False]])
"""
return (127 < gray) & (gray <= 255)
return (gray > 127) & (gray <= 255)


def erosion(image: np.array, kernel: np.array) -> np.array:
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/all_construct.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[
# slice condition
if target[i : i + len(word)] == word:
new_combinations: list[list[str]] = [
[word] + way for way in table[i]
[word, *way] for way in table[i]
]
# adds the word to every combination the current position holds
# now,push that combination to the table[i+len(word)]
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/fizz_buzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def fizz_buzz(number: int, iterations: int) -> str:
out += "Fizz"
if number % 5 == 0:
out += "Buzz"
if not number % 3 == 0 and not number % 5 == 0:
if 0 not in (number % 3, number % 5):
out += str(number)

# print(out)
Expand Down
10 changes: 2 additions & 8 deletions dynamic_programming/longest_common_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,14 @@ def longest_common_subsequence(x: str, y: str):

for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
match = 1
else:
match = 0
match = 1 if x[i - 1] == y[j - 1] else 0

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

seq = ""
i, j = m, n
while i > 0 and j > 0:
if x[i - 1] == y[j - 1]:
match = 1
else:
match = 0
match = 1 if x[i - 1] == y[j - 1] else 0

if l[i][j] == l[i - 1][j - 1] + match:
if match == 1:
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/longest_increasing_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
i += 1

temp_array = [element for element in array[1:] if element >= pivot]
temp_array = [pivot] + longest_subsequence(temp_array)
temp_array = [pivot, *longest_subsequence(temp_array)]
if len(temp_array) > len(longest_subseq):
return temp_array
else:
Expand Down
14 changes: 6 additions & 8 deletions graphs/basic_graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,9 @@ def dijk(g, s):
u = i
known.add(u)
for v in g[u]:
if v[0] not in known:
if dist[u] + v[1] < dist.get(v[0], 100000):
dist[v[0]] = dist[u] + v[1]
path[v[0]] = u
if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000):
dist[v[0]] = dist[u] + v[1]
path[v[0]] = u
for i in dist:
if i != s:
print(dist[i])
Expand Down Expand Up @@ -243,10 +242,9 @@ def prim(g, s):
u = i
known.add(u)
for v in g[u]:
if v[0] not in known:
if v[1] < dist.get(v[0], 100000):
dist[v[0]] = v[1]
path[v[0]] = u
if v[0] not in known and v[1] < dist.get(v[0], 100000):
dist[v[0]] = v[1]
path[v[0]] = u
return dist


Expand Down
9 changes: 4 additions & 5 deletions graphs/check_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ def check_cycle(graph: dict) -> bool:
visited: set[int] = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
rec_stk: set[int] = set()
for node in graph:
if node not in visited:
if depth_first_search(graph, node, visited, rec_stk):
return True
return False
return any(
node not in visited and depth_first_search(graph, node, visited, rec_stk)
for node in graph
)


def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion graphs/connected_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def dfs(graph: dict, vert: int, visited: list) -> list:
if not visited[neighbour]:
connected_verts += dfs(graph, neighbour, visited)

return [vert] + connected_verts
return [vert, *connected_verts]


def connected_components(graph: dict) -> list:
Expand Down
2 changes: 1 addition & 1 deletion graphs/dijkstra_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def dijkstra(self, src):
self.dist[src] = 0
q = PriorityQueue()
q.insert((0, src)) # (dist from src, node)
for u in self.adjList.keys():
for u in self.adjList:
if u != src:
self.dist[u] = sys.maxsize # Infinity
self.par[u] = -1
Expand Down
5 changes: 2 additions & 3 deletions graphs/edmonds_karp_multiple_source_and_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,8 @@ def relabel(self, vertex_index):
self.graph[vertex_index][to_index]
- self.preflow[vertex_index][to_index]
> 0
):
if min_height is None or self.heights[to_index] < min_height:
min_height = self.heights[to_index]
) and (min_height is None or self.heights[to_index] < min_height):
min_height = self.heights[to_index]

if min_height is not None:
self.heights[vertex_index] = min_height + 1
Expand Down
6 changes: 3 additions & 3 deletions graphs/frequent_pattern_graph_miner.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,11 @@ def create_edge(nodes, graph, cluster, c1):
"""
create edge between the nodes
"""
for i in cluster[c1].keys():
for i in cluster[c1]:
count = 0
c2 = c1 + 1
while c2 < max(cluster.keys()):
for j in cluster[c2].keys():
for j in cluster[c2]:
"""
creates edge only if the condition satisfies
"""
Expand Down Expand Up @@ -185,7 +185,7 @@ def find_freq_subgraph_given_support(s, cluster, graph):
find edges of multiple frequent subgraphs
"""
k = int(s / 100 * (len(cluster) - 1))
for i in cluster[k].keys():
for i in cluster[k]:
my_dfs(graph, tuple(cluster[k][i]), (["Header"],))


Expand Down
Loading