From 6796e27ef03ab8f0f11f0cb81feb866022b007d2 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 12:30:53 +0100 Subject: [PATCH 01/24] ci(pre-commit): Add ``flake8-builtins`` additional dependency to ``pre-commit`` (#7104) --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2f6a92814c66..861d7ee18cb4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -40,7 +40,7 @@ repos: - --ignore=E203,W503 - --max-complexity=25 - --max-line-length=88 - additional_dependencies: [pep8-naming] + additional_dependencies: [pep8-naming, flake8-builtins] - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.982 From 771e65bdd6f632898efff7ca8af45cb02b4edbd5 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 12:31:31 +0100 Subject: [PATCH 02/24] refactor: Fix ``flake8-builtins`` (#7104) --- arithmetic_analysis/gaussian_elimination.py | 6 +++--- arithmetic_analysis/jacobi_iteration_method.py | 6 +++--- audio_filters/show_response.py | 8 ++++---- backtracking/hamiltonian_cycle.py | 6 +++--- data_structures/binary_tree/avl_tree.py | 2 +- data_structures/binary_tree/fenwick_tree.py | 8 ++++---- data_structures/heap/heap.py | 2 +- data_structures/linked_list/__init__.py | 2 +- data_structures/linked_list/merge_two_lists.py | 2 +- data_structures/linked_list/singly_linked_list.py | 4 ++-- data_structures/queue/double_ended_queue.py | 10 +++++----- data_structures/stacks/next_greater_element.py | 12 ++++++------ digital_image_processing/index_calculation.py | 6 +++--- dynamic_programming/optimal_binary_search_tree.py | 6 +++--- graphs/a_star.py | 8 ++++---- graphs/dijkstra.py | 4 ++-- graphs/finding_bridges.py | 14 +++++++------- graphs/prim.py | 4 ++-- hashes/djb2.py | 6 +++--- hashes/sdbm.py | 6 +++--- linear_algebra/src/lib.py | 2 +- maths/armstrong_numbers.py | 12 ++++++------ maths/bailey_borwein_plouffe.py | 6 +++--- maths/kadanes.py | 8 ++++---- maths/prime_numbers.py | 14 +++++++------- maths/sum_of_arithmetic_series.py | 4 ++-- neural_network/2_hidden_layers_neural_network.py | 10 ++++++---- neural_network/convolution_neural_network.py | 10 +++++----- neural_network/perceptron.py | 4 ++-- other/lfu_cache.py | 6 ++++-- other/lru_cache.py | 6 ++++-- project_euler/problem_065/sol1.py | 4 ++-- project_euler/problem_070/sol1.py | 6 +++--- sorts/odd_even_sort.py | 10 +++++----- strings/snake_case_to_camel_pascal_case.py | 8 ++++---- 35 files changed, 119 insertions(+), 113 deletions(-) diff --git a/arithmetic_analysis/gaussian_elimination.py b/arithmetic_analysis/gaussian_elimination.py index 89ed3b323d03..65c5a60bb45d 100644 --- a/arithmetic_analysis/gaussian_elimination.py +++ b/arithmetic_analysis/gaussian_elimination.py @@ -33,11 +33,11 @@ def retroactive_resolution( x: NDArray[float64] = np.zeros((rows, 1), dtype=float) for row in reversed(range(rows)): - sum = 0 + count = 0 for col in range(row + 1, columns): - sum += coefficients[row, col] * x[col] + count += coefficients[row, col] * x[col] - x[row, 0] = (vector[row] - sum) / coefficients[row, row] + x[row, 0] = (vector[row] - count) / coefficients[row, row] return x diff --git a/arithmetic_analysis/jacobi_iteration_method.py b/arithmetic_analysis/jacobi_iteration_method.py index 4336aaa91623..59d4cdb97d8e 100644 --- a/arithmetic_analysis/jacobi_iteration_method.py +++ b/arithmetic_analysis/jacobi_iteration_method.py @@ -147,14 +147,14 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool: is_diagonally_dominant = True for i in range(0, rows): - sum = 0 + count = 0 for j in range(0, cols - 1): if i == j: continue else: - sum += table[i][j] + count += table[i][j] - if table[i][i] <= sum: + if table[i][i] <= count: raise ValueError("Coefficient matrix is not strictly diagonally dominant") return is_diagonally_dominant diff --git a/audio_filters/show_response.py b/audio_filters/show_response.py index 6e2731a58419..097b8152b4e6 100644 --- a/audio_filters/show_response.py +++ b/audio_filters/show_response.py @@ -34,7 +34,7 @@ def get_bounds( return lowest, highest -def show_frequency_response(filter: FilterType, samplerate: int) -> None: +def show_frequency_response(filter_type: FilterType, samplerate: int) -> None: """ Show frequency response of a filter @@ -45,7 +45,7 @@ def show_frequency_response(filter: FilterType, samplerate: int) -> None: size = 512 inputs = [1] + [0] * (size - 1) - outputs = [filter.process(item) for item in inputs] + outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler @@ -66,7 +66,7 @@ def show_frequency_response(filter: FilterType, samplerate: int) -> None: plt.show() -def show_phase_response(filter: FilterType, samplerate: int) -> None: +def show_phase_response(filter_type: FilterType, samplerate: int) -> None: """ Show phase response of a filter @@ -77,7 +77,7 @@ def show_phase_response(filter: FilterType, samplerate: int) -> None: size = 512 inputs = [1] + [0] * (size - 1) - outputs = [filter.process(item) for item in inputs] + outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler diff --git a/backtracking/hamiltonian_cycle.py b/backtracking/hamiltonian_cycle.py index 500e993e5c8b..4c6ae46799f4 100644 --- a/backtracking/hamiltonian_cycle.py +++ b/backtracking/hamiltonian_cycle.py @@ -95,10 +95,10 @@ def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step - for next in range(0, len(graph)): - if valid_connection(graph, next, curr_ind, path): + for next_ver in range(0, len(graph)): + if valid_connection(graph, next_ver, curr_ind, path): # Insert current vertex into path as next transition - path[curr_ind] = next + path[curr_ind] = next_ver # Validate created path if util_hamilton_cycle(graph, path, curr_ind + 1): return True diff --git a/data_structures/binary_tree/avl_tree.py b/data_structures/binary_tree/avl_tree.py index 2f4bd60d9749..320e7ed0d792 100644 --- a/data_structures/binary_tree/avl_tree.py +++ b/data_structures/binary_tree/avl_tree.py @@ -33,7 +33,7 @@ def pop(self) -> Any: def count(self) -> int: return self.tail - self.head - def print(self) -> None: + def print_queue(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail]) diff --git a/data_structures/binary_tree/fenwick_tree.py b/data_structures/binary_tree/fenwick_tree.py index 96020d1427af..60992c95ed2b 100644 --- a/data_structures/binary_tree/fenwick_tree.py +++ b/data_structures/binary_tree/fenwick_tree.py @@ -46,7 +46,7 @@ def init(self, arr: list[int]) -> None: self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): - j = self.next(i) + j = self.next_index(i) if j < self.size: self.tree[j] += self.tree[i] @@ -64,13 +64,13 @@ def get_array(self) -> list[int]: """ arr = self.tree[:] for i in range(self.size - 1, 0, -1): - j = self.next(i) + j = self.next_index(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod - def next(index: int) -> int: + def next_index(index: int) -> int: return index + (index & (-index)) @staticmethod @@ -102,7 +102,7 @@ def add(self, index: int, value: int) -> None: return while index < self.size: self.tree[index] += value - index = self.next(index) + index = self.next_index(index) def update(self, index: int, value: int) -> None: """ diff --git a/data_structures/heap/heap.py b/data_structures/heap/heap.py index 4c19747ec823..ac6e6caa58cc 100644 --- a/data_structures/heap/heap.py +++ b/data_structures/heap/heap.py @@ -88,7 +88,7 @@ def build_max_heap(self, collection: Iterable[float]) -> None: for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) - def max(self) -> float: + def get_max(self) -> float: """return the max in the heap""" if self.heap_size >= 1: return self.h[0] diff --git a/data_structures/linked_list/__init__.py b/data_structures/linked_list/__init__.py index 6ba660231ae1..85660a6d2c27 100644 --- a/data_structures/linked_list/__init__.py +++ b/data_structures/linked_list/__init__.py @@ -11,7 +11,7 @@ class Node: - def __init__(self, item: Any, next: Any) -> None: + def __init__(self, item: Any, next: Any) -> None: # noqa: A002 self.item = item self.next = next diff --git a/data_structures/linked_list/merge_two_lists.py b/data_structures/linked_list/merge_two_lists.py index 43dd461867f1..52bc9c4c1e24 100644 --- a/data_structures/linked_list/merge_two_lists.py +++ b/data_structures/linked_list/merge_two_lists.py @@ -13,7 +13,7 @@ @dataclass class Node: data: int - next: Node | None + next: Node | None # noqa: A003 class SortedLinkedList: diff --git a/data_structures/linked_list/singly_linked_list.py b/data_structures/linked_list/singly_linked_list.py index a4156b650776..59d7c512bad7 100644 --- a/data_structures/linked_list/singly_linked_list.py +++ b/data_structures/linked_list/singly_linked_list.py @@ -392,7 +392,7 @@ def test_singly_linked_list_2() -> None: This section of the test used varying data types for input. >>> test_singly_linked_list_2() """ - input = [ + test_input = [ -9, 100, Node(77345112), @@ -410,7 +410,7 @@ def test_singly_linked_list_2() -> None: ] linked_list = LinkedList() - for i in input: + for i in test_input: linked_list.insert_tail(i) # Check if it's empty or not diff --git a/data_structures/queue/double_ended_queue.py b/data_structures/queue/double_ended_queue.py index f38874788df1..451e8b80f8af 100644 --- a/data_structures/queue/double_ended_queue.py +++ b/data_structures/queue/double_ended_queue.py @@ -42,7 +42,7 @@ class _Node: """ val: Any = None - next: Deque._Node | None = None + next: Deque._Node | None = None # noqa: A003 prev: Deque._Node | None = None class _Iterator: @@ -179,7 +179,7 @@ def appendleft(self, val: Any) -> None: # make sure there were no errors assert not self.is_empty(), "Error on appending value." - def extend(self, iter: Iterable[Any]) -> None: + def extend(self, iterable: Iterable[Any]) -> None: """ Appends every value of iter to the end of the deque. Time complexity: O(n) @@ -205,10 +205,10 @@ def extend(self, iter: Iterable[Any]) -> None: >>> list(our_deque_2) == list(deque_collections_2) True """ - for val in iter: + for val in iterable: self.append(val) - def extendleft(self, iter: Iterable[Any]) -> None: + def extendleft(self, iterable: Iterable[Any]) -> None: """ Appends every value of iter to the beginning of the deque. Time complexity: O(n) @@ -234,7 +234,7 @@ def extendleft(self, iter: Iterable[Any]) -> None: >>> list(our_deque_2) == list(deque_collections_2) True """ - for val in iter: + for val in iterable: self.appendleft(val) def pop(self) -> Any: diff --git a/data_structures/stacks/next_greater_element.py b/data_structures/stacks/next_greater_element.py index 5bab7c609b67..8d7ba4492a09 100644 --- a/data_structures/stacks/next_greater_element.py +++ b/data_structures/stacks/next_greater_element.py @@ -17,12 +17,12 @@ def next_greatest_element_slow(arr: list[float]) -> list[float]: arr_size = len(arr) for i in range(arr_size): - next: float = -1 + _next: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: - next = arr[j] + _next = arr[j] break - result.append(next) + result.append(_next) return result @@ -36,12 +36,12 @@ def next_greatest_element_fast(arr: list[float]) -> list[float]: """ result = [] for i, outer in enumerate(arr): - next: float = -1 + _next: float = -1 for inner in arr[i + 1 :]: if outer < inner: - next = inner + _next = inner break - result.append(next) + result.append(_next) return result diff --git a/digital_image_processing/index_calculation.py b/digital_image_processing/index_calculation.py index 2f8fdc066919..5269fe8bbf4d 100644 --- a/digital_image_processing/index_calculation.py +++ b/digital_image_processing/index_calculation.py @@ -497,9 +497,9 @@ def s(self): https://www.indexdatabase.de/db/i-single.php?id=77 :return: index """ - max = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) - min = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) - return (max - min) / max + _max = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) + _min = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) + return (_max - _min) / _max def _if(self): """ diff --git a/dynamic_programming/optimal_binary_search_tree.py b/dynamic_programming/optimal_binary_search_tree.py index 0d94c1b61d39..b4f1181ac11c 100644 --- a/dynamic_programming/optimal_binary_search_tree.py +++ b/dynamic_programming/optimal_binary_search_tree.py @@ -104,7 +104,7 @@ def find_optimal_binary_search_tree(nodes): dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes # array - sum = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] + total = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # stores tree roots that will be used later for constructing binary search tree root = [[i if i == j else 0 for j in range(n)] for i in range(n)] @@ -113,14 +113,14 @@ def find_optimal_binary_search_tree(nodes): j = i + interval_length - 1 dp[i][j] = sys.maxsize # set the value to "infinity" - sum[i][j] = sum[i][j - 1] + freqs[j] + total[i][j] = total[i][j - 1] + freqs[j] # Apply Knuth's optimization # Loop without optimization: for r in range(i, j + 1): for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree - cost = left + sum[i][j] + right + cost = left + total[i][j] + right if dp[i][j] > cost: dp[i][j] = cost diff --git a/graphs/a_star.py b/graphs/a_star.py index e0f24734a4cb..793ba3bda6b2 100644 --- a/graphs/a_star.py +++ b/graphs/a_star.py @@ -40,10 +40,10 @@ def search( else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() - next = cell.pop() - x = next[2] - y = next[3] - g = next[1] + next_cell = cell.pop() + x = next_cell[2] + y = next_cell[3] + g = next_cell[1] if x == goal[0] and y == goal[1]: found = True diff --git a/graphs/dijkstra.py b/graphs/dijkstra.py index 62c60f2c6be6..b0bdfab60649 100644 --- a/graphs/dijkstra.py +++ b/graphs/dijkstra.py @@ -56,8 +56,8 @@ def dijkstra(graph, start, end): for v, c in graph[u]: if v in visited: continue - next = cost + c - heapq.heappush(heap, (next, v)) + next_item = cost + c + heapq.heappush(heap, (next_item, v)) return -1 diff --git a/graphs/finding_bridges.py b/graphs/finding_bridges.py index 3813c4ebbd2a..c17606745ad8 100644 --- a/graphs/finding_bridges.py +++ b/graphs/finding_bridges.py @@ -72,22 +72,22 @@ def compute_bridges(graph: dict[int, list[int]]) -> list[tuple[int, int]]: [] """ - id = 0 + id_ = 0 n = len(graph) # No of vertices in graph low = [0] * n visited = [False] * n - def dfs(at, parent, bridges, id): + def dfs(at, parent, bridges, id_): visited[at] = True - low[at] = id - id += 1 + low[at] = id_ + id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: - dfs(to, at, bridges, id) + dfs(to, at, bridges, id_) low[at] = min(low[at], low[to]) - if id <= low[to]: + if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at)) else: # This edge is a back edge and cannot be a bridge @@ -96,7 +96,7 @@ def dfs(at, parent, bridges, id): bridges: list[tuple[int, int]] = [] for i in range(n): if not visited[i]: - dfs(i, -1, bridges, id) + dfs(i, -1, bridges, id_) return bridges diff --git a/graphs/prim.py b/graphs/prim.py index 55d0fbfa8e96..344967bebed8 100644 --- a/graphs/prim.py +++ b/graphs/prim.py @@ -13,7 +13,7 @@ class Vertex: """Class Vertex.""" - def __init__(self, id): + def __init__(self, _id): """ Arguments: id - input an id to identify the vertex @@ -21,7 +21,7 @@ def __init__(self, id): neighbors - a list of the vertices it is linked to edges - a dict to store the edges's weight """ - self.id = str(id) + self.id = str(_id) self.key = None self.pi = None self.neighbors = [] diff --git a/hashes/djb2.py b/hashes/djb2.py index 2d1c9aabb1fb..1babf07e0769 100644 --- a/hashes/djb2.py +++ b/hashes/djb2.py @@ -29,7 +29,7 @@ def djb2(s: str) -> int: >>> djb2('scramble bits') 1609059040 """ - hash = 5381 + _hash = 5381 for x in s: - hash = ((hash << 5) + hash) + ord(x) - return hash & 0xFFFFFFFF + _hash = ((_hash << 5) + _hash) + ord(x) + return _hash & 0xFFFFFFFF diff --git a/hashes/sdbm.py b/hashes/sdbm.py index daf292717f75..bbd31d630617 100644 --- a/hashes/sdbm.py +++ b/hashes/sdbm.py @@ -31,7 +31,7 @@ def sdbm(plain_text: str) -> int: >>> sdbm('scramble bits') 730247649148944819640658295400555317318720608290373040936089 """ - hash = 0 + _hash = 0 for plain_chr in plain_text: - hash = ord(plain_chr) + (hash << 6) + (hash << 16) - hash - return hash + _hash = ord(plain_chr) + (_hash << 6) + (_hash << 16) - _hash + return _hash diff --git a/linear_algebra/src/lib.py b/linear_algebra/src/lib.py index b9791c860a74..81658ae58b69 100644 --- a/linear_algebra/src/lib.py +++ b/linear_algebra/src/lib.py @@ -119,7 +119,7 @@ def __mul__(self, other: float | Vector) -> float | Vector: else: # error case raise Exception("invalid operand!") - def set(self, components: Collection[float]) -> None: + def set_components(self, components: Collection[float]) -> None: """ input: new components changes the components of the vector. diff --git a/maths/armstrong_numbers.py b/maths/armstrong_numbers.py index 65aebe93722e..6a519932f8ac 100644 --- a/maths/armstrong_numbers.py +++ b/maths/armstrong_numbers.py @@ -25,7 +25,7 @@ def armstrong_number(n: int) -> bool: return False # Initialization of sum and number of digits. - sum = 0 + _sum = 0 number_of_digits = 0 temp = n # Calculation of digits of the number @@ -36,9 +36,9 @@ def armstrong_number(n: int) -> bool: temp = n while temp > 0: rem = temp % 10 - sum += rem**number_of_digits + _sum += rem**number_of_digits temp //= 10 - return n == sum + return n == _sum def pluperfect_number(n: int) -> bool: @@ -55,7 +55,7 @@ def pluperfect_number(n: int) -> bool: # Init a "histogram" of the digits digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] digit_total = 0 - sum = 0 + _sum = 0 temp = n while temp > 0: temp, rem = divmod(temp, 10) @@ -63,9 +63,9 @@ def pluperfect_number(n: int) -> bool: digit_total += 1 for (cnt, i) in zip(digit_histogram, range(len(digit_histogram))): - sum += cnt * i**digit_total + _sum += cnt * i**digit_total - return n == sum + return n == _sum def narcissistic_number(n: int) -> bool: diff --git a/maths/bailey_borwein_plouffe.py b/maths/bailey_borwein_plouffe.py index b647ae56dbac..5bfd01202ea3 100644 --- a/maths/bailey_borwein_plouffe.py +++ b/maths/bailey_borwein_plouffe.py @@ -67,7 +67,7 @@ def _subsum( @param precision: same as precision in main function @return: floating-point number whose integer part is not important """ - sum = 0.0 + _sum = 0.0 for sum_index in range(digit_pos_to_extract + precision): denominator = 8 * sum_index + denominator_addend if sum_index < digit_pos_to_extract: @@ -79,8 +79,8 @@ def _subsum( ) else: exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index) - sum += exponential_term / denominator - return sum + _sum += exponential_term / denominator + return _sum if __name__ == "__main__": diff --git a/maths/kadanes.py b/maths/kadanes.py index d239d4a2589b..b23409e2b978 100644 --- a/maths/kadanes.py +++ b/maths/kadanes.py @@ -14,13 +14,13 @@ def negative_exist(arr: list) -> int: [-2, 0, 0, 0, 0] """ arr = arr or [0] - max = arr[0] + max_number = arr[0] for i in arr: if i >= 0: return 0 - elif max <= i: - max = i - return max + elif max_number <= i: + max_number = i + return max_number def kadanes(arr: list) -> int: diff --git a/maths/prime_numbers.py b/maths/prime_numbers.py index 7be4d3d95b0e..4e076fe317b4 100644 --- a/maths/prime_numbers.py +++ b/maths/prime_numbers.py @@ -2,7 +2,7 @@ from collections.abc import Generator -def slow_primes(max: int) -> Generator[int, None, None]: +def slow_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(slow_primes(0)) @@ -20,7 +20,7 @@ def slow_primes(max: int) -> Generator[int, None, None]: >>> list(slow_primes(10000))[-1] 9973 """ - numbers: Generator = (i for i in range(1, (max + 1))) + numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): if (i % j) == 0: @@ -29,7 +29,7 @@ def slow_primes(max: int) -> Generator[int, None, None]: yield i -def primes(max: int) -> Generator[int, None, None]: +def primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(primes(0)) @@ -47,7 +47,7 @@ def primes(max: int) -> Generator[int, None, None]: >>> list(primes(10000))[-1] 9973 """ - numbers: Generator = (i for i in range(1, (max + 1))) + numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) bound = int(math.sqrt(i)) + 1 @@ -58,7 +58,7 @@ def primes(max: int) -> Generator[int, None, None]: yield i -def fast_primes(max: int) -> Generator[int, None, None]: +def fast_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(fast_primes(0)) @@ -76,9 +76,9 @@ def fast_primes(max: int) -> Generator[int, None, None]: >>> list(fast_primes(10000))[-1] 9973 """ - numbers: Generator = (i for i in range(1, (max + 1), 2)) + numbers: Generator = (i for i in range(1, (max_n + 1), 2)) # It's useless to test even numbers as they will not be prime - if max > 2: + if max_n > 2: yield 2 # Because 2 will not be tested, it's necessary to yield it now for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 diff --git a/maths/sum_of_arithmetic_series.py b/maths/sum_of_arithmetic_series.py index e0e22760bfbe..3e01342531e6 100644 --- a/maths/sum_of_arithmetic_series.py +++ b/maths/sum_of_arithmetic_series.py @@ -8,9 +8,9 @@ def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float >>> sum_of_series(1, 10, 100) 49600.0 """ - sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) + _sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series - return sum + return _sum def main(): diff --git a/neural_network/2_hidden_layers_neural_network.py b/neural_network/2_hidden_layers_neural_network.py index 1cf78ec4c7c0..dd796f26712f 100644 --- a/neural_network/2_hidden_layers_neural_network.py +++ b/neural_network/2_hidden_layers_neural_network.py @@ -182,7 +182,7 @@ def train(self, output: numpy.ndarray, iterations: int, give_loss: bool) -> None loss = numpy.mean(numpy.square(output - self.feedforward())) print(f"Iteration {iteration} Loss: {loss}") - def predict(self, input: numpy.ndarray) -> int: + def predict(self, input_val: numpy.ndarray) -> int: """ Predict's the output for the given input values using the trained neural network. @@ -201,7 +201,7 @@ def predict(self, input: numpy.ndarray) -> int: """ # Input values for which the predictions are to be made. - self.array = input + self.array = input_val self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights) @@ -264,7 +264,7 @@ def example() -> int: True """ # Input values. - input = numpy.array( + test_input = numpy.array( ( [0, 0, 0], [0, 0, 1], @@ -282,7 +282,9 @@ def example() -> int: output = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.float64) # Calling neural network class. - neural_network = TwoHiddenLayerNeuralNetwork(input_array=input, output_array=output) + neural_network = TwoHiddenLayerNeuralNetwork( + input_array=test_input, output_array=output + ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index bbade1c417d0..9dfb6d091412 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -140,24 +140,24 @@ def convolute(self, data, convs, w_convs, thre_convs, conv_step): focus_list = np.asarray(focus1_list) return focus_list, data_featuremap - def pooling(self, featuremaps, size_pooling, type="average_pool"): + def pooling(self, featuremaps, size_pooling, pooling_type="average_pool"): # pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map / size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): - map = featuremaps[i_map] + feature_map = featuremaps[i_map] map_pooled = [] for i_focus in range(0, size_map, size_pooling): for j_focus in range(0, size_map, size_pooling): - focus = map[ + focus = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] - if type == "average_pool": + if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(focus)) - elif type == "max_pooling": + elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled) diff --git a/neural_network/perceptron.py b/neural_network/perceptron.py index 063be5ea554c..a2bfdb326d77 100644 --- a/neural_network/perceptron.py +++ b/neural_network/perceptron.py @@ -182,7 +182,7 @@ def sign(self, u: float) -> int: [0.2012, 0.2611, 5.4631], ] -exit = [ +target = [ -1, -1, -1, @@ -222,7 +222,7 @@ def sign(self, u: float) -> int: doctest.testmod() network = Perceptron( - sample=samples, target=exit, learning_rate=0.01, epoch_number=1000, bias=-1 + sample=samples, target=target, learning_rate=0.01, epoch_number=1000, bias=-1 ) network.training() print("Finished training perceptron") diff --git a/other/lfu_cache.py b/other/lfu_cache.py index 072d00ab58c8..8043956d6d57 100644 --- a/other/lfu_cache.py +++ b/other/lfu_cache.py @@ -250,7 +250,7 @@ def get(self, key: T) -> U | None: self.miss += 1 return None - def set(self, key: T, value: U) -> None: + def set_key(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ @@ -297,7 +297,9 @@ def cache_decorator_wrapper(*args: T) -> U: result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) - cls.decorator_function_to_instance_map[func].set(args[0], result) + cls.decorator_function_to_instance_map[func].set_key( + args[0], result + ) return result def cache_info() -> LFUCache[T, U]: diff --git a/other/lru_cache.py b/other/lru_cache.py index b68ae0a8e296..5dc10d065fbb 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -266,7 +266,7 @@ def get(self, key: T) -> U | None: self.miss += 1 return None - def set(self, key: T, value: U) -> None: + def set_key(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ @@ -315,7 +315,9 @@ def cache_decorator_wrapper(*args: T) -> U: result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) - cls.decorator_function_to_instance_map[func].set(args[0], result) + cls.decorator_function_to_instance_map[func].set_key( + args[0], result + ) return result def cache_info() -> LRUCache[T, U]: diff --git a/project_euler/problem_065/sol1.py b/project_euler/problem_065/sol1.py index 229769a77d07..0a00cf4773d7 100644 --- a/project_euler/problem_065/sol1.py +++ b/project_euler/problem_065/sol1.py @@ -71,7 +71,7 @@ def sum_digits(num: int) -> int: return digit_sum -def solution(max: int = 100) -> int: +def solution(max_n: int = 100) -> int: """ Returns the sum of the digits in the numerator of the max-th convergent of the continued fraction for e. @@ -86,7 +86,7 @@ def solution(max: int = 100) -> int: pre_numerator = 1 cur_numerator = 2 - for i in range(2, max + 1): + for i in range(2, max_n + 1): temp = pre_numerator e_cont = 2 * i // 3 if i % 3 == 0 else 1 pre_numerator = cur_numerator diff --git a/project_euler/problem_070/sol1.py b/project_euler/problem_070/sol1.py index d42b017cc476..273f37efc5fc 100644 --- a/project_euler/problem_070/sol1.py +++ b/project_euler/problem_070/sol1.py @@ -72,7 +72,7 @@ def has_same_digits(num1: int, num2: int) -> bool: return sorted(str(num1)) == sorted(str(num2)) -def solution(max: int = 10000000) -> int: +def solution(max_n: int = 10000000) -> int: """ Finds the value of n from 1 to max such that n/φ(n) produces a minimum. @@ -85,9 +85,9 @@ def solution(max: int = 10000000) -> int: min_numerator = 1 # i min_denominator = 0 # φ(i) - totients = get_totients(max + 1) + totients = get_totients(max_n + 1) - for i in range(2, max + 1): + for i in range(2, max_n + 1): t = totients[i] if i * min_denominator < min_numerator * t and has_same_digits(i, t): diff --git a/sorts/odd_even_sort.py b/sorts/odd_even_sort.py index 557337ee77bc..532f829499e8 100644 --- a/sorts/odd_even_sort.py +++ b/sorts/odd_even_sort.py @@ -20,21 +20,21 @@ def odd_even_sort(input_list: list) -> list: >>> odd_even_sort([1 ,2 ,3 ,4]) [1, 2, 3, 4] """ - sorted = False - while sorted is False: # Until all the indices are traversed keep looping - sorted = True + is_sorted = False + while is_sorted is False: # Until all the indices are traversed keep looping + is_sorted = True for i in range(0, len(input_list) - 1, 2): # iterating over all even indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order - sorted = False + is_sorted = False for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order - sorted = False + is_sorted = False return input_list diff --git a/strings/snake_case_to_camel_pascal_case.py b/strings/snake_case_to_camel_pascal_case.py index 7b2b61d1d1cf..563298966aa6 100644 --- a/strings/snake_case_to_camel_pascal_case.py +++ b/strings/snake_case_to_camel_pascal_case.py @@ -1,4 +1,4 @@ -def snake_to_camel_case(input: str, use_pascal: bool = False) -> str: +def snake_to_camel_case(raw_input: str, use_pascal: bool = False) -> str: """ Transforms a snake_case given string to camelCase (or PascalCase if indicated) (defaults to not use Pascal) @@ -26,14 +26,14 @@ def snake_to_camel_case(input: str, use_pascal: bool = False) -> str: ValueError: Expected boolean as use_pascal parameter, found """ - if not isinstance(input, str): - raise ValueError(f"Expected string as input, found {type(input)}") + if not isinstance(raw_input, str): + raise ValueError(f"Expected string as input, found {type(raw_input)}") if not isinstance(use_pascal, bool): raise ValueError( f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" ) - words = input.split("_") + words = raw_input.split("_") start_index = 0 if use_pascal else 1 From 4d8ac3e61f732d4f3ca50a79a247ea495d9a53a8 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 12:46:59 +0100 Subject: [PATCH 03/24] fix(lru_cache): Fix naming conventions in docstrings (#7104) --- other/lru_cache.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/other/lru_cache.py b/other/lru_cache.py index 5dc10d065fbb..67bcfa3867f4 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -150,8 +150,8 @@ class LRUCache(Generic[T, U]): >>> cache = LRUCache(2) - >>> cache.set(1, 1) - >>> cache.set(2, 2) + >>> cache.set_key(1, 1) + >>> cache.set_key(2, 2) >>> cache.get(1) 1 @@ -166,7 +166,7 @@ class LRUCache(Generic[T, U]): {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 2: Node: key: 2, val: 2, has next: True, has prev: True} - >>> cache.set(3, 3) + >>> cache.set_key(3, 3) >>> cache.list DoubleLinkedList, @@ -182,7 +182,7 @@ class LRUCache(Generic[T, U]): >>> cache.get(2) is None True - >>> cache.set(4, 4) + >>> cache.set_key(4, 4) >>> cache.get(1) is None True @@ -238,7 +238,7 @@ def __contains__(self, key: T) -> bool: >>> 1 in cache False - >>> cache.set(1, 1) + >>> cache.set_key(1, 1) >>> 1 in cache True From c69b7d9145b5daa4ebc973919b0490b99bafb4e5 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 12:50:05 +0100 Subject: [PATCH 04/24] ci(pre-commit): Order additional dependencies alphabetically (#7104) --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 861d7ee18cb4..e0de70b01883 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -40,7 +40,7 @@ repos: - --ignore=E203,W503 - --max-complexity=25 - --max-line-length=88 - additional_dependencies: [pep8-naming, flake8-builtins] + additional_dependencies: [flake8-builtins, pep8-naming] - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.982 From f13819e7740a42e5da9382b32005376a2d7c2450 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 12:54:27 +0100 Subject: [PATCH 05/24] fix(lfu_cache): Correct function name in docstring (#7104) --- other/lfu_cache.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/other/lfu_cache.py b/other/lfu_cache.py index 8043956d6d57..9966dde2ae99 100644 --- a/other/lfu_cache.py +++ b/other/lfu_cache.py @@ -166,14 +166,14 @@ class LFUCache(Generic[T, U]): or as a function decorator. >>> cache = LFUCache(2) - >>> cache.set(1, 1) - >>> cache.set(2, 2) + >>> cache.set_key(1, 1) + >>> cache.set_key(2, 2) >>> cache.get(1) 1 - >>> cache.set(3, 3) + >>> cache.set_key(3, 3) >>> cache.get(2) is None True - >>> cache.set(4, 4) + >>> cache.set_key(4, 4) >>> cache.get(1) is None True >>> cache.get(3) @@ -224,7 +224,7 @@ def __contains__(self, key: T) -> bool: >>> 1 in cache False - >>> cache.set(1, 1) + >>> cache.set_key(1, 1) >>> 1 in cache True """ From fa72f61fca89393a486c5bf2d887b5c77eb9ddab Mon Sep 17 00:00:00 2001 From: Caeden Date: Thu, 13 Oct 2022 12:57:46 +0100 Subject: [PATCH 06/24] Update strings/snake_case_to_camel_pascal_case.py Co-authored-by: Christian Clauss --- strings/snake_case_to_camel_pascal_case.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strings/snake_case_to_camel_pascal_case.py b/strings/snake_case_to_camel_pascal_case.py index 563298966aa6..e0150c2685ba 100644 --- a/strings/snake_case_to_camel_pascal_case.py +++ b/strings/snake_case_to_camel_pascal_case.py @@ -26,7 +26,7 @@ def snake_to_camel_case(raw_input: str, use_pascal: bool = False) -> str: ValueError: Expected boolean as use_pascal parameter, found """ - if not isinstance(raw_input, str): + if not isinstance(input_, str): raise ValueError(f"Expected string as input, found {type(raw_input)}") if not isinstance(use_pascal, bool): raise ValueError( From 1293059e20c1b5a4f3889bca961ec572f5f6ab09 Mon Sep 17 00:00:00 2001 From: Caeden Date: Thu, 13 Oct 2022 12:57:54 +0100 Subject: [PATCH 07/24] Update data_structures/stacks/next_greater_element.py Co-authored-by: Christian Clauss --- data_structures/stacks/next_greater_element.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/stacks/next_greater_element.py b/data_structures/stacks/next_greater_element.py index 8d7ba4492a09..c45668b075d7 100644 --- a/data_structures/stacks/next_greater_element.py +++ b/data_structures/stacks/next_greater_element.py @@ -17,7 +17,7 @@ def next_greatest_element_slow(arr: list[float]) -> list[float]: arr_size = len(arr) for i in range(arr_size): - _next: float = -1 + next_: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: _next = arr[j] From a8952493b577a119abc1fa9b9d2dc375fdd38a58 Mon Sep 17 00:00:00 2001 From: Caeden Date: Thu, 13 Oct 2022 12:57:59 +0100 Subject: [PATCH 08/24] Update digital_image_processing/index_calculation.py Co-authored-by: Christian Clauss --- digital_image_processing/index_calculation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/digital_image_processing/index_calculation.py b/digital_image_processing/index_calculation.py index 5269fe8bbf4d..f9f2f804bf8f 100644 --- a/digital_image_processing/index_calculation.py +++ b/digital_image_processing/index_calculation.py @@ -497,7 +497,7 @@ def s(self): https://www.indexdatabase.de/db/i-single.php?id=77 :return: index """ - _max = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) + max_ = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) _min = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (_max - _min) / _max From eb5524ba82cb46453428ee05db91b6286c463735 Mon Sep 17 00:00:00 2001 From: Caeden Date: Thu, 13 Oct 2022 12:58:59 +0100 Subject: [PATCH 09/24] Update graphs/prim.py Co-authored-by: Christian Clauss --- graphs/prim.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphs/prim.py b/graphs/prim.py index 344967bebed8..7b5f83a73e38 100644 --- a/graphs/prim.py +++ b/graphs/prim.py @@ -13,7 +13,7 @@ class Vertex: """Class Vertex.""" - def __init__(self, _id): + def __init__(self, id_): """ Arguments: id - input an id to identify the vertex From 89a4005ef2ee1a487a9a2966de35bf995ebc2fd3 Mon Sep 17 00:00:00 2001 From: Caeden Date: Thu, 13 Oct 2022 12:59:10 +0100 Subject: [PATCH 10/24] Update hashes/djb2.py Co-authored-by: Christian Clauss --- hashes/djb2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hashes/djb2.py b/hashes/djb2.py index 1babf07e0769..4ca0c92f96d9 100644 --- a/hashes/djb2.py +++ b/hashes/djb2.py @@ -29,7 +29,7 @@ def djb2(s: str) -> int: >>> djb2('scramble bits') 1609059040 """ - _hash = 5381 + hash_ = 5381 for x in s: _hash = ((_hash << 5) + _hash) + ord(x) return _hash & 0xFFFFFFFF From f84bcd74015befebac05398c7aa4e35eb6a9eaa3 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 13:05:46 +0100 Subject: [PATCH 11/24] refactor: Rename `_builtin` to `builtin_` ( #7104) --- arithmetic_analysis/gaussian_elimination.py | 6 +++--- arithmetic_analysis/jacobi_iteration_method.py | 6 +++--- data_structures/stacks/next_greater_element.py | 10 +++++----- digital_image_processing/index_calculation.py | 4 ++-- graphs/prim.py | 2 +- hashes/djb2.py | 4 ++-- hashes/sdbm.py | 6 +++--- maths/armstrong_numbers.py | 12 ++++++------ maths/bailey_borwein_plouffe.py | 6 +++--- maths/sum_of_arithmetic_series.py | 4 ++-- 10 files changed, 30 insertions(+), 30 deletions(-) diff --git a/arithmetic_analysis/gaussian_elimination.py b/arithmetic_analysis/gaussian_elimination.py index 65c5a60bb45d..f0f20af8e417 100644 --- a/arithmetic_analysis/gaussian_elimination.py +++ b/arithmetic_analysis/gaussian_elimination.py @@ -33,11 +33,11 @@ def retroactive_resolution( x: NDArray[float64] = np.zeros((rows, 1), dtype=float) for row in reversed(range(rows)): - count = 0 + total = 0 for col in range(row + 1, columns): - count += coefficients[row, col] * x[col] + total += coefficients[row, col] * x[col] - x[row, 0] = (vector[row] - count) / coefficients[row, row] + x[row, 0] = (vector[row] - total) / coefficients[row, row] return x diff --git a/arithmetic_analysis/jacobi_iteration_method.py b/arithmetic_analysis/jacobi_iteration_method.py index 59d4cdb97d8e..0aab4db20595 100644 --- a/arithmetic_analysis/jacobi_iteration_method.py +++ b/arithmetic_analysis/jacobi_iteration_method.py @@ -147,14 +147,14 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool: is_diagonally_dominant = True for i in range(0, rows): - count = 0 + total = 0 for j in range(0, cols - 1): if i == j: continue else: - count += table[i][j] + total += table[i][j] - if table[i][i] <= count: + if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant") return is_diagonally_dominant diff --git a/data_structures/stacks/next_greater_element.py b/data_structures/stacks/next_greater_element.py index c45668b075d7..33267cb3eb17 100644 --- a/data_structures/stacks/next_greater_element.py +++ b/data_structures/stacks/next_greater_element.py @@ -20,9 +20,9 @@ def next_greatest_element_slow(arr: list[float]) -> list[float]: next_: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: - _next = arr[j] + next_ = arr[j] break - result.append(_next) + result.append(next_) return result @@ -36,12 +36,12 @@ def next_greatest_element_fast(arr: list[float]) -> list[float]: """ result = [] for i, outer in enumerate(arr): - _next: float = -1 + next_: float = -1 for inner in arr[i + 1 :]: if outer < inner: - _next = inner + next_ = inner break - result.append(_next) + result.append(next_) return result diff --git a/digital_image_processing/index_calculation.py b/digital_image_processing/index_calculation.py index f9f2f804bf8f..822039f6638a 100644 --- a/digital_image_processing/index_calculation.py +++ b/digital_image_processing/index_calculation.py @@ -498,8 +498,8 @@ def s(self): :return: index """ max_ = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) - _min = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) - return (_max - _min) / _max + min_ = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) + return (max_ - min_) / max_ def _if(self): """ diff --git a/graphs/prim.py b/graphs/prim.py index 7b5f83a73e38..6cb1a6def359 100644 --- a/graphs/prim.py +++ b/graphs/prim.py @@ -21,7 +21,7 @@ def __init__(self, id_): neighbors - a list of the vertices it is linked to edges - a dict to store the edges's weight """ - self.id = str(_id) + self.id = str(id_) self.key = None self.pi = None self.neighbors = [] diff --git a/hashes/djb2.py b/hashes/djb2.py index 4ca0c92f96d9..c9e92b08dcfd 100644 --- a/hashes/djb2.py +++ b/hashes/djb2.py @@ -31,5 +31,5 @@ def djb2(s: str) -> int: """ hash_ = 5381 for x in s: - _hash = ((_hash << 5) + _hash) + ord(x) - return _hash & 0xFFFFFFFF + hash_ = ((hash_ << 5) + hash_) + ord(x) + return hash_ & 0xFFFFFFFF diff --git a/hashes/sdbm.py b/hashes/sdbm.py index bbd31d630617..b9758b485a71 100644 --- a/hashes/sdbm.py +++ b/hashes/sdbm.py @@ -31,7 +31,7 @@ def sdbm(plain_text: str) -> int: >>> sdbm('scramble bits') 730247649148944819640658295400555317318720608290373040936089 """ - _hash = 0 + hash_ = 0 for plain_chr in plain_text: - _hash = ord(plain_chr) + (_hash << 6) + (_hash << 16) - _hash - return _hash + hash_ = ord(plain_chr) + (hash_ << 6) + (hash_ << 16) - hash_ + return hash_ diff --git a/maths/armstrong_numbers.py b/maths/armstrong_numbers.py index 6a519932f8ac..f62991b7415b 100644 --- a/maths/armstrong_numbers.py +++ b/maths/armstrong_numbers.py @@ -25,7 +25,7 @@ def armstrong_number(n: int) -> bool: return False # Initialization of sum and number of digits. - _sum = 0 + total = 0 number_of_digits = 0 temp = n # Calculation of digits of the number @@ -36,9 +36,9 @@ def armstrong_number(n: int) -> bool: temp = n while temp > 0: rem = temp % 10 - _sum += rem**number_of_digits + total += rem**number_of_digits temp //= 10 - return n == _sum + return n == total def pluperfect_number(n: int) -> bool: @@ -55,7 +55,7 @@ def pluperfect_number(n: int) -> bool: # Init a "histogram" of the digits digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] digit_total = 0 - _sum = 0 + total = 0 temp = n while temp > 0: temp, rem = divmod(temp, 10) @@ -63,9 +63,9 @@ def pluperfect_number(n: int) -> bool: digit_total += 1 for (cnt, i) in zip(digit_histogram, range(len(digit_histogram))): - _sum += cnt * i**digit_total + total += cnt * i**digit_total - return n == _sum + return n == total def narcissistic_number(n: int) -> bool: diff --git a/maths/bailey_borwein_plouffe.py b/maths/bailey_borwein_plouffe.py index 5bfd01202ea3..389b1566e9de 100644 --- a/maths/bailey_borwein_plouffe.py +++ b/maths/bailey_borwein_plouffe.py @@ -67,7 +67,7 @@ def _subsum( @param precision: same as precision in main function @return: floating-point number whose integer part is not important """ - _sum = 0.0 + total = 0.0 for sum_index in range(digit_pos_to_extract + precision): denominator = 8 * sum_index + denominator_addend if sum_index < digit_pos_to_extract: @@ -79,8 +79,8 @@ def _subsum( ) else: exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index) - _sum += exponential_term / denominator - return _sum + total += exponential_term / denominator + return total if __name__ == "__main__": diff --git a/maths/sum_of_arithmetic_series.py b/maths/sum_of_arithmetic_series.py index 3e01342531e6..65a25bd4bf20 100644 --- a/maths/sum_of_arithmetic_series.py +++ b/maths/sum_of_arithmetic_series.py @@ -8,9 +8,9 @@ def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float >>> sum_of_series(1, 10, 100) 49600.0 """ - _sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) + sum_ = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series - return _sum + return sum_ def main(): From c8d6d470c92fbd8f5032ac0eb237c7c561940529 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 13:09:50 +0100 Subject: [PATCH 12/24] fix: Rename all instances (#7104) --- strings/snake_case_to_camel_pascal_case.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/strings/snake_case_to_camel_pascal_case.py b/strings/snake_case_to_camel_pascal_case.py index e0150c2685ba..56b893c16388 100644 --- a/strings/snake_case_to_camel_pascal_case.py +++ b/strings/snake_case_to_camel_pascal_case.py @@ -1,4 +1,4 @@ -def snake_to_camel_case(raw_input: str, use_pascal: bool = False) -> str: +def snake_to_camel_case(input_: str, use_pascal: bool = False) -> str: """ Transforms a snake_case given string to camelCase (or PascalCase if indicated) (defaults to not use Pascal) @@ -27,13 +27,13 @@ def snake_to_camel_case(raw_input: str, use_pascal: bool = False) -> str: """ if not isinstance(input_, str): - raise ValueError(f"Expected string as input, found {type(raw_input)}") + raise ValueError(f"Expected string as input, found {type(input_)}") if not isinstance(use_pascal, bool): raise ValueError( f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" ) - words = raw_input.split("_") + words = input_.split("_") start_index = 0 if use_pascal else 1 From 244a3a3e1e2398e802c103c485d038ad1f174630 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 14:27:36 +0100 Subject: [PATCH 13/24] refactor: Update variable names (#7104) --- data_structures/queue/double_ended_queue.py | 8 ++++---- data_structures/stacks/next_greater_element.py | 6 +++--- digital_image_processing/index_calculation.py | 6 +++--- hashes/djb2.py | 6 +++--- hashes/sdbm.py | 6 +++--- maths/sum_of_arithmetic_series.py | 4 ++-- neural_network/2_hidden_layers_neural_network.py | 4 ++-- strings/snake_case_to_camel_pascal_case.py | 8 ++++---- 8 files changed, 24 insertions(+), 24 deletions(-) diff --git a/data_structures/queue/double_ended_queue.py b/data_structures/queue/double_ended_queue.py index 451e8b80f8af..c80ab3ea8d6a 100644 --- a/data_structures/queue/double_ended_queue.py +++ b/data_structures/queue/double_ended_queue.py @@ -15,8 +15,8 @@ class Deque: ---------- append(val: Any) -> None appendleft(val: Any) -> None - extend(iter: Iterable) -> None - extendleft(iter: Iterable) -> None + extend(iterable: Iterable) -> None + extendleft(iterable: Iterable) -> None pop() -> Any popleft() -> Any Observers @@ -181,7 +181,7 @@ def appendleft(self, val: Any) -> None: def extend(self, iterable: Iterable[Any]) -> None: """ - Appends every value of iter to the end of the deque. + Appends every value of iterable to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) @@ -210,7 +210,7 @@ def extend(self, iterable: Iterable[Any]) -> None: def extendleft(self, iterable: Iterable[Any]) -> None: """ - Appends every value of iter to the beginning of the deque. + Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) diff --git a/data_structures/stacks/next_greater_element.py b/data_structures/stacks/next_greater_element.py index 33267cb3eb17..2722dff3d60a 100644 --- a/data_structures/stacks/next_greater_element.py +++ b/data_structures/stacks/next_greater_element.py @@ -17,12 +17,12 @@ def next_greatest_element_slow(arr: list[float]) -> list[float]: arr_size = len(arr) for i in range(arr_size): - next_: float = -1 + next_element: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: - next_ = arr[j] + next_element = arr[j] break - result.append(next_) + result.append(next_element) return result diff --git a/digital_image_processing/index_calculation.py b/digital_image_processing/index_calculation.py index 822039f6638a..01cd79fc18ff 100644 --- a/digital_image_processing/index_calculation.py +++ b/digital_image_processing/index_calculation.py @@ -497,9 +497,9 @@ def s(self): https://www.indexdatabase.de/db/i-single.php?id=77 :return: index """ - max_ = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) - min_ = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) - return (max_ - min_) / max_ + max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) + min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) + return (max_value - min_value) / max_value def _if(self): """ diff --git a/hashes/djb2.py b/hashes/djb2.py index c9e92b08dcfd..4c84635098f2 100644 --- a/hashes/djb2.py +++ b/hashes/djb2.py @@ -29,7 +29,7 @@ def djb2(s: str) -> int: >>> djb2('scramble bits') 1609059040 """ - hash_ = 5381 + hash_value = 5381 for x in s: - hash_ = ((hash_ << 5) + hash_) + ord(x) - return hash_ & 0xFFFFFFFF + hash_value = ((hash_value << 5) + hash_value) + ord(x) + return hash_value & 0xFFFFFFFF diff --git a/hashes/sdbm.py b/hashes/sdbm.py index b9758b485a71..94c182e675e0 100644 --- a/hashes/sdbm.py +++ b/hashes/sdbm.py @@ -31,7 +31,7 @@ def sdbm(plain_text: str) -> int: >>> sdbm('scramble bits') 730247649148944819640658295400555317318720608290373040936089 """ - hash_ = 0 + hash_value = 0 for plain_chr in plain_text: - hash_ = ord(plain_chr) + (hash_ << 6) + (hash_ << 16) - hash_ - return hash_ + hash_value = ord(plain_chr) + (hash_value << 6) + (hash_value << 16) - hash_value + return hash_value diff --git a/maths/sum_of_arithmetic_series.py b/maths/sum_of_arithmetic_series.py index 65a25bd4bf20..3e381b8c20a8 100644 --- a/maths/sum_of_arithmetic_series.py +++ b/maths/sum_of_arithmetic_series.py @@ -8,9 +8,9 @@ def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float >>> sum_of_series(1, 10, 100) 49600.0 """ - sum_ = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) + total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series - return sum_ + return total def main(): diff --git a/neural_network/2_hidden_layers_neural_network.py b/neural_network/2_hidden_layers_neural_network.py index dd796f26712f..9c5772326165 100644 --- a/neural_network/2_hidden_layers_neural_network.py +++ b/neural_network/2_hidden_layers_neural_network.py @@ -182,7 +182,7 @@ def train(self, output: numpy.ndarray, iterations: int, give_loss: bool) -> None loss = numpy.mean(numpy.square(output - self.feedforward())) print(f"Iteration {iteration} Loss: {loss}") - def predict(self, input_val: numpy.ndarray) -> int: + def predict(self, input_arr: numpy.ndarray) -> int: """ Predict's the output for the given input values using the trained neural network. @@ -201,7 +201,7 @@ def predict(self, input_val: numpy.ndarray) -> int: """ # Input values for which the predictions are to be made. - self.array = input_val + self.array = input_arr self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights) diff --git a/strings/snake_case_to_camel_pascal_case.py b/strings/snake_case_to_camel_pascal_case.py index 56b893c16388..eaabdcb87a0f 100644 --- a/strings/snake_case_to_camel_pascal_case.py +++ b/strings/snake_case_to_camel_pascal_case.py @@ -1,4 +1,4 @@ -def snake_to_camel_case(input_: str, use_pascal: bool = False) -> str: +def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str: """ Transforms a snake_case given string to camelCase (or PascalCase if indicated) (defaults to not use Pascal) @@ -26,14 +26,14 @@ def snake_to_camel_case(input_: str, use_pascal: bool = False) -> str: ValueError: Expected boolean as use_pascal parameter, found """ - if not isinstance(input_, str): - raise ValueError(f"Expected string as input, found {type(input_)}") + if not isinstance(input_str, str): + raise ValueError(f"Expected string as input, found {type(input_str)}") if not isinstance(use_pascal, bool): raise ValueError( f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" ) - words = input_.split("_") + words = input_str.split("_") start_index = 0 if use_pascal else 1 From 35787a1b83c42b0a4bb66b37940bbb0e6ad2cee4 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 13 Oct 2022 13:29:16 +0000 Subject: [PATCH 14/24] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- hashes/sdbm.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/hashes/sdbm.py b/hashes/sdbm.py index 94c182e675e0..a5432874ba7d 100644 --- a/hashes/sdbm.py +++ b/hashes/sdbm.py @@ -33,5 +33,7 @@ def sdbm(plain_text: str) -> int: """ hash_value = 0 for plain_chr in plain_text: - hash_value = ord(plain_chr) + (hash_value << 6) + (hash_value << 16) - hash_value + hash_value = ( + ord(plain_chr) + (hash_value << 6) + (hash_value << 16) - hash_value + ) return hash_value From 9874c44060dd0a73521477f6d2513bfe9dbdb916 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 14:41:37 +0100 Subject: [PATCH 15/24] ci: Create ``tox.ini`` and ignore ``A003`` (#7123) --- tox.ini | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 tox.ini diff --git a/tox.ini b/tox.ini new file mode 100644 index 000000000000..540d284d4fa0 --- /dev/null +++ b/tox.ini @@ -0,0 +1,3 @@ +[flake8] +extend-ignore = + A003 # Class attribute is shadowing a python builtin \ No newline at end of file From fe0afdbc53b52083fa5916e96112e3c49fc50dac Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 14:45:12 +0100 Subject: [PATCH 16/24] revert: Remove function name changes (#7104) --- data_structures/binary_tree/fenwick_tree.py | 8 ++++---- data_structures/heap/heap.py | 2 +- data_structures/linked_list/merge_two_lists.py | 2 +- data_structures/queue/double_ended_queue.py | 2 +- linear_algebra/src/lib.py | 2 +- other/lfu_cache.py | 14 +++++++------- other/lru_cache.py | 14 +++++++------- 7 files changed, 22 insertions(+), 22 deletions(-) diff --git a/data_structures/binary_tree/fenwick_tree.py b/data_structures/binary_tree/fenwick_tree.py index 60992c95ed2b..96020d1427af 100644 --- a/data_structures/binary_tree/fenwick_tree.py +++ b/data_structures/binary_tree/fenwick_tree.py @@ -46,7 +46,7 @@ def init(self, arr: list[int]) -> None: self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): - j = self.next_index(i) + j = self.next(i) if j < self.size: self.tree[j] += self.tree[i] @@ -64,13 +64,13 @@ def get_array(self) -> list[int]: """ arr = self.tree[:] for i in range(self.size - 1, 0, -1): - j = self.next_index(i) + j = self.next(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod - def next_index(index: int) -> int: + def next(index: int) -> int: return index + (index & (-index)) @staticmethod @@ -102,7 +102,7 @@ def add(self, index: int, value: int) -> None: return while index < self.size: self.tree[index] += value - index = self.next_index(index) + index = self.next(index) def update(self, index: int, value: int) -> None: """ diff --git a/data_structures/heap/heap.py b/data_structures/heap/heap.py index ac6e6caa58cc..e9d8b673c2cf 100644 --- a/data_structures/heap/heap.py +++ b/data_structures/heap/heap.py @@ -88,7 +88,7 @@ def build_max_heap(self, collection: Iterable[float]) -> None: for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) - def get_max(self) -> float: + def get(self) -> float: """return the max in the heap""" if self.heap_size >= 1: return self.h[0] diff --git a/data_structures/linked_list/merge_two_lists.py b/data_structures/linked_list/merge_two_lists.py index 52bc9c4c1e24..43dd461867f1 100644 --- a/data_structures/linked_list/merge_two_lists.py +++ b/data_structures/linked_list/merge_two_lists.py @@ -13,7 +13,7 @@ @dataclass class Node: data: int - next: Node | None # noqa: A003 + next: Node | None class SortedLinkedList: diff --git a/data_structures/queue/double_ended_queue.py b/data_structures/queue/double_ended_queue.py index c80ab3ea8d6a..7053879d4512 100644 --- a/data_structures/queue/double_ended_queue.py +++ b/data_structures/queue/double_ended_queue.py @@ -42,7 +42,7 @@ class _Node: """ val: Any = None - next: Deque._Node | None = None # noqa: A003 + next: Deque._Node | None = None prev: Deque._Node | None = None class _Iterator: diff --git a/linear_algebra/src/lib.py b/linear_algebra/src/lib.py index 81658ae58b69..b9791c860a74 100644 --- a/linear_algebra/src/lib.py +++ b/linear_algebra/src/lib.py @@ -119,7 +119,7 @@ def __mul__(self, other: float | Vector) -> float | Vector: else: # error case raise Exception("invalid operand!") - def set_components(self, components: Collection[float]) -> None: + def set(self, components: Collection[float]) -> None: """ input: new components changes the components of the vector. diff --git a/other/lfu_cache.py b/other/lfu_cache.py index 9966dde2ae99..57e364e74d8d 100644 --- a/other/lfu_cache.py +++ b/other/lfu_cache.py @@ -166,14 +166,14 @@ class LFUCache(Generic[T, U]): or as a function decorator. >>> cache = LFUCache(2) - >>> cache.set_key(1, 1) - >>> cache.set_key(2, 2) + >>> cache.set(1, 1) + >>> cache.set(2, 2) >>> cache.get(1) 1 - >>> cache.set_key(3, 3) + >>> cache.set(3, 3) >>> cache.get(2) is None True - >>> cache.set_key(4, 4) + >>> cache.set(4, 4) >>> cache.get(1) is None True >>> cache.get(3) @@ -224,7 +224,7 @@ def __contains__(self, key: T) -> bool: >>> 1 in cache False - >>> cache.set_key(1, 1) + >>> cache.set(1, 1) >>> 1 in cache True """ @@ -250,7 +250,7 @@ def get(self, key: T) -> U | None: self.miss += 1 return None - def set_key(self, key: T, value: U) -> None: + def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ @@ -297,7 +297,7 @@ def cache_decorator_wrapper(*args: T) -> U: result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) - cls.decorator_function_to_instance_map[func].set_key( + cls.decorator_function_to_instance_map[func].set( args[0], result ) return result diff --git a/other/lru_cache.py b/other/lru_cache.py index 67bcfa3867f4..8c14bf73bded 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -150,8 +150,8 @@ class LRUCache(Generic[T, U]): >>> cache = LRUCache(2) - >>> cache.set_key(1, 1) - >>> cache.set_key(2, 2) + >>> cache.set(1, 1) + >>> cache.set(2, 2) >>> cache.get(1) 1 @@ -166,7 +166,7 @@ class LRUCache(Generic[T, U]): {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 2: Node: key: 2, val: 2, has next: True, has prev: True} - >>> cache.set_key(3, 3) + >>> cache.set(3, 3) >>> cache.list DoubleLinkedList, @@ -182,7 +182,7 @@ class LRUCache(Generic[T, U]): >>> cache.get(2) is None True - >>> cache.set_key(4, 4) + >>> cache.set(4, 4) >>> cache.get(1) is None True @@ -238,7 +238,7 @@ def __contains__(self, key: T) -> bool: >>> 1 in cache False - >>> cache.set_key(1, 1) + >>> cache.set(1, 1) >>> 1 in cache True @@ -266,7 +266,7 @@ def get(self, key: T) -> U | None: self.miss += 1 return None - def set_key(self, key: T, value: U) -> None: + def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ @@ -315,7 +315,7 @@ def cache_decorator_wrapper(*args: T) -> U: result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) - cls.decorator_function_to_instance_map[func].set_key( + cls.decorator_function_to_instance_map[func].set( args[0], result ) return result From 3d39ee991c0d3572bb0c0b5f2308087c7881645b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 13 Oct 2022 13:46:07 +0000 Subject: [PATCH 17/24] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- other/lfu_cache.py | 4 +--- other/lru_cache.py | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/other/lfu_cache.py b/other/lfu_cache.py index 57e364e74d8d..072d00ab58c8 100644 --- a/other/lfu_cache.py +++ b/other/lfu_cache.py @@ -297,9 +297,7 @@ def cache_decorator_wrapper(*args: T) -> U: result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) - cls.decorator_function_to_instance_map[func].set( - args[0], result - ) + cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LFUCache[T, U]: diff --git a/other/lru_cache.py b/other/lru_cache.py index 8c14bf73bded..b68ae0a8e296 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -315,9 +315,7 @@ def cache_decorator_wrapper(*args: T) -> U: result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) - cls.decorator_function_to_instance_map[func].set( - args[0], result - ) + cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LRUCache[T, U]: From c46e0213ab2d5677283c7dcfe58a89f465a6e464 Mon Sep 17 00:00:00 2001 From: Dhruv Manilawala Date: Thu, 13 Oct 2022 19:25:07 +0530 Subject: [PATCH 18/24] Rename tox.ini to .flake8 --- .flake8 | 3 +++ tox.ini | 3 --- 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 .flake8 delete mode 100644 tox.ini diff --git a/.flake8 b/.flake8 new file mode 100644 index 000000000000..9a5863c9cd0b --- /dev/null +++ b/.flake8 @@ -0,0 +1,3 @@ +[flake8] +extend-ignore = + A003 # Class attribute is shadowing a python builtin diff --git a/tox.ini b/tox.ini deleted file mode 100644 index 540d284d4fa0..000000000000 --- a/tox.ini +++ /dev/null @@ -1,3 +0,0 @@ -[flake8] -extend-ignore = - A003 # Class attribute is shadowing a python builtin \ No newline at end of file From 9f13912b8e10f8d48abe6528c99adbf19113ce10 Mon Sep 17 00:00:00 2001 From: Caeden Date: Thu, 13 Oct 2022 14:59:27 +0100 Subject: [PATCH 19/24] Update data_structures/heap/heap.py Co-authored-by: Dhruv Manilawala --- data_structures/heap/heap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/heap/heap.py b/data_structures/heap/heap.py index e9d8b673c2cf..4c19747ec823 100644 --- a/data_structures/heap/heap.py +++ b/data_structures/heap/heap.py @@ -88,7 +88,7 @@ def build_max_heap(self, collection: Iterable[float]) -> None: for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) - def get(self) -> float: + def max(self) -> float: """return the max in the heap""" if self.heap_size >= 1: return self.h[0] From 0d63a429f09943c02f095755038e0b9fdc4687cc Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 15:12:06 +0100 Subject: [PATCH 20/24] refactor: Rename `next_` to `next_item` (#7104) --- data_structures/stacks/next_greater_element.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/data_structures/stacks/next_greater_element.py b/data_structures/stacks/next_greater_element.py index 2722dff3d60a..7d76d1f47dfa 100644 --- a/data_structures/stacks/next_greater_element.py +++ b/data_structures/stacks/next_greater_element.py @@ -36,12 +36,12 @@ def next_greatest_element_fast(arr: list[float]) -> list[float]: """ result = [] for i, outer in enumerate(arr): - next_: float = -1 + next_item: float = -1 for inner in arr[i + 1 :]: if outer < inner: - next_ = inner + next_item = inner break - result.append(next_) + result.append(next_item) return result From 952d1a255960b20f2944769f3d48de9a6eb70f86 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 16:38:41 +0100 Subject: [PATCH 21/24] ci(pre-commit): Add `flake8` plugin `flake8-bugbear` (#7127) --- .pre-commit-config.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e0de70b01883..d2558b90abb1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -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 From 214befd3f9df9e2c08b6148f386649370c5eb055 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 16:39:10 +0100 Subject: [PATCH 22/24] refactor: Follow `flake8-bugbear` plugin (#7127) --- .../jacobi_iteration_method.py | 2 +- .../newton_forward_interpolation.py | 2 +- arithmetic_analysis/secant_method.py | 2 +- audio_filters/butterworth_filter.py | 23 +++++++++++++------ backtracking/sum_of_subsets.py | 8 +++---- boolean_algebra/quine_mc_cluskey.py | 2 +- ciphers/mixed_keyword_cypher.py | 2 +- ciphers/rabin_miller.py | 2 +- compression/burrows_wheeler.py | 2 +- .../binary_search_tree_recursive.py | 8 +++---- .../linked_list/circular_linked_list.py | 8 +++---- .../linked_list/doubly_linked_list.py | 8 +++---- .../middle_element_of_linked_list.py | 2 +- .../linked_list/singly_linked_list.py | 6 ++--- data_structures/linked_list/skip_list.py | 4 ++-- data_structures/queue/queue_on_list.py | 2 +- .../queue/queue_on_pseudo_stack.py | 2 +- data_structures/stacks/stack.py | 6 ++--- divide_and_conquer/convex_hull.py | 8 +++---- .../strassen_matrix_multiplication.py | 6 ++--- dynamic_programming/all_construct.py | 2 +- dynamic_programming/knapsack.py | 6 ++--- fractals/julia_sets.py | 2 +- fractals/koch_snowflake.py | 2 +- fractals/mandelbrot.py | 2 +- genetic_algorithm/basic_string.py | 7 ++++-- graphs/basic_graphs.py | 4 ++-- graphs/bellman_ford.py | 2 +- graphs/dijkstra_2.py | 18 +++++++-------- graphs/frequent_pattern_graph_miner.py | 2 +- graphs/kahns_algorithm_long.py | 2 +- graphs/kahns_algorithm_topo.py | 2 +- graphs/minimum_spanning_tree_prims.py | 2 +- graphs/page_rank.py | 2 +- graphs/scc_kosaraju.py | 4 ++-- greedy_methods/optimal_merge_pattern.py | 2 +- hashes/chaos_machine.py | 2 +- hashes/enigma_machine.py | 2 +- machine_learning/self_organizing_map.py | 2 +- maths/area_under_curve.py | 2 +- maths/line_length.py | 2 +- maths/lucas_lehmer_primality_test.py | 2 +- maths/lucas_series.py | 2 +- maths/miller_rabin.py | 2 +- maths/monte_carlo_dice.py | 2 +- maths/numerical_integration.py | 2 +- maths/pi_monte_carlo_estimation.py | 2 +- maths/pollard_rho.py | 2 +- maths/primelib.py | 8 +++---- maths/proth_number.py | 2 +- maths/square_root.py | 2 +- maths/ugly_numbers.py | 2 +- matrix/matrix_class.py | 2 +- ...h_fibonacci_using_matrix_exponentiation.py | 2 +- .../back_propagation_neural_network.py | 2 +- neural_network/perceptron.py | 2 +- other/lfu_cache.py | 2 +- other/lru_cache.py | 2 +- other/magicdiamondpattern.py | 8 +++---- other/scoring_algorithm.py | 2 +- physics/lorentz_transformation_four_vector.py | 2 +- physics/n_body_simulation.py | 2 +- project_euler/problem_011/sol2.py | 2 +- project_euler/problem_025/sol3.py | 2 +- project_euler/problem_026/sol1.py | 2 +- project_euler/problem_188/sol1.py | 2 +- project_euler/problem_203/sol1.py | 2 +- scheduling/multi_level_feedback_queue.py | 2 +- sorts/double_sort.py | 2 +- 69 files changed, 128 insertions(+), 116 deletions(-) diff --git a/arithmetic_analysis/jacobi_iteration_method.py b/arithmetic_analysis/jacobi_iteration_method.py index 0aab4db20595..3087309e8c3d 100644 --- a/arithmetic_analysis/jacobi_iteration_method.py +++ b/arithmetic_analysis/jacobi_iteration_method.py @@ -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 diff --git a/arithmetic_analysis/newton_forward_interpolation.py b/arithmetic_analysis/newton_forward_interpolation.py index 490e0687f15f..466f6c18cf59 100644 --- a/arithmetic_analysis/newton_forward_interpolation.py +++ b/arithmetic_analysis/newton_forward_interpolation.py @@ -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): diff --git a/arithmetic_analysis/secant_method.py b/arithmetic_analysis/secant_method.py index 45bcb185fc3e..d28a46206d40 100644 --- a/arithmetic_analysis/secant_method.py +++ b/arithmetic_analysis/secant_method.py @@ -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 diff --git a/audio_filters/butterworth_filter.py b/audio_filters/butterworth_filter.py index 409cfeb1d95c..cffedb7a68fd 100644 --- a/audio_filters/butterworth_filter.py +++ b/audio_filters/butterworth_filter.py @@ -11,7 +11,7 @@ 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 diff --git a/backtracking/sum_of_subsets.py b/backtracking/sum_of_subsets.py index 8348544c0175..128e290718cd 100644 --- a/backtracking/sum_of_subsets.py +++ b/backtracking/sum_of_subsets.py @@ -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], ) diff --git a/boolean_algebra/quine_mc_cluskey.py b/boolean_algebra/quine_mc_cluskey.py index 9aa9b10c8429..5bd7117bb3e7 100644 --- a/boolean_algebra/quine_mc_cluskey.py +++ b/boolean_algebra/quine_mc_cluskey.py @@ -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) diff --git a/ciphers/mixed_keyword_cypher.py b/ciphers/mixed_keyword_cypher.py index 178902173477..f55c9c4286df 100644 --- a/ciphers/mixed_keyword_cypher.py +++ b/ciphers/mixed_keyword_cypher.py @@ -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 diff --git a/ciphers/rabin_miller.py b/ciphers/rabin_miller.py index 0aab80eb9175..410d559d4315 100644 --- a/ciphers/rabin_miller.py +++ b/ciphers/rabin_miller.py @@ -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: diff --git a/compression/burrows_wheeler.py b/compression/burrows_wheeler.py index 4ad99a642e49..0916b8a654d2 100644 --- a/compression/burrows_wheeler.py +++ b/compression/burrows_wheeler.py @@ -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() diff --git a/data_structures/binary_tree/binary_search_tree_recursive.py b/data_structures/binary_tree/binary_search_tree_recursive.py index 0d0ac8fd1e22..97eb8e25bedd 100644 --- a/data_structures/binary_tree/binary_search_tree_recursive.py +++ b/data_structures/binary_tree/binary_search_tree_recursive.py @@ -357,7 +357,7 @@ def test_put(self) -> None: 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 @@ def test_search(self) -> None: 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 @@ def test_get_max_label(self) -> None: 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 @@ def test_get_min_label(self) -> None: 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: diff --git a/data_structures/linked_list/circular_linked_list.py b/data_structures/linked_list/circular_linked_list.py index 6fec0a12542f..67a63cd55e19 100644 --- a/data_structures/linked_list/circular_linked_list.py +++ b/data_structures/linked_list/circular_linked_list.py @@ -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 diff --git a/data_structures/linked_list/doubly_linked_list.py b/data_structures/linked_list/doubly_linked_list.py index 0eb3cf101a3e..9e996ef0fb9d 100644 --- a/data_structures/linked_list/doubly_linked_list.py +++ b/data_structures/linked_list/doubly_linked_list.py @@ -96,7 +96,7 @@ def insert_at_nth(self, index: int, data): 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 @@ def delete_at_nth(self, index: int): 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. diff --git a/data_structures/linked_list/middle_element_of_linked_list.py b/data_structures/linked_list/middle_element_of_linked_list.py index 0c6250f3b731..86dad6b41d73 100644 --- a/data_structures/linked_list/middle_element_of_linked_list.py +++ b/data_structures/linked_list/middle_element_of_linked_list.py @@ -62,7 +62,7 @@ def middle_element(self) -> int | None: 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()) diff --git a/data_structures/linked_list/singly_linked_list.py b/data_structures/linked_list/singly_linked_list.py index 59d7c512bad7..89a05ae81d4c 100644 --- a/data_structures/linked_list/singly_linked_list.py +++ b/data_structures/linked_list/singly_linked_list.py @@ -132,7 +132,7 @@ def __setitem__(self, index: int, data: Any) -> None: 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. diff --git a/data_structures/linked_list/skip_list.py b/data_structures/linked_list/skip_list.py index 176049120aab..a667e3e9bc84 100644 --- a/data_structures/linked_list/skip_list.py +++ b/data_structures/linked_list/skip_list.py @@ -205,7 +205,7 @@ def insert(self, key: KT, value: 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 is_sorted(lst): 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() diff --git a/data_structures/queue/queue_on_list.py b/data_structures/queue/queue_on_list.py index 485cf0b6f7a3..71fca6b2f5f4 100644 --- a/data_structures/queue/queue_on_list.py +++ b/data_structures/queue/queue_on_list.py @@ -37,7 +37,7 @@ def get(self): 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} diff --git a/data_structures/queue/queue_on_pseudo_stack.py b/data_structures/queue/queue_on_pseudo_stack.py index 9a0c16f61eb4..d9845100008e 100644 --- a/data_structures/queue/queue_on_pseudo_stack.py +++ b/data_structures/queue/queue_on_pseudo_stack.py @@ -37,7 +37,7 @@ def get(self) -> Any: 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) diff --git a/data_structures/stacks/stack.py b/data_structures/stacks/stack.py index d1c73df43067..55d424d5018b 100644 --- a/data_structures/stacks/stack.py +++ b/data_structures/stacks/stack.py @@ -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 diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index 72da116398a9..39e78be04a71 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -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: diff --git a/divide_and_conquer/strassen_matrix_multiplication.py b/divide_and_conquer/strassen_matrix_multiplication.py index 17efcfc7c8ee..0ee426e4b39a 100644 --- a/divide_and_conquer/strassen_matrix_multiplication.py +++ b/divide_and_conquer/strassen_matrix_multiplication.py @@ -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() diff --git a/dynamic_programming/all_construct.py b/dynamic_programming/all_construct.py index 5ffed2caa182..3839d01e6db0 100644 --- a/dynamic_programming/all_construct.py +++ b/dynamic_programming/all_construct.py @@ -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 diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index 9efb60bab98b..350752c6c3df 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -30,11 +30,11 @@ 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): + 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]) + 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 diff --git a/fractals/julia_sets.py b/fractals/julia_sets.py index f273943851fc..28c675c750bc 100644 --- a/fractals/julia_sets.py +++ b/fractals/julia_sets.py @@ -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) diff --git a/fractals/koch_snowflake.py b/fractals/koch_snowflake.py index 07c1835b41ed..b0aaa86b11d8 100644 --- a/fractals/koch_snowflake.py +++ b/fractals/koch_snowflake.py @@ -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 diff --git a/fractals/mandelbrot.py b/fractals/mandelbrot.py index 5d61b72e172f..f97bcd17031c 100644 --- a/fractals/mandelbrot.py +++ b/fractals/mandelbrot.py @@ -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 diff --git a/genetic_algorithm/basic_string.py b/genetic_algorithm/basic_string.py index 97dbe182bc82..bd7d8026866c 100644 --- a/genetic_algorithm/basic_string.py +++ b/genetic_algorithm/basic_string.py @@ -80,7 +80,7 @@ def evaluate(item: str, main_target: str = target) -> tuple[str, float]: 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 select(parent_1: tuple[str, float]) -> list[str]: 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)) diff --git a/graphs/basic_graphs.py b/graphs/basic_graphs.py index b02e9af65846..298a97bf0e17 100644 --- a/graphs/basic_graphs.py +++ b/graphs/basic_graphs.py @@ -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 diff --git a/graphs/bellman_ford.py b/graphs/bellman_ford.py index 0f654a510b59..eb2cd25bf682 100644 --- a/graphs/bellman_ford.py +++ b/graphs/bellman_ford.py @@ -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"]) diff --git a/graphs/dijkstra_2.py b/graphs/dijkstra_2.py index 3170765bc8a8..f548463ff7bd 100644 --- a/graphs/dijkstra_2.py +++ b/graphs/dijkstra_2.py @@ -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__": diff --git a/graphs/frequent_pattern_graph_miner.py b/graphs/frequent_pattern_graph_miner.py index 50081afa6728..a5ecbe6e8223 100644 --- a/graphs/frequent_pattern_graph_miner.py +++ b/graphs/frequent_pattern_graph_miner.py @@ -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 diff --git a/graphs/kahns_algorithm_long.py b/graphs/kahns_algorithm_long.py index 776ae3a2f903..63cbeb909a8a 100644 --- a/graphs/kahns_algorithm_long.py +++ b/graphs/kahns_algorithm_long.py @@ -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 diff --git a/graphs/kahns_algorithm_topo.py b/graphs/kahns_algorithm_topo.py index 6879b047fe35..b1260bd5bd9b 100644 --- a/graphs/kahns_algorithm_topo.py +++ b/graphs/kahns_algorithm_topo.py @@ -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 diff --git a/graphs/minimum_spanning_tree_prims.py b/graphs/minimum_spanning_tree_prims.py index 9b2c645f16df..5b2eaa4bff40 100644 --- a/graphs/minimum_spanning_tree_prims.py +++ b/graphs/minimum_spanning_tree_prims.py @@ -91,7 +91,7 @@ def delete_minimum(heap, positions): 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)) diff --git a/graphs/page_rank.py b/graphs/page_rank.py index 672405b7345b..e1af35b34749 100644 --- a/graphs/page_rank.py +++ b/graphs/page_rank.py @@ -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 ) diff --git a/graphs/scc_kosaraju.py b/graphs/scc_kosaraju.py index ea9d35282858..39211c64b687 100644 --- a/graphs/scc_kosaraju.py +++ b/graphs/scc_kosaraju.py @@ -39,10 +39,10 @@ def kosaraju(): # 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) diff --git a/greedy_methods/optimal_merge_pattern.py b/greedy_methods/optimal_merge_pattern.py index 911e1966f3b9..a1c934f84498 100644 --- a/greedy_methods/optimal_merge_pattern.py +++ b/greedy_methods/optimal_merge_pattern.py @@ -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) diff --git a/hashes/chaos_machine.py b/hashes/chaos_machine.py index 69313fbb2065..238fdb1c0634 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -53,7 +53,7 @@ def xorshift(x, y): 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] diff --git a/hashes/enigma_machine.py b/hashes/enigma_machine.py index b0d45718e286..0194f7da7d6f 100644 --- a/hashes/enigma_machine.py +++ b/hashes/enigma_machine.py @@ -48,7 +48,7 @@ def engine(input_character): break except Exception as error: print(error) - for i in range(token): + for _ in range(token): rotator() for j in decode: engine(j) diff --git a/machine_learning/self_organizing_map.py b/machine_learning/self_organizing_map.py index bd3d388f910f..057c2a76b8ac 100644 --- a/machine_learning/self_organizing_map.py +++ b/machine_learning/self_organizing_map.py @@ -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 diff --git a/maths/area_under_curve.py b/maths/area_under_curve.py index d345398b4c2c..b557b2029657 100644 --- a/maths/area_under_curve.py +++ b/maths/area_under_curve.py @@ -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 diff --git a/maths/line_length.py b/maths/line_length.py index ad12a816b93e..ea27ee904a24 100644 --- a/maths/line_length.py +++ b/maths/line_length.py @@ -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 diff --git a/maths/lucas_lehmer_primality_test.py b/maths/lucas_lehmer_primality_test.py index 916abfcc175e..0a5621aacd79 100644 --- a/maths/lucas_lehmer_primality_test.py +++ b/maths/lucas_lehmer_primality_test.py @@ -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 diff --git a/maths/lucas_series.py b/maths/lucas_series.py index 6b32c2022e13..cae6c2815aec 100644 --- a/maths/lucas_series.py +++ b/maths/lucas_series.py @@ -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 diff --git a/maths/miller_rabin.py b/maths/miller_rabin.py index b4dfed1290de..9f2668dbab14 100644 --- a/maths/miller_rabin.py +++ b/maths/miller_rabin.py @@ -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 diff --git a/maths/monte_carlo_dice.py b/maths/monte_carlo_dice.py index 17cedbdbcb18..c4150b88f6cc 100644 --- a/maths/monte_carlo_dice.py +++ b/maths/monte_carlo_dice.py @@ -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 diff --git a/maths/numerical_integration.py b/maths/numerical_integration.py index a2bfce5b911d..8f32fd3564df 100644 --- a/maths/numerical_integration.py +++ b/maths/numerical_integration.py @@ -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 diff --git a/maths/pi_monte_carlo_estimation.py b/maths/pi_monte_carlo_estimation.py index 81be083787bd..29b679907239 100644 --- a/maths/pi_monte_carlo_estimation.py +++ b/maths/pi_monte_carlo_estimation.py @@ -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(): diff --git a/maths/pollard_rho.py b/maths/pollard_rho.py index 0fc80cd4280b..5082f54f71a8 100644 --- a/maths/pollard_rho.py +++ b/maths/pollard_rho.py @@ -73,7 +73,7 @@ def rand_fn(value: int, step: int, modulus: int) -> int: """ 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 diff --git a/maths/primelib.py b/maths/primelib.py index 7d2a22f39c59..eb72a9f8ae6a 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -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 diff --git a/maths/proth_number.py b/maths/proth_number.py index e175031435b0..6b15190249f0 100644 --- a/maths/proth_number.py +++ b/maths/proth_number.py @@ -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 diff --git a/maths/square_root.py b/maths/square_root.py index b324c723037c..2cbf14beae18 100644 --- a/maths/square_root.py +++ b/maths/square_root.py @@ -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: diff --git a/maths/ugly_numbers.py b/maths/ugly_numbers.py index 4451a68cdaad..81bd928c6b3d 100644 --- a/maths/ugly_numbers.py +++ b/maths/ugly_numbers.py @@ -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: diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index 305cad0a5a9c..6495bd8fc88d 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -351,7 +351,7 @@ def __pow__(self, other: int) -> 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 diff --git a/matrix/nth_fibonacci_using_matrix_exponentiation.py b/matrix/nth_fibonacci_using_matrix_exponentiation.py index 7c964d884617..65f10c90d07a 100644 --- a/matrix/nth_fibonacci_using_matrix_exponentiation.py +++ b/matrix/nth_fibonacci_using_matrix_exponentiation.py @@ -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 diff --git a/neural_network/back_propagation_neural_network.py b/neural_network/back_propagation_neural_network.py index 43e796e77be3..23b818b0f3cf 100644 --- a/neural_network/back_propagation_neural_network.py +++ b/neural_network/back_propagation_neural_network.py @@ -128,7 +128,7 @@ def train(self, xdata, ydata, train_round, accuracy): 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 diff --git a/neural_network/perceptron.py b/neural_network/perceptron.py index a2bfdb326d77..f04c81424c81 100644 --- a/neural_network/perceptron.py +++ b/neural_network/perceptron.py @@ -69,7 +69,7 @@ def training(self) -> None: 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) diff --git a/other/lfu_cache.py b/other/lfu_cache.py index 072d00ab58c8..2f26bb6cc74a 100644 --- a/other/lfu_cache.py +++ b/other/lfu_cache.py @@ -303,7 +303,7 @@ def cache_decorator_wrapper(*args: 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 diff --git a/other/lru_cache.py b/other/lru_cache.py index b68ae0a8e296..aa910e487406 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -321,7 +321,7 @@ def cache_decorator_wrapper(*args: 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 diff --git a/other/magicdiamondpattern.py b/other/magicdiamondpattern.py index 71bc50b51fc2..0fc41d7a25d8 100644 --- a/other/magicdiamondpattern.py +++ b/other/magicdiamondpattern.py @@ -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="") diff --git a/other/scoring_algorithm.py b/other/scoring_algorithm.py index aecd19c55927..1e6293f8465c 100644 --- a/other/scoring_algorithm.py +++ b/other/scoring_algorithm.py @@ -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 diff --git a/physics/lorentz_transformation_four_vector.py b/physics/lorentz_transformation_four_vector.py index bda852c25520..f58b40e5906b 100644 --- a/physics/lorentz_transformation_four_vector.py +++ b/physics/lorentz_transformation_four_vector.py @@ -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) diff --git a/physics/n_body_simulation.py b/physics/n_body_simulation.py index 7e9fc1642c84..2f8153782663 100644 --- a/physics/n_body_simulation.py +++ b/physics/n_body_simulation.py @@ -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) diff --git a/project_euler/problem_011/sol2.py b/project_euler/problem_011/sol2.py index 839ca6717571..9ea0db991aaf 100644 --- a/project_euler/problem_011/sol2.py +++ b/project_euler/problem_011/sol2.py @@ -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 diff --git a/project_euler/problem_025/sol3.py b/project_euler/problem_025/sol3.py index c66411dc55fc..0b9f3a0c84ef 100644 --- a/project_euler/problem_025/sol3.py +++ b/project_euler/problem_025/sol3.py @@ -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 diff --git a/project_euler/problem_026/sol1.py b/project_euler/problem_026/sol1.py index 75d48df7910c..ccf2c111d2c5 100644 --- a/project_euler/problem_026/sol1.py +++ b/project_euler/problem_026/sol1.py @@ -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) diff --git a/project_euler/problem_188/sol1.py b/project_euler/problem_188/sol1.py index dd4360adb32b..88bd1327e917 100644 --- a/project_euler/problem_188/sol1.py +++ b/project_euler/problem_188/sol1.py @@ -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 diff --git a/project_euler/problem_203/sol1.py b/project_euler/problem_203/sol1.py index dc93683da535..713b530b6af2 100644 --- a/project_euler/problem_203/sol1.py +++ b/project_euler/problem_203/sol1.py @@ -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 = [] diff --git a/scheduling/multi_level_feedback_queue.py b/scheduling/multi_level_feedback_queue.py index b54cc8719039..a3ba1b340e9b 100644 --- a/scheduling/multi_level_feedback_queue.py +++ b/scheduling/multi_level_feedback_queue.py @@ -205,7 +205,7 @@ def round_robin( """ 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 diff --git a/sorts/double_sort.py b/sorts/double_sort.py index 4e08e27b3c21..5ca88a6745d5 100644 --- a/sorts/double_sort.py +++ b/sorts/double_sort.py @@ -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): From 0c48669df7fa90bf50ca4d3325d64de9aa439dc4 Mon Sep 17 00:00:00 2001 From: CaedenPH Date: Thu, 13 Oct 2022 16:48:41 +0100 Subject: [PATCH 23/24] fix: Correct `knapsack` code (#7127) --- dynamic_programming/knapsack.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index 350752c6c3df..093e15f49ba0 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -31,12 +31,12 @@ def knapsack(w, wt, val, n): 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_]) + 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_] - return dp[n][w], dp + return dp[n][w_], dp def knapsack_with_example_solution(w: int, wt: list, val: list): From 808ee5db0b90e20a32aaeed6fd3a3b04fb578af0 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 13 Oct 2022 15:55:45 +0000 Subject: [PATCH 24/24] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- web_programming/open_google_results.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/web_programming/open_google_results.py b/web_programming/open_google_results.py index 0e1dba8c5856..2685bf62114d 100644 --- a/web_programming/open_google_results.py +++ b/web_programming/open_google_results.py @@ -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 @@ res = requests.get( url, - headers={ - "User-Agent": str(UserAgent().random) - }, + headers={"User-Agent": str(UserAgent().random)}, ) try: