Make some ruff fixes (#8154)

* Make some ruff fixes

* Undo manual fix

* Undo manual fix

* Updates from ruff=0.0.251
This commit is contained in:
Christian Clauss 2023-03-01 17:23:33 +01:00 committed by GitHub
parent 1c15cdff70
commit 64543faa98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
73 changed files with 151 additions and 203 deletions

View File

@ -47,7 +47,7 @@ class IIRFilter:
>>> filt.set_coefficients(a_coeffs, b_coeffs) >>> filt.set_coefficients(a_coeffs, b_coeffs)
""" """
if len(a_coeffs) < self.order: 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: if len(a_coeffs) != self.order + 1:
raise ValueError( raise ValueError(

View File

@ -129,9 +129,9 @@ def depth_first_search(
# If it is False we call dfs function again and we update the inputs # If it is False we call dfs function again and we update the inputs
depth_first_search( depth_first_search(
possible_board + [col], [*possible_board, col],
diagonal_right_collisions + [row - col], [*diagonal_right_collisions, row - col],
diagonal_left_collisions + [row + col], [*diagonal_left_collisions, row + col],
boards, boards,
n, n,
) )

View File

@ -44,7 +44,7 @@ def create_state_space_tree(
nums, nums,
max_sum, max_sum,
index + 1, index + 1,
path + [nums[index]], [*path, nums[index]],
result, result,
remaining_nums_sum - nums[index], remaining_nums_sum - nums[index],
) )

View File

@ -33,7 +33,7 @@ class BifidCipher:
>>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5]) >>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5])
True True
""" """
index1, index2 = np.where(self.SQUARE == letter) index1, index2 = np.where(letter == self.SQUARE)
indexes = np.concatenate([index1 + 1, index2 + 1]) indexes = np.concatenate([index1 + 1, index2 + 1])
return indexes return indexes

View File

@ -228,10 +228,10 @@ class DiffieHellman:
def is_valid_public_key(self, key: int) -> bool: def is_valid_public_key(self, key: int) -> bool:
# check if the other public key is valid based on NIST SP800-56 # check if the other public key is valid based on NIST SP800-56
if 2 <= key and key <= self.prime - 2: return (
if pow(key, (self.prime - 1) // 2, self.prime) == 1: 2 <= key <= self.prime - 2
return True and pow(key, (self.prime - 1) // 2, self.prime) == 1
return False )
def generate_shared_key(self, other_key_str: str) -> str: def generate_shared_key(self, other_key_str: str) -> str:
other_key = int(other_key_str, base=16) other_key = int(other_key_str, base=16)
@ -243,10 +243,10 @@ class DiffieHellman:
@staticmethod @staticmethod
def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool: 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 # 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: return (
if pow(remote_public_key_str, (prime - 1) // 2, prime) == 1: 2 <= remote_public_key_str <= prime - 2
return True and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1
return False )
@staticmethod @staticmethod
def generate_shared_key_static( def generate_shared_key_static(

View File

@ -31,7 +31,7 @@ class PolybiusCipher:
>>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5]) >>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5])
True True
""" """
index1, index2 = np.where(self.SQUARE == letter) index1, index2 = np.where(letter == self.SQUARE)
indexes = np.concatenate([index1 + 1, index2 + 1]) indexes = np.concatenate([index1 + 1, index2 + 1])
return indexes return indexes

View File

@ -128,11 +128,10 @@ class XORCipher:
assert isinstance(file, str) and isinstance(key, int) assert isinstance(file, str) and isinstance(key, int)
try: try:
with open(file) as fin: with open(file) as fin, open("encrypt.out", "w+") as fout:
with open("encrypt.out", "w+") as fout: # actual encrypt-process
# actual encrypt-process for line in fin:
for line in fin: fout.write(self.encrypt_string(line, key))
fout.write(self.encrypt_string(line, key))
except OSError: except OSError:
return False return False
@ -152,11 +151,10 @@ class XORCipher:
assert isinstance(file, str) and isinstance(key, int) assert isinstance(file, str) and isinstance(key, int)
try: try:
with open(file) as fin: with open(file) as fin, open("decrypt.out", "w+") as fout:
with open("decrypt.out", "w+") as fout: # actual encrypt-process
# actual encrypt-process for line in fin:
for line in fin: fout.write(self.decrypt_string(line, key))
fout.write(self.decrypt_string(line, key))
except OSError: except OSError:
return False return False

View File

