mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
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:
parent
1c15cdff70
commit
64543faa98
|
@ -47,7 +47,7 @@ class IIRFilter:
|
|||
>>> 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(
|
||||
|
|
|
@ -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,
|
||||
)
|
||||
|
|
|
@ -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],
|
||||
)
|
||||
|
|
|
@ -33,7 +33,7 @@ class BifidCipher:
|
|||
>>> 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
|
||||
|
||||
|
|
|
@ -228,10 +228,10 @@ class DiffieHellman:
|
|||
|
||||
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)
|
||||
|
@ -243,10 +243,10 @@ class DiffieHellman:
|
|||
@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(
|
||||
|
|
|
@ -31,7 +31,7 @@ class PolybiusCipher:
|
|||
>>> 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
|
||||
|
||||
|
|
|
@ -128,8 +128,7 @@ class XORCipher:
|
|||
assert isinstance(file, str) and isinstance(key, int)
|
||||
|
||||
try:
|
||||
with open(file) as fin:
|
||||
with open("encrypt.out", "w+") as fout:
|
||||
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))
|
||||
|
@ -152,8 +151,7 @@ class XORCipher:
|
|||
assert isinstance(file, str) and isinstance(key, int)
|
||||
|
||||
try:
|
||||
with open(file) as fin:
|
||||
with open("decrypt.out", "w+") as fout:
|
||||
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))
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -60,7 +60,7 @@ class BinarySearchTree:
|
|||
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:
|
||||
|
|
|
@ -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]:
|
||||
|
@ -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:
|
||||
|
|
|
@ -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 = []
|
||||
|
|
|
@ -319,8 +319,7 @@ class RedBlackTree:
|
|||
"""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:
|
||||
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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -136,12 +136,12 @@ class BinomialHeap:
|
|||
|
||||
# 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
|
||||
|
||||
|
|
|
@ -128,7 +128,7 @@ class LinkedList:
|
|||
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)
|
||||
|
|
|
@ -107,6 +107,7 @@ class LinkedList:
|
|||
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:
|
||||
|
|
|
@ -388,10 +388,7 @@ def test_delete_doesnt_leave_dead_nodes():
|
|||
|
||||
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):
|
||||
|
|
|
@ -127,7 +127,7 @@ class CircularQueueLinkedList:
|
|||
"""
|
||||
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
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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)]
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -139,8 +139,7 @@ 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):
|
||||
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:
|
||||
|
@ -243,8 +242,7 @@ 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):
|
||||
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
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -112,7 +112,7 @@ class Graph:
|
|||
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
|
||||
|
|
|
@ -163,8 +163,7 @@ class PushRelabelExecutor(MaximumFlowAlgorithmExecutor):
|
|||
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:
|
||||
) and (min_height is None or self.heights[to_index] < min_height):
|
||||
min_height = self.heights[to_index]
|
||||
|
||||
if min_height is not None:
|
||||
|
|
|
@ -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
|
||||
"""
|
||||
|
@ -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"],))
|
||||
|
||||
|
||||
|
|
|
@ -144,6 +144,7 @@ class Graph:
|
|||
self.rank[root1] += 1
|
||||
self.parent[root2] = root1
|
||||
return root1
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def boruvka_mst(graph):
|
||||
|
|
|
@ -44,10 +44,7 @@ class Heap:
|
|||
temp = position[index]
|
||||
|
||||
while index != 0:
|
||||
if index % 2 == 0:
|
||||
parent = int((index - 2) / 2)
|
||||
else:
|
||||
parent = int((index - 1) / 2)
|
||||
parent = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
|
||||
|
||||
if val < heap[parent]:
|
||||
heap[index] = heap[parent]
|
||||
|
|
|
@ -135,14 +135,14 @@ class MinPriorityQueue(Generic[T]):
|
|||
# only]
|
||||
curr_pos = self.position_map[elem]
|
||||
if curr_pos == 0:
|
||||
return
|
||||
return None
|
||||
parent_position = get_parent_position(curr_pos)
|
||||
_, weight = self.heap[curr_pos]
|
||||
_, parent_weight = self.heap[parent_position]
|
||||
if parent_weight > weight:
|
||||
self._swap_nodes(parent_position, curr_pos)
|
||||
return self._bubble_up(elem)
|
||||
return
|
||||
return None
|
||||
|
||||
def _bubble_down(self, elem: T) -> None:
|
||||
# Place a node at the proper position (downward movement) [to be used
|
||||
|
@ -154,8 +154,7 @@ class MinPriorityQueue(Generic[T]):
|
|||
if child_left_position < self.elements and child_right_position < self.elements:
|
||||
_, child_left_weight = self.heap[child_left_position]
|
||||
_, child_right_weight = self.heap[child_right_position]
|
||||
if child_right_weight < child_left_weight:
|
||||
if child_right_weight < weight:
|
||||
if child_right_weight < child_left_weight and child_right_weight < weight:
|
||||
self._swap_nodes(child_right_position, curr_pos)
|
||||
return self._bubble_down(elem)
|
||||
if child_left_position < self.elements:
|
||||
|
@ -164,14 +163,13 @@ class MinPriorityQueue(Generic[T]):
|
|||
self._swap_nodes(child_left_position, curr_pos)
|
||||
return self._bubble_down(elem)
|
||||
else:
|
||||
return
|
||||
return None
|
||||
if child_right_position < self.elements:
|
||||
_, child_right_weight = self.heap[child_right_position]
|
||||
if child_right_weight < weight:
|
||||
self._swap_nodes(child_right_position, curr_pos)
|
||||
return self._bubble_down(elem)
|
||||
else:
|
||||
return
|
||||
return None
|
||||
|
||||
def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None:
|
||||
# Swap the nodes at the given positions
|
||||
|
|
|
@ -126,8 +126,7 @@ def emitter_converter(size_par, data):
|
|||
aux = (bin_pos[cont_loop])[-1 * (bp)]
|
||||
except IndexError:
|
||||
aux = "0"
|
||||
if aux == "1":
|
||||
if x == "1":
|
||||
if aux == "1" and x == "1":
|
||||
cont_bo += 1
|
||||
cont_loop += 1
|
||||
parity.append(cont_bo % 2)
|
||||
|
|
|
@ -108,7 +108,7 @@ class Vector:
|
|||
mul implements the scalar multiplication
|
||||
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]
|
||||
return Vector(ans)
|
||||
elif isinstance(other, Vector) and len(self) == len(other):
|
||||
|
@ -216,7 +216,7 @@ def axpy(scalar: float, x: Vector, y: Vector) -> Vector:
|
|||
assert (
|
||||
isinstance(x, Vector)
|
||||
and isinstance(y, Vector)
|
||||
and (isinstance(scalar, int) or isinstance(scalar, float))
|
||||
and (isinstance(scalar, (int, float)))
|
||||
)
|
||||
return x * scalar + y
|
||||
|
||||
|
@ -337,12 +337,13 @@ class Matrix:
|
|||
"vector must have the same size as the "
|
||||
"number of columns of the matrix!"
|
||||
)
|
||||
elif isinstance(other, int) or isinstance(other, float): # matrix-scalar
|
||||
elif isinstance(other, (int, float)): # matrix-scalar
|
||||
matrix = [
|
||||
[self.__matrix[i][j] * other for j in range(self.__width)]
|
||||
for i in range(self.__height)
|
||||
]
|
||||
return Matrix(matrix, self.__width, self.__height)
|
||||
return None
|
||||
|
||||
def height(self) -> int:
|
||||
"""
|
||||
|
|
|
@ -55,6 +55,7 @@ def output(example_no, data_set):
|
|||
return train_data[example_no][1]
|
||||
elif data_set == "test":
|
||||
return test_data[example_no][1]
|
||||
return None
|
||||
|
||||
|
||||
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])
|
||||
elif data_set == "test":
|
||||
return _hypothesis_value(test_data[example_no][0])
|
||||
return None
|
||||
|
||||
|
||||
def summation_of_cost_derivative(index, end=m):
|
||||
|
|
|
@ -229,7 +229,7 @@ def report_generator(
|
|||
"""
|
||||
# Fill missing values with given rules
|
||||
if fill_missing_report:
|
||||
df.fillna(value=fill_missing_report, inplace=True)
|
||||
df = df.fillna(value=fill_missing_report)
|
||||
df["dummy"] = 1
|
||||
numeric_cols = df.select_dtypes(np.number).columns
|
||||
report = (
|
||||
|
@ -338,7 +338,7 @@ def report_generator(
|
|||
)
|
||||
report.columns.name = ""
|
||||
report = report.reset_index()
|
||||
report.drop(columns=["index"], inplace=True)
|
||||
report = report.drop(columns=["index"])
|
||||
return report
|
||||
|
||||
|
||||
|
|
|
@ -129,7 +129,7 @@ class SmoSVM:
|
|||
# error
|
||||
self._unbound = [i for i in self._all_samples if self._is_unbound(i)]
|
||||
for s in self.unbound:
|
||||
if s == i1 or s == i2:
|
||||
if s in (i1, i2):
|
||||
continue
|
||||
self._error[s] += (
|
||||
y1 * (a1_new - a1) * k(i1, s)
|
||||
|
@ -225,7 +225,7 @@ class SmoSVM:
|
|||
def _choose_alphas(self):
|
||||
locis = yield from self._choose_a1()
|
||||
if not locis:
|
||||
return
|
||||
return None
|
||||
return locis
|
||||
|
||||
def _choose_a1(self):
|
||||
|
@ -423,8 +423,7 @@ class Kernel:
|
|||
return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2))
|
||||
|
||||
def _check(self):
|
||||
if self._kernel == self._rbf:
|
||||
if self.gamma < 0:
|
||||
if self._kernel == self._rbf and self.gamma < 0:
|
||||
raise ValueError("gamma value must greater than 0")
|
||||
|
||||
def _get_kernel(self, kernel_name):
|
||||
|
|
|
@ -75,9 +75,9 @@ def test_abs_val():
|
|||
"""
|
||||
>>> test_abs_val()
|
||||
"""
|
||||
assert 0 == abs_val(0)
|
||||
assert 34 == abs_val(34)
|
||||
assert 100000000000 == abs_val(-100000000000)
|
||||
assert abs_val(0) == 0
|
||||
assert abs_val(34) == 34
|
||||
assert abs_val(-100000000000) == 100000000000
|
||||
|
||||
a = [-3, -1, 2, -11]
|
||||
assert abs_max(a) == -11
|
||||
|
|
|
@ -6,7 +6,7 @@ def bin_exp_mod(a, n, b):
|
|||
7
|
||||
"""
|
||||
# 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:
|
||||
return 1
|
||||
|
||||
|
|
|
@ -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 None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -12,6 +12,7 @@ def res(x, y):
|
|||
return 0
|
||||
elif y == 0:
|
||||
return 1 # any number raised to 0 is 1
|
||||
raise AssertionError("This should never happen")
|
||||
|
||||
|
||||
if __name__ == "__main__": # Main function
|
||||
|
|
|
@ -80,10 +80,7 @@ class FFT:
|
|||
|
||||
# Discrete fourier transform of A and B
|
||||
def __dft(self, which):
|
||||
if which == "A":
|
||||
dft = [[x] for x in self.polyA]
|
||||
else:
|
||||
dft = [[x] for x in self.polyB]
|
||||
dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
|
||||
# Corner case
|
||||
if len(dft) <= 1:
|
||||
return dft[0]
|
||||
|
|
|
@ -153,6 +153,7 @@ class BPNN:
|
|||
if mse < self.accuracy:
|
||||
print("----达到精度----")
|
||||
return mse
|
||||
return None
|
||||
|
||||
def cal_loss(self, ydata, ydata_):
|
||||
self.loss = np.sum(np.power((ydata - ydata_), 2))
|
||||
|
|
|
@ -125,8 +125,7 @@ def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]:
|
|||
miny = y
|
||||
minx = x
|
||||
minidx = i
|
||||
if y == miny:
|
||||
if x < minx:
|
||||
if y == miny and x < minx:
|
||||
minx = x
|
||||
minidx = i
|
||||
|
||||
|
|
|
@ -24,9 +24,8 @@ def is_balanced(s):
|
|||
if s[i] in open_brackets:
|
||||
stack.append(s[i])
|
||||
|
||||
elif s[i] in closed_brackets:
|
||||
if len(stack) == 0 or (
|
||||
len(stack) > 0 and open_to_closed[stack.pop()] != s[i]
|
||||
elif s[i] in closed_brackets and (
|
||||
len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != s[i])
|
||||
):
|
||||
return False
|
||||
|
||||
|
|
|
@ -70,10 +70,10 @@ def hubble_parameter(
|
|||
68.3
|
||||
"""
|
||||
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")
|
||||
|
||||
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")
|
||||
else:
|
||||
curvature = 1 - (matter_density + radiation_density + dark_energy)
|
||||
|
|
|
@ -63,6 +63,7 @@ def solution(n: int = 20) -> int:
|
|||
if i == 0:
|
||||
i = 1
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -32,8 +32,7 @@ def solution() -> int:
|
|||
for a in range(300):
|
||||
for b in range(a + 1, 400):
|
||||
for c in range(b + 1, 500):
|
||||
if (a + b + c) == 1000:
|
||||
if (a**2) + (b**2) == (c**2):
|
||||
if (a + b + c) == 1000 and (a**2) + (b**2) == (c**2):
|
||||
return a * b * c
|
||||
|
||||
return -1
|
||||
|
|
|
@ -34,10 +34,7 @@ def collatz_sequence_length(n: int) -> int:
|
|||
"""Returns the Collatz sequence length for n."""
|
||||
if n in COLLATZ_SEQUENCE_LENGTHS:
|
||||
return COLLATZ_SEQUENCE_LENGTHS[n]
|
||||
if n % 2 == 0:
|
||||
next_n = n // 2
|
||||
else:
|
||||
next_n = 3 * n + 1
|
||||
next_n = n // 2 if n % 2 == 0 else 3 * n + 1
|
||||
sequence_length = collatz_sequence_length(next_n) + 1
|
||||
COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length
|
||||
return sequence_length
|
||||
|
|
|
@ -48,14 +48,8 @@ def solution():
|
|||
|
||||
for i in range(1, len(a)):
|
||||
for j in range(len(a[i])):
|
||||
if j != len(a[i - 1]):
|
||||
number1 = a[i - 1][j]
|
||||
else:
|
||||
number1 = 0
|
||||
if j > 0:
|
||||
number2 = a[i - 1][j - 1]
|
||||
else:
|
||||
number2 = 0
|
||||
number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
|
||||
number2 = a[i - 1][j - 1] if j > 0 else 0
|
||||
a[i][j] += max(number1, number2)
|
||||
return max(a[-1])
|
||||
|
||||
|
|
|
@ -39,7 +39,7 @@ def solution():
|
|||
while year < 2001:
|
||||
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:
|
||||
month += 1
|
||||
day = day - days_per_month[month - 2]
|
||||
|
|
|
@ -20,11 +20,9 @@ from fractions import Fraction
|
|||
|
||||
|
||||
def is_digit_cancelling(num: int, den: int) -> bool:
|
||||
if num != den:
|
||||
if num % 10 == den // 10:
|
||||
if (num // 10) / (den % 10) == num / den:
|
||||
return True
|
||||
return False
|
||||
return (
|
||||
num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
|
||||
)
|
||||
|
||||
|
||||
def fraction_list(digit_len: int) -> list[str]:
|
||||
|
|
|
@ -67,8 +67,7 @@ def solution(n: int = 10000) -> int:
|
|||
count_odd_periods = 0
|
||||
for i in range(2, n + 1):
|
||||
sr = sqrt(i)
|
||||
if sr - floor(sr) != 0:
|
||||
if continuous_fraction_period(i) % 2 == 1:
|
||||
if sr - floor(sr) != 0 and continuous_fraction_period(i) % 2 == 1:
|
||||
count_odd_periods += 1
|
||||
return count_odd_periods
|
||||
|
||||
|
|
|
@ -37,14 +37,8 @@ def solution():
|
|||
|
||||
for i in range(1, len(a)):
|
||||
for j in range(len(a[i])):
|
||||
if j != len(a[i - 1]):
|
||||
number1 = a[i - 1][j]
|
||||
else:
|
||||
number1 = 0
|
||||
if j > 0:
|
||||
number2 = a[i - 1][j - 1]
|
||||
else:
|
||||
number2 = 0
|
||||
number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
|
||||
number2 = a[i - 1][j - 1] if j > 0 else 0
|
||||
a[i][j] += max(number1, number2)
|
||||
return max(a[-1])
|
||||
|
||||
|
|
|
@ -65,7 +65,7 @@ def solution(limit: int = 100) -> int:
|
|||
>>> solution(50)
|
||||
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]
|
||||
triples: list[int] = [3 * x for x in range(1, 21)]
|
||||
all_values: list[int] = singles + doubles + triples + [0]
|
||||
|
|
|
@ -50,8 +50,8 @@ def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]:
|
|||
coefficients = {1}
|
||||
previous_coefficients = [1]
|
||||
for _ in range(2, depth + 1):
|
||||
coefficients_begins_one = previous_coefficients + [0]
|
||||
coefficients_ends_one = [0] + previous_coefficients
|
||||
coefficients_begins_one = [*previous_coefficients, 0]
|
||||
coefficients_ends_one = [0, *previous_coefficients]
|
||||
previous_coefficients = []
|
||||
for x, y in zip(coefficients_begins_one, coefficients_ends_one):
|
||||
coefficients.add(x + y)
|
||||
|
|
|
@ -36,8 +36,7 @@ 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:
|
||||
if remaining_time[j] > 0:
|
||||
if arrival_time[j] <= increment_time and remaining_time[j] > 0:
|
||||
if remaining_time[j] < minm:
|
||||
minm = remaining_time[j]
|
||||
short = j
|
||||
|
|
|
@ -21,8 +21,7 @@ def md_prefix(i):
|
|||
def print_path(old_path: str, new_path: str) -> str:
|
||||
old_parts = old_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 new_part:
|
||||
if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part:
|
||||
print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}")
|
||||
return new_path
|
||||
|
||||
|
|
|
@ -37,6 +37,7 @@ def build_tree():
|
|||
right_node = TreeNode(int(check))
|
||||
node_found.right = right_node
|
||||
q.put(right_node)
|
||||
return None
|
||||
|
||||
|
||||
def pre_order(node: TreeNode) -> None:
|
||||
|
|
|
@ -58,8 +58,7 @@ def circle_sort(collection: list) -> list:
|
|||
left += 1
|
||||
right -= 1
|
||||
|
||||
if left == right:
|
||||
if collection[left] > collection[right + 1]:
|
||||
if left == right and collection[left] > collection[right + 1]:
|
||||
collection[left], collection[right + 1] = (
|
||||
collection[right + 1],
|
||||
collection[left],
|
||||
|
|
|
@ -66,7 +66,7 @@ def counting_sort_string(string):
|
|||
|
||||
if __name__ == "__main__":
|
||||
# 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()
|
||||
unsorted = [int(item) for item in user_input.split(",")]
|
||||
|
|
|
@ -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]
|
||||
j -= 1
|
||||
if not j == i:
|
||||
if j != i:
|
||||
i += 1
|
||||
|
||||
_msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i)
|
||||
|
|
|
@ -39,7 +39,7 @@ def quick_sort(collection: list) -> list:
|
|||
for element in collection[pivot_index + 1 :]:
|
||||
(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__":
|
||||
|
|
|
@ -9,11 +9,11 @@ def quick_sort(data: list) -> list:
|
|||
if len(data) <= 1:
|
||||
return data
|
||||
else:
|
||||
return (
|
||||
quick_sort([e for e in data[1:] if e <= data[0]])
|
||||
+ [data[0]]
|
||||
+ quick_sort([e for e in data[1:] if e > data[0]])
|
||||
)
|
||||
return [
|
||||
*quick_sort([e for e in data[1:] if e <= data[0]]),
|
||||
data[0],
|
||||
*quick_sort([e for e in data[1:] if e > data[0]]),
|
||||
]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -32,9 +32,9 @@ def merge(left, right):
|
|||
return left
|
||||
|
||||
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):
|
||||
|
|
|
@ -27,10 +27,7 @@ class Trie:
|
|||
def _elements(self, d: dict) -> tuple:
|
||||
result = []
|
||||
for c, v in d.items():
|
||||
if c == END:
|
||||
sub_result = [" "]
|
||||
else:
|
||||
sub_result = [c + s for s in self._elements(v)]
|
||||
sub_result = [" "] if c == END else [(c + s) for s in self._elements(v)]
|
||||
result.extend(sub_result)
|
||||
return tuple(result)
|
||||
|
||||
|
|
|
@ -38,10 +38,7 @@ def check_anagrams(first_str: str, second_str: str) -> bool:
|
|||
count[first_str[i]] += 1
|
||||
count[second_str[i]] -= 1
|
||||
|
||||
for _count in count.values():
|
||||
if _count != 0:
|
||||
return False
|
||||
return True
|
||||
return all(_count == 0 for _count in count.values())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -30,10 +30,7 @@ def is_palindrome(s: str) -> bool:
|
|||
# with the help of 1st index (i==n-i-1)
|
||||
# where n is length of string
|
||||
|
||||
for i in range(end):
|
||||
if s[i] != s[n - i - 1]:
|
||||
return False
|
||||
return True
|
||||
return all(s[i] == s[n - i - 1] for i in range(end))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -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]
|
||||
|
||||
return "".join([initial_word] + capitalized_words)
|
||||
return "".join([initial_word, *capitalized_words])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -63,7 +63,7 @@ def convert(number: int) -> str:
|
|||
current = temp_num % 10
|
||||
if counter % 2 == 0:
|
||||
addition = ""
|
||||
if counter in placevalue.keys() and current != 0:
|
||||
if counter in placevalue and current != 0:
|
||||
addition = placevalue[counter]
|
||||
if counter == 2:
|
||||
words = singles[current] + addition + words
|
||||
|
@ -84,12 +84,12 @@ def convert(number: int) -> str:
|
|||
words = teens[number % 10] + words
|
||||
else:
|
||||
addition = ""
|
||||
if counter in placevalue.keys():
|
||||
if counter in placevalue:
|
||||
addition = placevalue[counter]
|
||||
words = doubles[current] + addition + words
|
||||
else:
|
||||
addition = ""
|
||||
if counter in placevalue.keys():
|
||||
if counter in placevalue:
|
||||
if current == 0 and ((temp_num % 100) // 10) == 0:
|
||||
addition = ""
|
||||
else:
|
||||
|
|
|
@ -105,7 +105,7 @@ def test_instagram_user(username: str = "github") -> None:
|
|||
import os
|
||||
|
||||
if os.environ.get("CI"):
|
||||
return None # test failing on GitHub Actions
|
||||
return # test failing on GitHub Actions
|
||||
instagram_user = InstagramUser(username)
|
||||
assert instagram_user.user_data
|
||||
assert isinstance(instagram_user.user_data, dict)
|
||||
|
|
|
@ -7,10 +7,7 @@ from bs4 import BeautifulSoup
|
|||
from fake_useragent import UserAgent
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(argv) > 1:
|
||||
query = "%20".join(argv[1:])
|
||||
else:
|
||||
query = quote(str(input("Search: ")))
|
||||
query = "%20".join(argv[1:]) if len(argv) > 1 else quote(str(input("Search: ")))
|
||||
|
||||
print("Googling.....")
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user