Skip to content

Commit

Permalink
Add flake8-builtins to pre-commit and fix errors (TheAlgorithms#7105)
Browse files Browse the repository at this point in the history
Ignore `A003`

Co-authored-by: Christian Clauss <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Dhruv Manilawala <[email protected]>
  • Loading branch information
4 people authored Oct 13, 2022
1 parent e661b98 commit d5a9f64
Show file tree
Hide file tree
Showing 31 changed files with 113 additions and 106 deletions.
3 changes: 3 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[flake8]
extend-ignore =
A003 # Class attribute is shadowing a python builtin
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ repos:
- --ignore=E203,W503
- --max-complexity=25
- --max-line-length=88
additional_dependencies: [pep8-naming]
additional_dependencies: [flake8-builtins, pep8-naming]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.982
Expand Down
6 changes: 3 additions & 3 deletions arithmetic_analysis/gaussian_elimination.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ def retroactive_resolution(

x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
for row in reversed(range(rows)):
sum = 0
total = 0
for col in range(row + 1, columns):
sum += coefficients[row, col] * x[col]
total += coefficients[row, col] * x[col]

x[row, 0] = (vector[row] - sum) / coefficients[row, row]
x[row, 0] = (vector[row] - total) / coefficients[row, row]

return x

Expand Down
6 changes: 3 additions & 3 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,14 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:
is_diagonally_dominant = True

for i in range(0, rows):
sum = 0
total = 0
for j in range(0, cols - 1):
if i == j:
continue
else:
sum += table[i][j]
total += table[i][j]

if table[i][i] <= sum:
if table[i][i] <= total:
raise ValueError("Coefficient matrix is not strictly diagonally dominant")

return is_diagonally_dominant
Expand Down
8 changes: 4 additions & 4 deletions audio_filters/show_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions backtracking/hamiltonian_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion data_structures/binary_tree/avl_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions data_structures/linked_list/singly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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
Expand Down
16 changes: 8 additions & 8 deletions data_structures/queue/double_ended_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -179,9 +179,9 @@ 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.
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])
Expand All @@ -205,12 +205,12 @@ 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.
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])
Expand All @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions data_structures/stacks/next_greater_element.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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


Expand Down
6 changes: 3 additions & 3 deletions digital_image_processing/index_calculation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
6 changes: 3 additions & 3 deletions dynamic_programming/optimal_binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions graphs/a_star.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions graphs/dijkstra.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
14 changes: 7 additions & 7 deletions graphs/finding_bridges.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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


Expand Down
4 changes: 2 additions & 2 deletions graphs/prim.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
class Vertex:
"""Class Vertex."""

def __init__(self, id):
def __init__(self, id_):
"""
Arguments:
id - input an id to identify the vertex
Attributes:
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 = []
Expand Down
6 changes: 3 additions & 3 deletions hashes/djb2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 5 additions & 3 deletions hashes/sdbm.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ 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
12 changes: 6 additions & 6 deletions maths/armstrong_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -55,17 +55,17 @@ 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)
digit_histogram[rem] += 1
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:
Expand Down
Loading

0 comments on commit d5a9f64

Please sign in to comment.