@ -159,7 +159,7 @@ def update_image_and_anno(
new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) new_anno.append([bbox[0], xmin, ymin, xmax, ymax])
# Remove bounding box small than scale of filter # Remove bounding box small than scale of filter
if 0 < filter_scale: if filter_scale > 0:
new_anno = [ new_anno = [
anno anno
for anno in new_anno for anno in new_anno

View File

@ -60,7 +60,7 @@ class BinarySearchTree:
else: # Tree is not empty else: # Tree is not empty
parent_node = self.root # from root parent_node = self.root # from root
if parent_node is None: if parent_node is None:
return None return
while True: # While we don't get to a leaf while True: # While we don't get to a leaf
if value < parent_node.value: # We go left if value < parent_node.value: # We go left
if parent_node.left is None: if parent_node.left is None:

View File

@ -37,7 +37,7 @@ def preorder(root: Node | None) -> list[int]:
>>> preorder(make_tree()) >>> preorder(make_tree())
[1, 2, 4, 5, 3] [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]: def postorder(root: Node | None) -> list[int]:
@ -55,7 +55,7 @@ def inorder(root: Node | None) -> list[int]:
>>> inorder(make_tree()) >>> inorder(make_tree())
[4, 2, 5, 1, 3] [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: def height(root: Node | None) -> int:

View File

@ -50,7 +50,7 @@ def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return
""" """
if node: if node:
inorder_array = inorder(node.left_child) 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) inorder_array = inorder_array + inorder(node.right_child)
else: else:
inorder_array = [] inorder_array = []

View File

@ -319,9 +319,8 @@ class RedBlackTree:
"""A helper function to recursively check Property 4 of a """A helper function to recursively check Property 4 of a
Red-Black Tree. See check_color_properties for more info. Red-Black Tree. See check_color_properties for more info.
""" """
if self.color == 1: if self.color == 1 and 1 in (color(self.left), color(self.right)):
if color(self.left) == 1 or color(self.right) == 1: return False
return False
if self.left and not self.left.check_coloring(): if self.left and not self.left.check_coloring():
return False return False
if self.right and not self.right.check_coloring(): if self.right and not self.right.check_coloring():

View File

@ -52,7 +52,7 @@ def next_prime(value, factor=1, **kwargs):
first_value_val = value first_value_val = value
while not is_prime(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: if value == first_value_val:
return next_prime(value + 1, **kwargs) return next_prime(value + 1, **kwargs)

View File

@ -136,12 +136,12 @@ class BinomialHeap:
# Empty heaps corner cases # Empty heaps corner cases
if other.size == 0: if other.size == 0:
return return None
if self.size == 0: if self.size == 0:
self.size = other.size self.size = other.size
self.bottom_root = other.bottom_root self.bottom_root = other.bottom_root
self.min_node = other.min_node self.min_node = other.min_node
return return None
# Update size # Update size
self.size = self.size + other.size self.size = self.size + other.size

View File

@ -128,7 +128,7 @@ class LinkedList:
while node: while node:
if current_position == position: if current_position == position:
self.insert_before_node(node, new_node) self.insert_before_node(node, new_node)
return None return
current_position += 1 current_position += 1
node = node.next node = node.next
self.insert_after_node(self.tail, new_node) self.insert_after_node(self.tail, new_node)

View File

@ -107,6 +107,7 @@ class LinkedList:
for i, node in enumerate(self): for i, node in enumerate(self):
if i == index: if i == index:
return node return node
return None
# Used to change the data of a particular node # Used to change the data of a particular node
def __setitem__(self, index: int, data: Any) -> None: def __setitem__(self, index: int, data: Any) -> None:

View File

@ -388,10 +388,7 @@ def test_delete_doesnt_leave_dead_nodes():
def test_iter_always_yields_sorted_values(): def test_iter_always_yields_sorted_values():
def is_sorted(lst): def is_sorted(lst):
for item, next_item in zip(lst, lst[1:]): return all(next_item >= item for item, next_item in zip(lst, lst[1:]))
if next_item < item:
return False
return True
skip_list = SkipList() skip_list = SkipList()
for i in range(10): for i in range(10):

View File

@ -127,7 +127,7 @@ class CircularQueueLinkedList:
""" """
self.check_can_perform_operation() self.check_can_perform_operation()
if self.rear is None or self.front is None: if self.rear is None or self.front is None:
return return None
if self.front == self.rear: if self.front == self.rear:
data = self.front.data data = self.front.data
self.front.data = None self.front.data = None

View File

@ -32,7 +32,7 @@ def gray2binary(gray: np.array) -> np.array:
[False, True, False], [False, True, False],
[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: def dilation(image: np.array, kernel: np.array) -> np.array:

View File

@ -32,7 +32,7 @@ def gray2binary(gray: np.array) -> np.array:
[False, True, False], [False, True, False],
[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: def erosion(image: np.array, kernel: np.array) -> np.array:

View File

@ -34,7 +34,7 @@ def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[
# slice condition # slice condition
if target[i : i + len(word)] == word: if target[i : i + len(word)] == word:
new_combinations: list[list[str]] = [ 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 # adds the word to every combination the current position holds
# now,push that combination to the table[i+len(word)] # now,push that combination to the table[i+len(word)]

View File

@ -49,7 +49,7 @@ def fizz_buzz(number: int, iterations: int) -> str:
out += "Fizz" out += "Fizz"
if number % 5 == 0: if number % 5 == 0:
out += "Buzz" out += "Buzz"
if not number % 3 == 0 and not number % 5 == 0: if 0 not in (number % 3, number % 5):
out += str(number) out += str(number)
# print(out) # print(out)

View File

@ -42,20 +42,14 @@ def longest_common_subsequence(x: str, y: str):
for i in range(1, m + 1): for i in range(1, m + 1):
for j in range(1, n + 1): for j in range(1, n + 1):
if x[i - 1] == y[j - 1]: match = 1 if x[i - 1] == y[j - 1] else 0
match = 1
else:
match = 0
l[i][j] = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match) l[i][j] = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match)
seq = "" seq = ""
i, j = m, n i, j = m, n
while i > 0 and j > 0: while i > 0 and j > 0:
if x[i - 1] == y[j - 1]: match = 1 if x[i - 1] == y[j - 1] else 0
match = 1
else:
match = 0
if l[i][j] == l[i - 1][j - 1] + match: if l[i][j] == l[i - 1][j - 1] + match:
if match == 1: if match == 1:

View File

@ -48,7 +48,7 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
i += 1 i += 1
temp_array = [element for element in array[1:] if element >= pivot] 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): if len(temp_array) > len(longest_subseq):
return temp_array return temp_array
else: else:

View File

@ -139,10 +139,9 @@ def dijk(g, s):
u = i u = i
known.add(u) known.add(u)
for v in g[u]: for v in g[u]:
if v[0] not in known: if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000):
if dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1]
dist[v[0]] = dist[u] + v[1] path[v[0]] = u
path[v[0]] = u
for i in dist: for i in dist:
if i != s: if i != s:
print(dist[i]) print(dist[i])
@ -243,10 +242,9 @@ def prim(g, s):
u = i u = i
known.add(u) known.add(u)
for v in g[u]: for v in g[u]:
if v[0] not in known: if v[0] not in known and v[1] < dist.get(v[0], 100000):
if v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1]
dist[v[0]] = v[1] path[v[0]] = u
path[v[0]] = u
return dist return dist

View File

@ -15,11 +15,10 @@ def check_cycle(graph: dict) -> bool:
visited: set[int] = set() visited: set[int] = set()
# To detect a back edge, keep track of vertices currently in the recursion stack # To detect a back edge, keep track of vertices currently in the recursion stack
rec_stk: set[int] = set() rec_stk: set[int] = set()
for node in graph: return any(
if node not in visited: node not in visited and depth_first_search(graph, node, visited, rec_stk)
if depth_first_search(graph, node, visited, rec_stk): for node in graph
return True )
return False
def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool: def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool:

View File

@ -27,7 +27,7 @@ def dfs(graph: dict, vert: int, visited: list) -> list:
if not visited[neighbour]: if not visited[neighbour]:
connected_verts += dfs(graph, neighbour, visited) connected_verts += dfs(graph, neighbour, visited)
return [vert] + connected_verts return [vert, *connected_verts]
def connected_components(graph: dict) -> list: def connected_components(graph: dict) -> list:

View File

@ -112,7 +112,7 @@ class Graph:
self.dist[src] = 0 self.dist[src] = 0
q = PriorityQueue() q = PriorityQueue()
q.insert((0, src)) # (dist from src, node) q.insert((0, src)) # (dist from src, node)
for u in self.adjList.keys(): for u in self.adjList:
if u != src: if u != src:
self.dist[u] = sys.maxsize # Infinity self.dist[u] = sys.maxsize # Infinity
self.par[u] = -1 self.par[u] = -1

View File

@ -163,9 +163,8 @@ class PushRelabelExecutor(MaximumFlowAlgorithmExecutor):
self.graph[vertex_index][to_index] self.graph[vertex_index][to_index]
- self.preflow[vertex_index][to_index] - self.preflow[vertex_index][to_index]
> 0 > 0
): ) and (min_height is None or self.heights[to_index] < min_height):
if min_height is None or self.heights[to_index] < min_height: min_height = self.heights[to_index]
min_height = self.heights[to_index]
if min_height is not None: if min_height is not None:
self.heights[vertex_index] = min_height + 1 self.heights[vertex_index] = min_height + 1

