mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Add flake8 pluin flake8 bugbear to pre-commit (#7132)
* ci(pre-commit): Add ``flake8-builtins`` additional dependency to ``pre-commit`` (#7104) * refactor: Fix ``flake8-builtins`` (#7104) * fix(lru_cache): Fix naming conventions in docstrings (#7104) * ci(pre-commit): Order additional dependencies alphabetically (#7104) * fix(lfu_cache): Correct function name in docstring (#7104) * Update strings/snake_case_to_camel_pascal_case.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update data_structures/stacks/next_greater_element.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update digital_image_processing/index_calculation.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update graphs/prim.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update hashes/djb2.py Co-authored-by: Christian Clauss <cclauss@me.com> * refactor: Rename `_builtin` to `builtin_` ( #7104) * fix: Rename all instances (#7104) * refactor: Update variable names (#7104) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * ci: Create ``tox.ini`` and ignore ``A003`` (#7123) * revert: Remove function name changes (#7104) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Rename tox.ini to .flake8 * Update data_structures/heap/heap.py Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com> * refactor: Rename `next_` to `next_item` (#7104) * ci(pre-commit): Add `flake8` plugin `flake8-bugbear` (#7127) * refactor: Follow `flake8-bugbear` plugin (#7127) * fix: Correct `knapsack` code (#7127) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
This commit is contained in:
parent
f176786d12
commit
4d0c830d2c
|
@ -40,7 +40,10 @@ repos:
|
|||
- --ignore=E203,W503
|
||||
- --max-complexity=25
|
||||
- --max-line-length=88
|
||||
additional_dependencies: [flake8-builtins, pep8-naming]
|
||||
additional_dependencies:
|
||||
- flake8-bugbear
|
||||
- flake8-builtins
|
||||
- pep8-naming
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v0.982
|
||||
|
|
|
@ -110,7 +110,7 @@ def jacobi_iteration_method(
|
|||
strictly_diagonally_dominant(table)
|
||||
|
||||
# Iterates the whole matrix for given number of times
|
||||
for i in range(iterations):
|
||||
for _ in range(iterations):
|
||||
new_val = []
|
||||
for row in range(rows):
|
||||
temp = 0
|
||||
|
|
|
@ -23,7 +23,7 @@ def ucal(u: float, p: int) -> float:
|
|||
def main() -> None:
|
||||
n = int(input("enter the numbers of values: "))
|
||||
y: list[list[float]] = []
|
||||
for i in range(n):
|
||||
for _ in range(n):
|
||||
y.append([])
|
||||
for i in range(n):
|
||||
for j in range(n):
|
||||
|
|
|
@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
|
|||
"""
|
||||
x0 = lower_bound
|
||||
x1 = upper_bound
|
||||
for i in range(0, repeats):
|
||||
for _ in range(0, repeats):
|
||||
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
|
||||
return x1
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@ Alternatively you can use scipy.signal.butter, which should yield the same resul
|
|||
|
||||
|
||||
def make_lowpass(
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2)
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008
|
||||
) -> IIRFilter:
|
||||
"""
|
||||
Creates a low-pass filter
|
||||
|
@ -39,7 +39,7 @@ def make_lowpass(
|
|||
|
||||
|
||||
def make_highpass(
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2)
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008
|
||||
) -> IIRFilter:
|
||||
"""
|
||||
Creates a high-pass filter
|
||||
|
@ -67,7 +67,7 @@ def make_highpass(
|
|||
|
||||
|
||||
def make_bandpass(
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2)
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008
|
||||
) -> IIRFilter:
|
||||
"""
|
||||
Creates a band-pass filter
|
||||
|
@ -96,7 +96,7 @@ def make_bandpass(
|
|||
|
||||
|
||||
def make_allpass(
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2)
|
||||
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008
|
||||
) -> IIRFilter:
|
||||
"""
|
||||
Creates an all-pass filter
|
||||
|
@ -121,7 +121,10 @@ def make_allpass(
|
|||
|
||||
|
||||
def make_peak(
|
||||
frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2)
|
||||
frequency: int,
|
||||
samplerate: int,
|
||||
gain_db: float,
|
||||
q_factor: float = 1 / sqrt(2), # noqa: B008
|
||||
) -> IIRFilter:
|
||||
"""
|
||||
Creates a peak filter
|
||||
|
@ -150,7 +153,10 @@ def make_peak(
|
|||
|
||||
|
||||
def make_lowshelf(
|
||||
frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2)
|
||||
frequency: int,
|
||||
samplerate: int,
|
||||
gain_db: float,
|
||||
q_factor: float = 1 / sqrt(2), # noqa: B008
|
||||
) -> IIRFilter:
|
||||
"""
|
||||
Creates a low-shelf filter
|
||||
|
@ -184,7 +190,10 @@ def make_lowshelf(
|
|||
|
||||
|
||||
def make_highshelf(
|
||||
frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2)
|
||||
frequency: int,
|
||||
samplerate: int,
|
||||
gain_db: float,
|
||||
q_factor: float = 1 / sqrt(2), # noqa: B008
|
||||
) -> IIRFilter:
|
||||
"""
|
||||
Creates a high-shelf filter
|
||||
|
|
|
@ -39,14 +39,14 @@ def create_state_space_tree(
|
|||
if sum(path) == max_sum:
|
||||
result.append(path)
|
||||
return
|
||||
for num_index in range(num_index, len(nums)):
|
||||
for index in range(num_index, len(nums)):
|
||||
create_state_space_tree(
|
||||
nums,
|
||||
max_sum,
|
||||
num_index + 1,
|
||||
path + [nums[num_index]],
|
||||
index + 1,
|
||||
path + [nums[index]],
|
||||
result,
|
||||
remaining_nums_sum - nums[num_index],
|
||||
remaining_nums_sum - nums[index],
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -56,7 +56,7 @@ def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[st
|
|||
temp = []
|
||||
for minterm in minterms:
|
||||
string = ""
|
||||
for i in range(no_of_variable):
|
||||
for _ in range(no_of_variable):
|
||||
string = str(minterm % 2) + string
|
||||
minterm //= 2
|
||||
temp.append(string)
|
||||
|
|
|
@ -40,7 +40,7 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
|
|||
k = 0
|
||||
for _ in range(r):
|
||||
s = []
|
||||
for j in range(len_temp):
|
||||
for _ in range(len_temp):
|
||||
s.append(temp[k])
|
||||
if not (k < 25):
|
||||
break
|
||||
|
|
|
@ -11,7 +11,7 @@ def rabin_miller(num: int) -> bool:
|
|||
s = s // 2
|
||||
t += 1
|
||||
|
||||
for trials in range(5):
|
||||
for _ in range(5):
|
||||
a = random.randrange(2, num - 1)
|
||||
v = pow(a, s, num)
|
||||
if v != 1:
|
||||
|
|
|
@ -154,7 +154,7 @@ def reverse_bwt(bwt_string: str, idx_original_string: int) -> str:
|
|||
)
|
||||
|
||||
ordered_rotations = [""] * len(bwt_string)
|
||||
for x in range(len(bwt_string)):
|
||||
for _ in range(len(bwt_string)):
|
||||
for i in range(len(bwt_string)):
|
||||
ordered_rotations[i] = bwt_string[i] + ordered_rotations[i]
|
||||
ordered_rotations.sort()
|
||||
|
|
|
@ -357,7 +357,7 @@ class BinarySearchTreeTest(unittest.TestCase):
|
|||
assert t.root.left.left.parent == t.root.left
|
||||
assert t.root.left.left.label == 1
|
||||
|
||||
with self.assertRaises(Exception):
|
||||
with self.assertRaises(Exception): # noqa: B017
|
||||
t.put(1)
|
||||
|
||||
def test_search(self) -> None:
|
||||
|
@ -369,7 +369,7 @@ class BinarySearchTreeTest(unittest.TestCase):
|
|||
node = t.search(13)
|
||||
assert node.label == 13
|
||||
|
||||
with self.assertRaises(Exception):
|
||||
with self.assertRaises(Exception): # noqa: B017
|
||||
t.search(2)
|
||||
|
||||
def test_remove(self) -> None:
|
||||
|
@ -515,7 +515,7 @@ class BinarySearchTreeTest(unittest.TestCase):
|
|||
assert t.get_max_label() == 14
|
||||
|
||||
t.empty()
|
||||
with self.assertRaises(Exception):
|
||||
with self.assertRaises(Exception): # noqa: B017
|
||||
t.get_max_label()
|
||||
|
||||
def test_get_min_label(self) -> None:
|
||||
|
@ -524,7 +524,7 @@ class BinarySearchTreeTest(unittest.TestCase):
|
|||
assert t.get_min_label() == 1
|
||||
|
||||
t.empty()
|
||||
with self.assertRaises(Exception):
|
||||
with self.assertRaises(Exception): # noqa: B017
|
||||
t.get_min_label()
|
||||
|
||||
def test_inorder_traversal(self) -> None:
|
||||
|
|
|
@ -94,25 +94,25 @@ def test_circular_linked_list() -> None:
|
|||
|
||||
try:
|
||||
circular_linked_list.delete_front()
|
||||
assert False # This should not happen
|
||||
raise AssertionError() # This should not happen
|
||||
except IndexError:
|
||||
assert True # This should happen
|
||||
|
||||
try:
|
||||
circular_linked_list.delete_tail()
|
||||
assert False # This should not happen
|
||||
raise AssertionError() # This should not happen
|
||||
except IndexError:
|
||||
assert True # This should happen
|
||||
|
||||
try:
|
||||
circular_linked_list.delete_nth(-1)
|
||||
assert False
|
||||
raise AssertionError()
|
||||
except IndexError:
|
||||
assert True
|
||||
|
||||
try:
|
||||
circular_linked_list.delete_nth(0)
|
||||
assert False
|
||||
raise AssertionError()
|
||||
except IndexError:
|
||||
assert True
|
||||
|
||||
|
|
|
@ -96,7 +96,7 @@ class DoublyLinkedList:
|
|||
self.tail = new_node
|
||||
else:
|
||||
temp = self.head
|
||||
for i in range(0, index):
|
||||
for _ in range(0, index):
|
||||
temp = temp.next
|
||||
temp.previous.next = new_node
|
||||
new_node.previous = temp.previous
|
||||
|
@ -145,7 +145,7 @@ class DoublyLinkedList:
|
|||
self.tail.next = None
|
||||
else:
|
||||
temp = self.head
|
||||
for i in range(0, index):
|
||||
for _ in range(0, index):
|
||||
temp = temp.next
|
||||
delete_node = temp
|
||||
temp.next.previous = temp.previous
|
||||
|
@ -194,13 +194,13 @@ def test_doubly_linked_list() -> None:
|
|||
|
||||
try:
|
||||
linked_list.delete_head()
|
||||
assert False # This should not happen.
|
||||
raise AssertionError() # This should not happen.
|
||||
except IndexError:
|
||||
assert True # This should happen.
|
||||
|
||||
try:
|
||||
linked_list.delete_tail()
|
||||
assert False # This should not happen.
|
||||
raise AssertionError() # This should not happen.
|
||||
except IndexError:
|
||||
assert True # This should happen.
|
||||
|
||||
|
|
|
@ -62,7 +62,7 @@ class LinkedList:
|
|||
|
||||
if __name__ == "__main__":
|
||||
link = LinkedList()
|
||||
for i in range(int(input().strip())):
|
||||
for _ in range(int(input().strip())):
|
||||
data = int(input().strip())
|
||||
link.push(data)
|
||||
print(link.middle_element())
|
||||
|
|
|
@ -132,7 +132,7 @@ class LinkedList:
|
|||
if not 0 <= index < len(self):
|
||||
raise ValueError("list index out of range.")
|
||||
current = self.head
|
||||
for i in range(index):
|
||||
for _ in range(index):
|
||||
current = current.next
|
||||
current.data = data
|
||||
|
||||
|
@ -352,13 +352,13 @@ def test_singly_linked_list() -> None:
|
|||
|
||||
try:
|
||||
linked_list.delete_head()
|
||||
assert False # This should not happen.
|
||||
raise AssertionError() # This should not happen.
|
||||
except IndexError:
|
||||
assert True # This should happen.
|
||||
|
||||
try:
|
||||
linked_list.delete_tail()
|
||||
assert False # This should not happen.
|
||||
raise AssertionError() # This should not happen.
|
||||
except IndexError:
|
||||
assert True # This should happen.
|
||||
|
||||
|
|
|
@ -205,7 +205,7 @@ class SkipList(Generic[KT, VT]):
|
|||
|
||||
if level > self.level:
|
||||
# After level increase we have to add additional nodes to head.
|
||||
for i in range(self.level - 1, level):
|
||||
for _ in range(self.level - 1, level):
|
||||
update_vector.append(self.head)
|
||||
self.level = level
|
||||
|
||||
|
@ -407,7 +407,7 @@ def test_iter_always_yields_sorted_values():
|
|||
|
||||
|
||||
def pytests():
|
||||
for i in range(100):
|
||||
for _ in range(100):
|
||||
# Repeat test 100 times due to the probabilistic nature of skip list
|
||||
# random values == random bugs
|
||||
test_insert()
|
||||
|
|
|
@ -37,7 +37,7 @@ class Queue:
|
|||
number of times to rotate queue"""
|
||||
|
||||
def rotate(self, rotation):
|
||||
for i in range(rotation):
|
||||
for _ in range(rotation):
|
||||
self.put(self.get())
|
||||
|
||||
"""Enqueues {@code item}
|
||||
|
|
|
@ -37,7 +37,7 @@ class Queue:
|
|||
number of times to rotate queue"""
|
||||
|
||||
def rotate(self, rotation: int) -> None:
|
||||
for i in range(rotation):
|
||||
for _ in range(rotation):
|
||||
temp = self.stack[0]
|
||||
self.stack = self.stack[1:]
|
||||
self.put(temp)
|
||||
|
|
|
@ -92,13 +92,13 @@ def test_stack() -> None:
|
|||
|
||||
try:
|
||||
_ = stack.pop()
|
||||
assert False # This should not happen
|
||||
raise AssertionError() # This should not happen
|
||||
except StackUnderflowError:
|
||||
assert True # This should happen
|
||||
|
||||
try:
|
||||
_ = stack.peek()
|
||||
assert False # This should not happen
|
||||
raise AssertionError() # This should not happen
|
||||
except StackUnderflowError:
|
||||
assert True # This should happen
|
||||
|
||||
|
@ -118,7 +118,7 @@ def test_stack() -> None:
|
|||
|
||||
try:
|
||||
stack.push(200)
|
||||
assert False # This should not happen
|
||||
raise AssertionError() # This should not happen
|
||||
except StackOverflowError:
|
||||
assert True # This should happen
|
||||
|
||||
|
|
|
@ -458,16 +458,16 @@ def convex_hull_melkman(points: list[Point]) -> list[Point]:
|
|||
convex_hull[1] = points[i]
|
||||
i += 1
|
||||
|
||||
for i in range(i, n):
|
||||
for j in range(i, n):
|
||||
if (
|
||||
_det(convex_hull[0], convex_hull[-1], points[i]) > 0
|
||||
_det(convex_hull[0], convex_hull[-1], points[j]) > 0
|
||||
and _det(convex_hull[-1], convex_hull[0], points[1]) < 0
|
||||
):
|
||||
# The point lies within the convex hull
|
||||
continue
|
||||
|
||||
convex_hull.insert(0, points[i])
|
||||
convex_hull.append(points[i])
|
||||
convex_hull.insert(0, points[j])
|
||||
convex_hull.append(points[j])
|
||||
while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:
|
||||
del convex_hull[1]
|
||||
while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:
|
||||
|
|
|
@ -132,12 +132,12 @@ def strassen(matrix1: list, matrix2: list) -> list:
|
|||
# power of 2
|
||||
for i in range(0, maxim):
|
||||
if i < dimension1[0]:
|
||||
for j in range(dimension1[1], maxim):
|
||||
for _ in range(dimension1[1], maxim):
|
||||
new_matrix1[i].append(0)
|
||||
else:
|
||||
new_matrix1.append([0] * maxim)
|
||||
if i < dimension2[0]:
|
||||
for j in range(dimension2[1], maxim):
|
||||
for _ in range(dimension2[1], maxim):
|
||||
new_matrix2[i].append(0)
|
||||
else:
|
||||
new_matrix2.append([0] * maxim)
|
||||
|
@ -147,7 +147,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
|
|||
# Removing the additional zeros
|
||||
for i in range(0, maxim):
|
||||
if i < dimension1[0]:
|
||||
for j in range(dimension2[1], maxim):
|
||||
for _ in range(dimension2[1], maxim):
|
||||
final_matrix[i].pop()
|
||||
else:
|
||||
final_matrix.pop()
|
||||
|
|
|
@ -21,7 +21,7 @@ def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[
|
|||
table_size: int = len(target) + 1
|
||||
|
||||
table: list[list[list[str]]] = []
|
||||
for i in range(table_size):
|
||||
for _ in range(table_size):
|
||||
table.append([])
|
||||
# seed value
|
||||
table[0] = [[]] # because empty string has empty combination
|
||||
|
|
|
@ -30,13 +30,13 @@ def knapsack(w, wt, val, n):
|
|||
dp = [[0 for i in range(w + 1)] for j in range(n + 1)]
|
||||
|
||||
for i in range(1, n + 1):
|
||||
for w in range(1, w + 1):
|
||||
if wt[i - 1] <= w:
|
||||
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w])
|
||||
for w_ in range(1, w + 1):
|
||||
if wt[i - 1] <= w_:
|
||||
dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_])
|
||||
else:
|
||||
dp[i][w] = dp[i - 1][w]
|
||||
dp[i][w_] = dp[i - 1][w_]
|
||||
|
||||
return dp[n][w], dp
|
||||
return dp[n][w_], dp
|
||||
|
||||
|
||||
def knapsack_with_example_solution(w: int, wt: list, val: list):
|
||||
|
|
|
@ -118,7 +118,7 @@ def iterate_function(
|
|||
"""
|
||||
|
||||
z_n = z_0.astype("complex64")
|
||||
for i in range(nb_iterations):
|
||||
for _ in range(nb_iterations):
|
||||
z_n = eval_function(function_params, z_n)
|
||||
if infinity is not None:
|
||||
numpy.nan_to_num(z_n, copy=False, nan=infinity)
|
||||
|
|
|
@ -46,7 +46,7 @@ def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndar
|
|||
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
|
||||
"""
|
||||
vectors = initial_vectors
|
||||
for i in range(steps):
|
||||
for _ in range(steps):
|
||||
vectors = iteration_step(vectors)
|
||||
return vectors
|
||||
|
||||
|
|
|
@ -36,7 +36,7 @@ def get_distance(x: float, y: float, max_step: int) -> float:
|
|||
"""
|
||||
a = x
|
||||
b = y
|
||||
for step in range(max_step):
|
||||
for step in range(max_step): # noqa: B007
|
||||
a_new = a * a - b * b + x
|
||||
b = 2 * a * b + y
|
||||
a = a_new
|
||||
|
|
|
@ -80,7 +80,7 @@ def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int,
|
|||
score = len(
|
||||
[g for position, g in enumerate(item) if g == main_target[position]]
|
||||
)
|
||||
return (item, float(score))
|
||||
return (item, float(score)) # noqa: B023
|
||||
|
||||
# Adding a bit of concurrency can make everything faster,
|
||||
#
|
||||
|
@ -129,7 +129,10 @@ def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int,
|
|||
child_n = int(parent_1[1] * 100) + 1
|
||||
child_n = 10 if child_n >= 10 else child_n
|
||||
for _ in range(child_n):
|
||||
parent_2 = population_score[random.randint(0, N_SELECTED)][0]
|
||||
parent_2 = population_score[ # noqa: B023
|
||||
random.randint(0, N_SELECTED)
|
||||
][0]
|
||||
|
||||
child_1, child_2 = crossover(parent_1[0], parent_2)
|
||||
# Append new string to the population list
|
||||
pop.append(mutate(child_1))
|
||||
|
|
|
@ -188,7 +188,7 @@ def topo(g, ind=None, q=None):
|
|||
def adjm():
|
||||
n = input().strip()
|
||||
a = []
|
||||
for i in range(n):
|
||||
for _ in range(n):
|
||||
a.append(map(int, input().strip().split()))
|
||||
return a, n
|
||||
|
||||
|
@ -264,7 +264,7 @@ def prim(g, s):
|
|||
def edglist():
|
||||
n, m = map(int, input().split(" "))
|
||||
edges = []
|
||||
for i in range(m):
|
||||
for _ in range(m):
|
||||
edges.append(map(int, input().split(" ")))
|
||||
return edges, n
|
||||
|
||||
|
|
|
@ -36,7 +36,7 @@ def bellman_ford(
|
|||
distance = [float("inf")] * vertex_count
|
||||
distance[src] = 0.0
|
||||
|
||||
for i in range(vertex_count - 1):
|
||||
for _ in range(vertex_count - 1):
|
||||
for j in range(edge_count):
|
||||
u, v, w = (graph[j][k] for k in ["src", "dst", "weight"])
|
||||
|
||||
|
|
|
@ -19,23 +19,23 @@ def min_dist(mdist, vset, v):
|
|||
|
||||
|
||||
def dijkstra(graph, v, src):
|
||||
mdist = [float("inf") for i in range(v)]
|
||||
vset = [False for i in range(v)]
|
||||
mdist = [float("inf") for _ in range(v)]
|
||||
vset = [False for _ in range(v)]
|
||||
mdist[src] = 0.0
|
||||
|
||||
for i in range(v - 1):
|
||||
for _ in range(v - 1):
|
||||
u = min_dist(mdist, vset, v)
|
||||
vset[u] = True
|
||||
|
||||
for v in range(v):
|
||||
for i in range(v):
|
||||
if (
|
||||
(not vset[v])
|
||||
and graph[u][v] != float("inf")
|
||||
and mdist[u] + graph[u][v] < mdist[v]
|
||||
(not vset[i])
|
||||
and graph[u][i] != float("inf")
|
||||
and mdist[u] + graph[u][i] < mdist[i]
|
||||
):
|
||||
mdist[v] = mdist[u] + graph[u][v]
|
||||
mdist[i] = mdist[u] + graph[u][i]
|
||||
|
||||
print_dist(mdist, v)
|
||||
print_dist(mdist, i)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -79,7 +79,7 @@ def get_nodes(frequency_table):
|
|||
{'11111': ['ab', 'ac', 'df', 'bd', 'bc']}
|
||||
"""
|
||||
nodes = {}
|
||||
for i, item in enumerate(frequency_table):
|
||||
for _, item in enumerate(frequency_table):
|
||||
nodes.setdefault(item[2], []).append(item[0])
|
||||
return nodes
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ def longest_distance(graph):
|
|||
queue = []
|
||||
long_dist = [1] * len(graph)
|
||||
|
||||
for key, values in graph.items():
|
||||
for values in graph.values():
|
||||
for i in values:
|
||||
indegree[i] += 1
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ def topological_sort(graph):
|
|||
topo = []
|
||||
cnt = 0
|
||||
|
||||
for key, values in graph.items():
|
||||
for values in graph.values():
|
||||
for i in values:
|
||||
indegree[i] += 1
|
||||
|
||||
|
|
|
@ -91,7 +91,7 @@ def prisms_algorithm(l): # noqa: E741
|
|||
distance_tv[x[0]] = x[1]
|
||||
heapify(distance_tv, positions)
|
||||
|
||||
for i in range(1, len(l)):
|
||||
for _ in range(1, len(l)):
|
||||
vertex = delete_minimum(distance_tv, positions)
|
||||
if visited[vertex] == 0:
|
||||
tree_edges.append((nbr_tv[vertex], vertex))
|
||||
|
|
|
@ -41,7 +41,7 @@ def page_rank(nodes, limit=3, d=0.85):
|
|||
|
||||
for i in range(limit):
|
||||
print(f"======= Iteration {i + 1} =======")
|
||||
for j, node in enumerate(nodes):
|
||||
for _, node in enumerate(nodes):
|
||||
ranks[node.name] = (1 - d) + d * sum(
|
||||
ranks[ib] / outbounds[ib] for ib in node.inbound
|
||||
)
|
||||
|
|
|
@ -39,10 +39,10 @@ if __name__ == "__main__":
|
|||
# n - no of nodes, m - no of edges
|
||||
n, m = list(map(int, input().strip().split()))
|
||||
|
||||
graph: list[list[int]] = [[] for i in range(n)] # graph
|
||||
graph: list[list[int]] = [[] for _ in range(n)] # graph
|
||||
reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph
|
||||
# input graph data (edges)
|
||||
for i in range(m):
|
||||
for _ in range(m):
|
||||
u, v = list(map(int, input().strip().split()))
|
||||
graph[u].append(v)
|
||||
reversed_graph[v].append(u)
|
||||
|
|
|
@ -41,7 +41,7 @@ def optimal_merge_pattern(files: list) -> float:
|
|||
while len(files) > 1:
|
||||
temp = 0
|
||||
# Consider two files with minimum cost to be merged
|
||||
for i in range(2):
|
||||
for _ in range(2):
|
||||
min_index = files.index(min(files))
|
||||
temp += files[min_index]
|
||||
files.pop(min_index)
|
||||
|
|
|
@ -53,7 +53,7 @@ def pull():
|
|||
key = machine_time % m
|
||||
|
||||
# Evolution (Time Length)
|
||||
for i in range(0, t):
|
||||
for _ in range(0, t):
|
||||
# Variables (Position + Parameters)
|
||||
r = params_space[key]
|
||||
value = buffer_space[key]
|
||||
|
|
|
@ -48,7 +48,7 @@ if __name__ == "__main__":
|
|||
break
|
||||
except Exception as error:
|
||||
print(error)
|
||||
for i in range(token):
|
||||
for _ in range(token):
|
||||
rotator()
|
||||
for j in decode:
|
||||
engine(j)
|
||||
|
|
|
@ -47,7 +47,7 @@ def main() -> None:
|
|||
epochs = 3
|
||||
alpha = 0.5
|
||||
|
||||
for i in range(epochs):
|
||||
for _ in range(epochs):
|
||||
for j in range(len(training_samples)):
|
||||
|
||||
# training sample
|
||||
|
|
|
@ -35,7 +35,7 @@ def trapezoidal_area(
|
|||
x1 = x_start
|
||||
fx1 = fnc(x_start)
|
||||
area = 0.0
|
||||
for i in range(steps):
|
||||
for _ in range(steps):
|
||||
# Approximates small segments of curve as linear and solve
|
||||
# for trapezoidal area
|
||||
x2 = (x_end - x_start) / steps + x1
|
||||
|
|
|
@ -40,7 +40,7 @@ def line_length(
|
|||
fx1 = fnc(x_start)
|
||||
length = 0.0
|
||||
|
||||
for i in range(steps):
|
||||
for _ in range(steps):
|
||||
|
||||
# Approximates curve as a sequence of linear lines and sums their length
|
||||
x2 = (x_end - x_start) / steps + x1
|
||||
|
|
|
@ -31,7 +31,7 @@ def lucas_lehmer_test(p: int) -> bool:
|
|||
|
||||
s = 4
|
||||
m = (1 << p) - 1
|
||||
for i in range(p - 2):
|
||||
for _ in range(p - 2):
|
||||
s = ((s * s) - 2) % m
|
||||
return s == 0
|
||||
|
||||
|
|
|
@ -50,7 +50,7 @@ def dynamic_lucas_number(n_th_number: int) -> int:
|
|||
if not isinstance(n_th_number, int):
|
||||
raise TypeError("dynamic_lucas_number accepts only integer arguments.")
|
||||
a, b = 2, 1
|
||||
for i in range(n_th_number):
|
||||
for _ in range(n_th_number):
|
||||
a, b = b, a + b
|
||||
return a
|
||||
|
||||
|
|
|
@ -33,7 +33,7 @@ def is_prime_big(n, prec=1000):
|
|||
b = bin_exp_mod(a, d, n)
|
||||
if b != 1:
|
||||
flag = True
|
||||
for i in range(exp):
|
||||
for _ in range(exp):
|
||||
if b == n - 1:
|
||||
flag = False
|
||||
break
|
||||
|
|
|
@ -35,7 +35,7 @@ def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]:
|
|||
"""
|
||||
dices = [Dice() for i in range(num_dice)]
|
||||
count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1)
|
||||
for i in range(num_throws):
|
||||
for _ in range(num_throws):
|
||||
count_of_sum[sum(dice.roll() for dice in dices)] += 1
|
||||
probability = [round((count * 100) / num_throws, 2) for count in count_of_sum]
|
||||
return probability[num_dice:] # remove probability of sums that never appear
|
||||
|
|
|
@ -39,7 +39,7 @@ def trapezoidal_area(
|
|||
fx1 = fnc(x_start)
|
||||
area = 0.0
|
||||
|
||||
for i in range(steps):
|
||||
for _ in range(steps):
|
||||
|
||||
# Approximates small segments of curve as linear and solve
|
||||
# for trapezoidal area
|
||||
|
|
|
@ -47,7 +47,7 @@ def estimate_pi(number_of_simulations: int) -> float:
|
|||
raise ValueError("At least one simulation is necessary to estimate PI.")
|
||||
|
||||
number_in_unit_circle = 0
|
||||
for simulation_index in range(number_of_simulations):
|
||||
for _ in range(number_of_simulations):
|
||||
random_point = Point.random_unit_square()
|
||||
|
||||
if random_point.is_in_unit_circle():
|
||||
|
|
|
@ -73,7 +73,7 @@ def pollard_rho(
|
|||
"""
|
||||
return (pow(value, 2) + step) % modulus
|
||||
|
||||
for attempt in range(attempts):
|
||||
for _ in range(attempts):
|
||||
# These track the position within the cycle detection logic.
|
||||
tortoise = seed
|
||||
hare = seed
|
||||
|
|
|
@ -406,14 +406,14 @@ def kg_v(number1, number2):
|
|||
count1 = prime_fac_1.count(n)
|
||||
count2 = prime_fac_2.count(n)
|
||||
|
||||
for i in range(max(count1, count2)):
|
||||
for _ in range(max(count1, count2)):
|
||||
ans *= n
|
||||
|
||||
else:
|
||||
|
||||
count1 = prime_fac_1.count(n)
|
||||
|
||||
for i in range(count1):
|
||||
for _ in range(count1):
|
||||
ans *= n
|
||||
|
||||
done.append(n)
|
||||
|
@ -425,7 +425,7 @@ def kg_v(number1, number2):
|
|||
|
||||
count2 = prime_fac_2.count(n)
|
||||
|
||||
for i in range(count2):
|
||||
for _ in range(count2):
|
||||
ans *= n
|
||||
|
||||
done.append(n)
|
||||
|
@ -637,7 +637,7 @@ def fib(n):
|
|||
fib1 = 1
|
||||
ans = 1 # this will be return
|
||||
|
||||
for i in range(n - 1):
|
||||
for _ in range(n - 1):
|
||||
|
||||
tmp = ans
|
||||
ans += fib1
|
||||
|
|
|
@ -49,7 +49,7 @@ def proth(number: int) -> int:
|
|||
proth_index = 2
|
||||
increment = 3
|
||||
for block in range(1, block_index):
|
||||
for move in range(increment):
|
||||
for _ in range(increment):
|
||||
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])
|
||||
proth_index += 1
|
||||
increment *= 2
|
||||
|
|
|
@ -49,7 +49,7 @@ def square_root_iterative(
|
|||
|
||||
value = get_initial_point(a)
|
||||
|
||||
for i in range(max_iter):
|
||||
for _ in range(max_iter):
|
||||
prev_value = value
|
||||
value = value - fx(value, a) / fx_derivative(value)
|
||||
if abs(prev_value - value) < tolerance:
|
||||
|
|
|
@ -32,7 +32,7 @@ def ugly_numbers(n: int) -> int:
|
|||
next_3 = ugly_nums[i3] * 3
|
||||
next_5 = ugly_nums[i5] * 5
|
||||
|
||||
for i in range(1, n):
|
||||
for _ in range(1, n):
|
||||
next_num = min(next_2, next_3, next_5)
|
||||
ugly_nums.append(next_num)
|
||||
if next_num == next_2:
|
||||
|
|
|
@ -351,7 +351,7 @@ class Matrix:
|
|||
"Only invertable matrices can be raised to a negative power"
|
||||
)
|
||||
result = self
|
||||
for i in range(other - 1):
|
||||
for _ in range(other - 1):
|
||||
result *= self
|
||||
return result
|
||||
|
||||
|
|
|
@ -65,7 +65,7 @@ def nth_fibonacci_bruteforce(n: int) -> int:
|
|||
return n
|
||||
fib0 = 0
|
||||
fib1 = 1
|
||||
for i in range(2, n + 1):
|
||||
for _ in range(2, n + 1):
|
||||
fib0, fib1 = fib1, fib0 + fib1
|
||||
return fib1
|
||||
|
||||
|
|
|
@ -128,7 +128,7 @@ class BPNN:
|
|||
self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1)
|
||||
|
||||
x_shape = np.shape(xdata)
|
||||
for round_i in range(train_round):
|
||||
for _ in range(train_round):
|
||||
all_loss = 0
|
||||
for row in range(x_shape[0]):
|
||||
_xdata = np.asmatrix(xdata[row, :]).T
|
||||
|
|
|
@ -69,7 +69,7 @@ class Perceptron:
|
|||
for sample in self.sample:
|
||||
sample.insert(0, self.bias)
|
||||
|
||||
for i in range(self.col_sample):
|
||||
for _ in range(self.col_sample):
|
||||
self.weight.append(random.random())
|
||||
|
||||
self.weight.insert(0, self.bias)
|
||||
|
|
|
@ -303,7 +303,7 @@ class LFUCache(Generic[T, U]):
|
|||
def cache_info() -> LFUCache[T, U]:
|
||||
return cls.decorator_function_to_instance_map[func]
|
||||
|
||||
setattr(cache_decorator_wrapper, "cache_info", cache_info)
|
||||
setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010
|
||||
|
||||
return cache_decorator_wrapper
|
||||
|
||||
|
|
|
@ -321,7 +321,7 @@ class LRUCache(Generic[T, U]):
|
|||
def cache_info() -> LRUCache[T, U]:
|
||||
return cls.decorator_function_to_instance_map[func]
|
||||
|
||||
setattr(cache_decorator_wrapper, "cache_info", cache_info)
|
||||
setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010
|
||||
|
||||
return cache_decorator_wrapper
|
||||
|
||||
|
|
|
@ -8,9 +8,9 @@ def floyd(n):
|
|||
n : size of pattern
|
||||
"""
|
||||
for i in range(0, n):
|
||||
for j in range(0, n - i - 1): # printing spaces
|
||||
for _ in range(0, n - i - 1): # printing spaces
|
||||
print(" ", end="")
|
||||
for k in range(0, i + 1): # printing stars
|
||||
for _ in range(0, i + 1): # printing stars
|
||||
print("* ", end="")
|
||||
print()
|
||||
|
||||
|
@ -22,10 +22,10 @@ def reverse_floyd(n):
|
|||
n : size of pattern
|
||||
"""
|
||||
for i in range(n, 0, -1):
|
||||
for j in range(i, 0, -1): # printing stars
|
||||
for _ in range(i, 0, -1): # printing stars
|
||||
print("* ", end="")
|
||||
print()
|
||||
for k in range(n - i + 1, 0, -1): # printing spaces
|
||||
for _ in range(n - i + 1, 0, -1): # printing spaces
|
||||
print(" ", end="")
|
||||
|
||||
|
||||
|
|
|
@ -77,7 +77,7 @@ def procentual_proximity(
|
|||
final_scores: list[float] = [0 for i in range(len(score_lists[0]))]
|
||||
|
||||
# generate final scores
|
||||
for i, slist in enumerate(score_lists):
|
||||
for slist in score_lists:
|
||||
for j, ele in enumerate(slist):
|
||||
final_scores[j] = final_scores[j] + ele
|
||||
|
||||
|
|
|
@ -145,7 +145,7 @@ def transformation_matrix(velocity: float) -> np.array:
|
|||
|
||||
|
||||
def transform(
|
||||
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True
|
||||
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
|
||||
) -> np.array:
|
||||
"""
|
||||
>>> transform(29979245,np.array([1,2,3,4]), False)
|
||||
|
|
|
@ -310,7 +310,7 @@ def example_3() -> BodySystem:
|
|||
"""
|
||||
|
||||
bodies = []
|
||||
for i in range(10):
|
||||
for _ in range(10):
|
||||
velocity_x = random.uniform(-0.5, 0.5)
|
||||
velocity_y = random.uniform(-0.5, 0.5)
|
||||
|
||||
|
|
|
@ -36,7 +36,7 @@ def solution():
|
|||
"""
|
||||
with open(os.path.dirname(__file__) + "/grid.txt") as f:
|
||||
l = [] # noqa: E741
|
||||
for i in range(20):
|
||||
for _ in range(20):
|
||||
l.append([int(x) for x in f.readline().split()])
|
||||
|
||||
maximum = 0
|
||||
|
|
|
@ -45,7 +45,7 @@ def solution(n: int = 1000) -> int:
|
|||
f = f1 + f2
|
||||
f1, f2 = f2, f
|
||||
index += 1
|
||||
for j in str(f):
|
||||
for _ in str(f):
|
||||
i += 1
|
||||
if i == n:
|
||||
break
|
||||
|
|
|
@ -41,7 +41,7 @@ def solution(numerator: int = 1, digit: int = 1000) -> int:
|
|||
for divide_by_number in range(numerator, digit + 1):
|
||||
has_been_divided: list[int] = []
|
||||
now_divide = numerator
|
||||
for division_cycle in range(1, digit + 1):
|
||||
for _ in range(1, digit + 1):
|
||||
if now_divide in has_been_divided:
|
||||
if longest_list_length < len(has_been_divided):
|
||||
longest_list_length = len(has_been_divided)
|
||||
|
|
|
@ -58,7 +58,7 @@ def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int:
|
|||
# calculate base↑↑height by right-assiciative repeated modular
|
||||
# exponentiation
|
||||
result = base
|
||||
for i in range(1, height):
|
||||
for _ in range(1, height):
|
||||
result = _modexpt(base, result, 10**digits)
|
||||
|
||||
return result
|
||||
|
|
|
@ -49,7 +49,7 @@ def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]:
|
|||
"""
|
||||
coefficients = {1}
|
||||
previous_coefficients = [1]
|
||||
for step in range(2, depth + 1):
|
||||
for _ in range(2, depth + 1):
|
||||
coefficients_begins_one = previous_coefficients + [0]
|
||||
coefficients_ends_one = [0] + previous_coefficients
|
||||
previous_coefficients = []
|
||||
|
|
|
@ -205,7 +205,7 @@ class MLFQ:
|
|||
"""
|
||||
finished: deque[Process] = deque() # sequence deque of terminated process
|
||||
# just for 1 cycle and unfinished processes will go back to queue
|
||||
for i in range(len(ready_queue)):
|
||||
for _ in range(len(ready_queue)):
|
||||
cp = ready_queue.popleft() # current process
|
||||
|
||||
# if process's arrival time is later than current time, update current time
|
||||
|
|
|
@ -15,7 +15,7 @@ def double_sort(lst):
|
|||
True
|
||||
"""
|
||||
no_of_elements = len(lst)
|
||||
for i in range(
|
||||
for _ in range(
|
||||
0, int(((no_of_elements - 1) / 2) + 1)
|
||||
): # we don't need to traverse to end of list as
|
||||
for j in range(0, no_of_elements - 1):
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
import webbrowser
|
||||
from sys import argv
|
||||
from urllib.parse import quote, parse_qs
|
||||
from fake_useragent import UserAgent
|
||||
from urllib.parse import parse_qs, quote
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from fake_useragent import UserAgent
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(argv) > 1:
|
||||
|
@ -18,9 +18,7 @@ if __name__ == "__main__":
|
|||
|
||||
res = requests.get(
|
||||
url,
|
||||
headers={
|
||||
"User-Agent": str(UserAgent().random)
|
||||
},
|
||||
headers={"User-Agent": str(UserAgent().random)},
|
||||
)
|
||||
|
||||
try:
|
||||
|
|
Loading…
Reference in New Issue
Block a user