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