View File

@ -130,11 +130,11 @@ def create_edge(nodes, graph, cluster, c1):
""" """
create edge between the nodes create edge between the nodes
""" """
for i in cluster[c1].keys(): for i in cluster[c1]:
count = 0 count = 0
c2 = c1 + 1 c2 = c1 + 1
while c2 < max(cluster.keys()): while c2 < max(cluster.keys()):
for j in cluster[c2].keys(): for j in cluster[c2]:
""" """
creates edge only if the condition satisfies creates edge only if the condition satisfies
""" """
@ -185,7 +185,7 @@ def find_freq_subgraph_given_support(s, cluster, graph):
find edges of multiple frequent subgraphs find edges of multiple frequent subgraphs
""" """
k = int(s / 100 * (len(cluster) - 1)) 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"],)) my_dfs(graph, tuple(cluster[k][i]), (["Header"],))

View File

@ -144,6 +144,7 @@ class Graph:
self.rank[root1] += 1 self.rank[root1] += 1
self.parent[root2] = root1 self.parent[root2] = root1
return root1 return root1
return None
@staticmethod @staticmethod
def boruvka_mst(graph): def boruvka_mst(graph):

View File

@ -44,10 +44,7 @@ class Heap:
temp = position[index] temp = position[index]
while index != 0: while index != 0:
if index % 2 == 0: parent = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
parent = int((index - 2) / 2)
else:
parent = int((index - 1) / 2)
if val < heap[parent]: if val < heap[parent]:
heap[index] = heap[parent] heap[index] = heap[parent]

View File

@ -135,14 +135,14 @@ class MinPriorityQueue(Generic[T]):
# only] # only]
curr_pos = self.position_map[elem] curr_pos = self.position_map[elem]
if curr_pos == 0: if curr_pos == 0:
return return None
parent_position = get_parent_position(curr_pos) parent_position = get_parent_position(curr_pos)
_, weight = self.heap[curr_pos] _, weight = self.heap[curr_pos]
_, parent_weight = self.heap[parent_position] _, parent_weight = self.heap[parent_position]
if parent_weight > weight: if parent_weight > weight:
self._swap_nodes(parent_position, curr_pos) self._swap_nodes(parent_position, curr_pos)
return self._bubble_up(elem) return self._bubble_up(elem)
return return None
def _bubble_down(self, elem: T) -> None: def _bubble_down(self, elem: T) -> None:
# Place a node at the proper position (downward movement) [to be used # Place a node at the proper position (downward movement) [to be used
@ -154,24 +154,22 @@ class MinPriorityQueue(Generic[T]):
if child_left_position < self.elements and child_right_position < self.elements: if child_left_position < self.elements and child_right_position < self.elements:
_, child_left_weight = self.heap[child_left_position] _, child_left_weight = self.heap[child_left_position]
_, child_right_weight = self.heap[child_right_position] _, child_right_weight = self.heap[child_right_position]
if child_right_weight < child_left_weight: if child_right_weight < child_left_weight and child_right_weight < weight:
if child_right_weight < weight: self._swap_nodes(child_right_position, curr_pos)
self._swap_nodes(child_right_position, curr_pos) return self._bubble_down(elem)
return self._bubble_down(elem)
if child_left_position < self.elements: if child_left_position < self.elements:
_, child_left_weight = self.heap[child_left_position] _, child_left_weight = self.heap[child_left_position]
if child_left_weight < weight: if child_left_weight < weight:
self._swap_nodes(child_left_position, curr_pos) self._swap_nodes(child_left_position, curr_pos)
return self._bubble_down(elem) return self._bubble_down(elem)
else: else:
return return None
if child_right_position < self.elements: if child_right_position < self.elements:
_, child_right_weight = self.heap[child_right_position] _, child_right_weight = self.heap[child_right_position]
if child_right_weight < weight: if child_right_weight < weight:
self._swap_nodes(child_right_position, curr_pos) self._swap_nodes(child_right_position, curr_pos)
return self._bubble_down(elem) return self._bubble_down(elem)
else: return None
return
def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None: def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None:
# Swap the nodes at the given positions # Swap the nodes at the given positions

View File

@ -126,9 +126,8 @@ def emitter_converter(size_par, data):
aux = (bin_pos[cont_loop])[-1 * (bp)] aux = (bin_pos[cont_loop])[-1 * (bp)]
except IndexError: except IndexError:
aux = "0" aux = "0"
if aux == "1": if aux == "1" and x == "1":
if x == "1": cont_bo += 1
cont_bo += 1
cont_loop += 1 cont_loop += 1
parity.append(cont_bo % 2) parity.append(cont_bo % 2)

View File

@ -108,7 +108,7 @@ class Vector:
mul implements the scalar multiplication mul implements the scalar multiplication
and the dot-product and the dot-product
""" """
if isinstance(other, float) or isinstance(other, int): if isinstance(other, (float, int)):
ans = [c * other for c in self.__components] ans = [c * other for c in self.__components]
return Vector(ans) return Vector(ans)
elif isinstance(other, Vector) and len(self) == len(other): elif isinstance(other, Vector) and len(self) == len(other):
@ -216,7 +216,7 @@ def axpy(scalar: float, x: Vector, y: Vector) -> Vector:
assert ( assert (
isinstance(x, Vector) isinstance(x, Vector)
and isinstance(y, Vector) and isinstance(y, Vector)
and (isinstance(scalar, int) or isinstance(scalar, float)) and (isinstance(scalar, (int, float)))
) )
return x * scalar + y return x * scalar + y
@ -337,12 +337,13 @@ class Matrix:
"vector must have the same size as the " "vector must have the same size as the "
"number of columns of the matrix!" "number of columns of the matrix!"
) )
elif isinstance(other, int) or isinstance(other, float): # matrix-scalar elif isinstance(other, (int, float)): # matrix-scalar
matrix = [ matrix = [
[self.__matrix[i][j] * other for j in range(self.__width)] [self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height) for i in range(self.__height)
] ]
return Matrix(matrix, self.__width, self.__height) return Matrix(matrix, self.__width, self.__height)
return None
def height(self) -> int: def height(self) -> int:
""" """

View File

@ -55,6 +55,7 @@ def output(example_no, data_set):
return train_data[example_no][1] return train_data[example_no][1]
elif data_set == "test": elif data_set == "test":
return test_data[example_no][1] return test_data[example_no][1]
return None
def calculate_hypothesis_value(example_no, data_set): def calculate_hypothesis_value(example_no, data_set):
@ -68,6 +69,7 @@ def calculate_hypothesis_value(example_no, data_set):
return _hypothesis_value(train_data[example_no][0]) return _hypothesis_value(train_data[example_no][0])
elif data_set == "test": elif data_set == "test":
return _hypothesis_value(test_data[example_no][0]) return _hypothesis_value(test_data[example_no][0])
return None
def summation_of_cost_derivative(index, end=m): def summation_of_cost_derivative(index, end=m):

View File

@ -229,7 +229,7 @@ def report_generator(
""" """
# Fill missing values with given rules # Fill missing values with given rules
if fill_missing_report: if fill_missing_report:
df.fillna(value=fill_missing_report, inplace=True) df = df.fillna(value=fill_missing_report)
df["dummy"] = 1 df["dummy"] = 1
numeric_cols = df.select_dtypes(np.number).columns numeric_cols = df.select_dtypes(np.number).columns
report = ( report = (
@ -338,7 +338,7 @@ def report_generator(
) )
report.columns.name = "" report.columns.name = ""
report = report.reset_index() report = report.reset_index()
report.drop(columns=["index"], inplace=True) report = report.drop(columns=["index"])
return report return report

View File

@ -129,7 +129,7 @@ class SmoSVM:
# error # error
self._unbound = [i for i in self._all_samples if self._is_unbound(i)] self._unbound = [i for i in self._all_samples if self._is_unbound(i)]
for s in self.unbound: for s in self.unbound:
if s == i1 or s == i2: if s in (i1, i2):
continue continue
self._error[s] += ( self._error[s] += (
y1 * (a1_new - a1) * k(i1, s) y1 * (a1_new - a1) * k(i1, s)
@ -225,7 +225,7 @@ class SmoSVM:
def _choose_alphas(self): def _choose_alphas(self):
locis = yield from self._choose_a1() locis = yield from self._choose_a1()
if not locis: if not locis:
return return None
return locis return locis
def _choose_a1(self): def _choose_a1(self):
@ -423,9 +423,8 @@ class Kernel:
return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2)) return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2))
def _check(self): def _check(self):
if self._kernel == self._rbf: if self._kernel == self._rbf and self.gamma < 0:
if self.gamma < 0: raise ValueError("gamma value must greater than 0")
raise ValueError("gamma value must greater than 0")
def _get_kernel(self, kernel_name): def _get_kernel(self, kernel_name):
maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf} maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf}

View File

@ -75,9 +75,9 @@ def test_abs_val():
""" """
>>> test_abs_val() >>> test_abs_val()
""" """
assert 0 == abs_val(0) assert abs_val(0) == 0
assert 34 == abs_val(34) assert abs_val(34) == 34
assert 100000000000 == abs_val(-100000000000) assert abs_val(-100000000000) == 100000000000
a = [-3, -1, 2, -11] a = [-3, -1, 2, -11]
assert abs_max(a) == -11 assert abs_max(a) == -11

View File

@ -6,7 +6,7 @@ def bin_exp_mod(a, n, b):
7 7
""" """
# mod b # mod b
assert not (b == 0), "This cannot accept modulo that is == 0" assert b != 0, "This cannot accept modulo that is == 0"
if n == 0: if n == 0:
return 1 return 1

View File

@ -71,6 +71,7 @@ def jaccard_similarity(set_a, set_b, alternative_union=False):
return len(intersection) / len(union) return len(intersection) / len(union)
return len(intersection) / len(union) return len(intersection) / len(union)
return None
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -12,6 +12,7 @@ def res(x, y):
return 0 return 0
elif y == 0: elif y == 0:
return 1 # any number raised to 0 is 1 return 1 # any number raised to 0 is 1
raise AssertionError("This should never happen")
if __name__ == "__main__": # Main function if __name__ == "__main__": # Main function

View File

@ -80,10 +80,7 @@ class FFT:
# Discrete fourier transform of A and B # Discrete fourier transform of A and B
def __dft(self, which): def __dft(self, which):
if which == "A": dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
dft = [[x] for x in self.polyA]
else:
dft = [[x] for x in self.polyB]
# Corner case # Corner case
if len(dft) <= 1: if len(dft) <= 1:
return dft[0] return dft[0]

View File

@ -153,6 +153,7 @@ class BPNN:
if mse < self.accuracy: if mse < self.accuracy:
print("----达到精度----") print("----达到精度----")
return mse return mse
return None
def cal_loss(self, ydata, ydata_): def cal_loss(self, ydata, ydata_):
self.loss = np.sum(np.power((ydata - ydata_), 2)) self.loss = np.sum(np.power((ydata - ydata_), 2))

View File

@ -125,10 +125,9 @@ def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]:
miny = y miny = y
minx = x minx = x
minidx = i minidx = i
if y == miny: if y == miny and x < minx:
if x < minx: minx = x
minx = x minidx = i
minidx = i
# remove the lowest and the most left point from points for preparing for sort # remove the lowest and the most left point from points for preparing for sort
points.pop(minidx) points.pop(minidx)

View File

@ -24,11 +24,10 @@ def is_balanced(s):
if s[i] in open_brackets: if s[i] in open_brackets:
stack.append(s[i]) stack.append(s[i])
elif s[i] in closed_brackets: elif s[i] in closed_brackets and (
if len(stack) == 0 or ( len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != s[i])
len(stack) > 0 and open_to_closed[stack.pop()] != s[i] ):
): return False
return False
return len(stack) == 0 return len(stack) == 0

View File

@ -70,10 +70,10 @@ def hubble_parameter(
68.3 68.3
""" """
parameters = [redshift, radiation_density, matter_density, dark_energy] parameters = [redshift, radiation_density, matter_density, dark_energy]
if any(0 > p for p in parameters): if any(p < 0 for p in parameters):
raise ValueError("All input parameters must be positive") raise ValueError("All input parameters must be positive")
if any(1 < p for p in parameters[1:4]): if any(p > 1 for p in parameters[1:4]):
raise ValueError("Relative densities cannot be greater than one") raise ValueError("Relative densities cannot be greater than one")
else: else:
curvature = 1 - (matter_density + radiation_density + dark_energy) curvature = 1 - (matter_density + radiation_density + dark_energy)

View File

@ -63,6 +63,7 @@ def solution(n: int = 20) -> int:
if i == 0: if i == 0:
i = 1 i = 1
return i return i
return None
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -32,9 +32,8 @@ def solution() -> int:
for a in range(300): for a in range(300):
for b in range(a + 1, 400): for b in range(a + 1, 400):
for c in range(b + 1, 500): for c in range(b + 1, 500):
if (a + b + c) == 1000: if (a + b + c) == 1000 and (a**2) + (b**2) == (c**2):
if (a**2) + (b**2) == (c**2): return a * b * c
return a * b * c
return -1 return -1

View File

@ -34,10 +34,7 @@ def collatz_sequence_length(n: int) -> int:
"""Returns the Collatz sequence length for n.""" """Returns the Collatz sequence length for n."""
if n in COLLATZ_SEQUENCE_LENGTHS: if n in COLLATZ_SEQUENCE_LENGTHS:
return COLLATZ_SEQUENCE_LENGTHS[n] return COLLATZ_SEQUENCE_LENGTHS[n]
if n % 2 == 0: next_n = n // 2 if n % 2 == 0 else 3 * n + 1
next_n = n // 2
else:
next_n = 3 * n + 1
sequence_length = collatz_sequence_length(next_n) + 1 sequence_length = collatz_sequence_length(next_n) + 1
COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length
return sequence_length return sequence_length

View File

@ -48,14 +48,8 @@ def solution():
for i in range(1, len(a)): for i in range(1, len(a)):
for j in range(len(a[i])): for j in range(len(a[i])):
if j != len(a[i - 1]): number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
number1 = a[i - 1][j] number2 = a[i - 1][j - 1] if j > 0 else 0
else:
number1 = 0
if j > 0:
number2 = a[i - 1][j - 1]
else:
number2 = 0
a[i][j] += max(number1, number2) a[i][j] += max(number1, number2)
return max(a[-1]) return max(a[-1])

View File

@ -39,7 +39,7 @@ def solution():
while year < 2001: while year < 2001:
day += 7 day += 7
if (year % 4 == 0 and not year % 100 == 0) or (year % 400 == 0): if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
if day > days_per_month[month - 1] and month != 2: if day > days_per_month[month - 1] and month != 2:
month += 1 month += 1
day = day - days_per_month[month - 2] day = day - days_per_month[month - 2]

View File

@ -20,11 +20,9 @@ from fractions import Fraction
def is_digit_cancelling(num: int, den: int) -> bool: def is_digit_cancelling(num: int, den: int) -> bool:
if num != den: return (
if num % 10 == den // 10: num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
if (num // 10) / (den % 10) == num / den: )
return True
return False
def fraction_list(digit_len: int) -> list[str]: def fraction_list(digit_len: int) -> list[str]:

View File

@ -67,9 +67,8 @@ def solution(n: int = 10000) -> int:
count_odd_periods = 0 count_odd_periods = 0
for i in range(2, n + 1): for i in range(2, n + 1):
sr = sqrt(i) sr = sqrt(i)
if sr - floor(sr) != 0: if sr - floor(sr) != 0 and continuous_fraction_period(i) % 2 == 1:
if continuous_fraction_period(i) % 2 == 1: count_odd_periods += 1
count_odd_periods += 1
return count_odd_periods return count_odd_periods

View File

@ -37,14 +37,8 @@ def solution():
for i in range(1, len(a)): for i in range(1, len(a)):
for j in range(len(a[i])): for j in range(len(a[i])):
if j != len(a[i - 1]): number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
number1 = a[i - 1][j] number2 = a[i - 1][j - 1] if j > 0 else 0
else:
number1 = 0
if j > 0:
number2 = a[i - 1][j - 1]
else:
number2 = 0
a[i][j] += max(number1, number2) a[i][j] += max(number1, number2)
return max(a[-1]) return max(a[-1])

View File

@ -65,7 +65,7 @@ def solution(limit: int = 100) -> int:
>>> solution(50) >>> solution(50)
12577 12577
""" """
singles: list[int] = list(range(1, 21)) + [25] singles: list[int] = [*list(range(1, 21)), 25]
doubles: list[int] = [2 * x for x in range(1, 21)] + [50] doubles: list[int] = [2 * x for x in range(1, 21)] + [50]
triples: list[int] = [3 * x for x in range(1, 21)] triples: list[int] = [3 * x for x in range(1, 21)]
all_values: list[int] = singles + doubles + triples + [0] all_values: list[int] = singles + doubles + triples + [0]

View File

@ -50,8 +50,8 @@ def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]:
coefficients = {1} coefficients = {1}
previous_coefficients = [1] previous_coefficients = [1]
for _ in range(2, depth + 1): for _ in range(2, depth + 1):
coefficients_begins_one = previous_coefficients + [0] coefficients_begins_one = [*previous_coefficients, 0]
coefficients_ends_one = [0] + previous_coefficients coefficients_ends_one = [0, *previous_coefficients]
previous_coefficients = [] previous_coefficients = []
for x, y in zip(coefficients_begins_one, coefficients_ends_one): for x, y in zip(coefficients_begins_one, coefficients_ends_one):
coefficients.add(x + y) coefficients.add(x + y)

View File

@ -36,12 +36,11 @@ def calculate_waitingtime(
# Process until all processes are completed # Process until all processes are completed
while complete != no_of_processes: while complete != no_of_processes:
for j in range(no_of_processes): for j in range(no_of_processes):
if arrival_time[j] <= increment_time: if arrival_time[j] <= increment_time and remaining_time[j] > 0:
if remaining_time[j] > 0: if remaining_time[j] < minm:
if remaining_time[j] < minm: minm = remaining_time[j]
minm = remaining_time[j] short = j
short = j check = True
check = True
if not check: if not check:
increment_time += 1 increment_time += 1

View File

@ -21,9 +21,8 @@ def md_prefix(i):
def print_path(old_path: str, new_path: str) -> str: def print_path(old_path: str, new_path: str) -> str:
old_parts = old_path.split(os.sep) old_parts = old_path.split(os.sep)
for i, new_part in enumerate(new_path.split(os.sep)): for i, new_part in enumerate(new_path.split(os.sep)):
if i + 1 > len(old_parts) or old_parts[i] != new_part: if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part:
if new_part: print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}")
print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}")
return new_path return new_path

View File

@ -37,6 +37,7 @@ def build_tree():
right_node = TreeNode(int(check)) right_node = TreeNode(int(check))
node_found.right = right_node node_found.right = right_node
q.put(right_node) q.put(right_node)
return None
def pre_order(node: TreeNode) -> None: def pre_order(node: TreeNode) -> None:

View File

@ -58,14 +58,13 @@ def circle_sort(collection: list) -> list:
left += 1 left += 1
right -= 1 right -= 1
if left == right: if left == right and collection[left] > collection[right + 1]:
if collection[left] > collection[right + 1]: collection[left], collection[right + 1] = (
collection[left], collection[right + 1] = ( collection[right + 1],
collection[right + 1], collection[left],
collection[left], )
)
swapped = True swapped = True
mid = low + int((high - low) / 2) mid = low + int((high - low) / 2)
left_swap = circle_sort_util(collection, low, mid) left_swap = circle_sort_util(collection, low, mid)

View File

@ -66,7 +66,7 @@ def counting_sort_string(string):
if __name__ == "__main__": if __name__ == "__main__":
# Test string sort # Test string sort
assert "eghhiiinrsssttt" == counting_sort_string("thisisthestring") assert counting_sort_string("thisisthestring") == "eghhiiinrsssttt"
user_input = input("Enter numbers separated by a comma:\n").strip() user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")] unsorted = [int(item) for item in user_input.split(",")]

View File

@ -147,7 +147,7 @@ def _msd_radix_sort_inplace(
list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i]
j -= 1 j -= 1
if not j == i: if j != i:
i += 1 i += 1
_msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i)

View File

@ -39,7 +39,7 @@ def quick_sort(collection: list) -> list:
for element in collection[pivot_index + 1 :]: for element in collection[pivot_index + 1 :]:
(greater if element > pivot else lesser).append(element) (greater if element > pivot else lesser).append(element)
return quick_sort(lesser) + [pivot] + quick_sort(greater) return [*quick_sort(lesser), pivot, *quick_sort(greater)]
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -9,11 +9,11 @@ def quick_sort(data: list) -> list:
if len(data) <= 1: if len(data) <= 1:
return data return data
else: else:
return ( return [
quick_sort([e for e in data[1:] if e <= data[0]]) *quick_sort([e for e in data[1:] if e <= data[0]]),
+ [data[0]] data[0],
+ quick_sort([e for e in data[1:] if e > data[0]]) *quick_sort([e for e in data[1:] if e > data[0]]),
) ]
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -32,9 +32,9 @@ def merge(left, right):
return left return left
if left[0] < right[0]: if left[0] < right[0]:
return [left[0]] + merge(left[1:], right) return [left[0], *merge(left[1:], right)]
return [right[0]] + merge(left, right[1:]) return [right[0], *merge(left, right[1:])]
def tim_sort(lst): def tim_sort(lst):

View File

@ -27,10 +27,7 @@ class Trie:
def _elements(self, d: dict) -> tuple: def _elements(self, d: dict) -> tuple:
result = [] result = []
for c, v in d.items(): for c, v in d.items():
if c == END: sub_result = [" "] if c == END else [(c + s) for s in self._elements(v)]
sub_result = [" "]
else:
sub_result = [c + s for s in self._elements(v)]
result.extend(sub_result) result.extend(sub_result)
return tuple(result) return tuple(result)

View File

@ -38,10 +38,7 @@ def check_anagrams(first_str: str, second_str: str) -> bool:
count[first_str[i]] += 1 count[first_str[i]] += 1
count[second_str[i]] -= 1 count[second_str[i]] -= 1
for _count in count.values(): return all(_count == 0 for _count in count.values())
if _count != 0:
return False
return True
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -30,10 +30,7 @@ def is_palindrome(s: str) -> bool:
# with the help of 1st index (i==n-i-1) # with the help of 1st index (i==n-i-1)
# where n is length of string # where n is length of string
for i in range(end): return all(s[i] == s[n - i - 1] for i in range(end))
if s[i] != s[n - i - 1]:
return False
return True
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -43,7 +43,7 @@ def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str:
initial_word = "" if use_pascal else words[0] initial_word = "" if use_pascal else words[0]
return "".join([initial_word] + capitalized_words) return "".join([initial_word, *capitalized_words])
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -63,7 +63,7 @@ def convert(number: int) -> str:
current = temp_num % 10 current = temp_num % 10
if counter % 2 == 0: if counter % 2 == 0:
addition = "" addition = ""
if counter in placevalue.keys() and current != 0: if counter in placevalue and current != 0:
addition = placevalue[counter] addition = placevalue[counter]
if counter == 2: if counter == 2:
words = singles[current] + addition + words words = singles[current] + addition + words
@ -84,12 +84,12 @@ def convert(number: int) -> str:
words = teens[number % 10] + words words = teens[number % 10] + words
else: else:
addition = "" addition = ""
if counter in placevalue.keys(): if counter in placevalue:
addition = placevalue[counter] addition = placevalue[counter]
words = doubles[current] + addition + words words = doubles[current] + addition + words
else: else:
addition = "" addition = ""
if counter in placevalue.keys(): if counter in placevalue:
if current == 0 and ((temp_num % 100) // 10) == 0: if current == 0 and ((temp_num % 100) // 10) == 0:
addition = "" addition = ""
else: else:

View File

@ -105,7 +105,7 @@ def test_instagram_user(username: str = "github") -> None:
import os import os
if os.environ.get("CI"): if os.environ.get("CI"):
return None # test failing on GitHub Actions return # test failing on GitHub Actions
instagram_user = InstagramUser(username) instagram_user = InstagramUser(username)
assert instagram_user.user_data assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict) assert isinstance(instagram_user.user_data, dict)

View File

@ -7,10 +7,7 @@ from bs4 import BeautifulSoup
from fake_useragent import UserAgent from fake_useragent import UserAgent
if __name__ == "__main__": if __name__ == "__main__":
if len(argv) > 1: query = "%20".join(argv[1:]) if len(argv) > 1 else quote(str(input("Search: ")))
query = "%20".join(argv[1:])
else:
query = quote(str(input("Search: ")))
print("Googling.....") print("Googling.....")