mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Add flake8-builtins to pre-commit and fix errors (#7105)
Ignore `A003` Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
This commit is contained in:
parent
e661b98829
commit
d5a9f649b8
3
.flake8
Normal file
3
.flake8
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
[flake8]
|
||||||
|
extend-ignore =
|
||||||
|
A003 # Class attribute is shadowing a python builtin
|
|
@ -40,7 +40,7 @@ repos:
|
||||||
- --ignore=E203,W503
|
- --ignore=E203,W503
|
||||||
- --max-complexity=25
|
- --max-complexity=25
|
||||||
- --max-line-length=88
|
- --max-line-length=88
|
||||||
additional_dependencies: [pep8-naming]
|
additional_dependencies: [flake8-builtins, pep8-naming]
|
||||||
|
|
||||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
rev: v0.982
|
rev: v0.982
|
||||||
|
|
|
@ -33,11 +33,11 @@ def retroactive_resolution(
|
||||||
|
|
||||||
x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
|
x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
|
||||||
for row in reversed(range(rows)):
|
for row in reversed(range(rows)):
|
||||||
sum = 0
|
total = 0
|
||||||
for col in range(row + 1, columns):
|
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
|
return x
|
||||||
|
|
||||||
|
|
|
@ -147,14 +147,14 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:
|
||||||
is_diagonally_dominant = True
|
is_diagonally_dominant = True
|
||||||
|
|
||||||
for i in range(0, rows):
|
for i in range(0, rows):
|
||||||
sum = 0
|
total = 0
|
||||||
for j in range(0, cols - 1):
|
for j in range(0, cols - 1):
|
||||||
if i == j:
|
if i == j:
|
||||||
continue
|
continue
|
||||||
else:
|
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")
|
raise ValueError("Coefficient matrix is not strictly diagonally dominant")
|
||||||
|
|
||||||
return is_diagonally_dominant
|
return is_diagonally_dominant
|
||||||
|
|
|
@ -34,7 +34,7 @@ def get_bounds(
|
||||||
return lowest, highest
|
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
|
Show frequency response of a filter
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ def show_frequency_response(filter: FilterType, samplerate: int) -> None:
|
||||||
|
|
||||||
size = 512
|
size = 512
|
||||||
inputs = [1] + [0] * (size - 1)
|
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
|
filler = [0] * (samplerate - size) # zero-padding
|
||||||
outputs += filler
|
outputs += filler
|
||||||
|
@ -66,7 +66,7 @@ def show_frequency_response(filter: FilterType, samplerate: int) -> None:
|
||||||
plt.show()
|
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
|
Show phase response of a filter
|
||||||
|
|
||||||
|
@ -77,7 +77,7 @@ def show_phase_response(filter: FilterType, samplerate: int) -> None:
|
||||||
|
|
||||||
size = 512
|
size = 512
|
||||||
inputs = [1] + [0] * (size - 1)
|
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
|
filler = [0] * (samplerate - size) # zero-padding
|
||||||
outputs += filler
|
outputs += filler
|
||||||
|
|
|
@ -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
|
return graph[path[curr_ind - 1]][path[0]] == 1
|
||||||
|
|
||||||
# Recursive Step
|
# Recursive Step
|
||||||
for next in range(0, len(graph)):
|
for next_ver in range(0, len(graph)):
|
||||||
if valid_connection(graph, next, curr_ind, path):
|
if valid_connection(graph, next_ver, curr_ind, path):
|
||||||
# Insert current vertex into path as next transition
|
# Insert current vertex into path as next transition
|
||||||
path[curr_ind] = next
|
path[curr_ind] = next_ver
|
||||||
# Validate created path
|
# Validate created path
|
||||||
if util_hamilton_cycle(graph, path, curr_ind + 1):
|
if util_hamilton_cycle(graph, path, curr_ind + 1):
|
||||||
return True
|
return True
|
||||||
|
|
|
@ -33,7 +33,7 @@ class MyQueue:
|
||||||
def count(self) -> int:
|
def count(self) -> int:
|
||||||
return self.tail - self.head
|
return self.tail - self.head
|
||||||
|
|
||||||
def print(self) -> None:
|
def print_queue(self) -> None:
|
||||||
print(self.data)
|
print(self.data)
|
||||||
print("**************")
|
print("**************")
|
||||||
print(self.data[self.head : self.tail])
|
print(self.data[self.head : self.tail])
|
||||||
|
|
|
@ -11,7 +11,7 @@ from typing import Any
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
def __init__(self, item: Any, next: Any) -> None:
|
def __init__(self, item: Any, next: Any) -> None: # noqa: A002
|
||||||
self.item = item
|
self.item = item
|
||||||
self.next = next
|
self.next = next
|
||||||
|
|
||||||
|
|
|
@ -392,7 +392,7 @@ def test_singly_linked_list_2() -> None:
|
||||||
This section of the test used varying data types for input.
|
This section of the test used varying data types for input.
|
||||||
>>> test_singly_linked_list_2()
|
>>> test_singly_linked_list_2()
|
||||||
"""
|
"""
|
||||||
input = [
|
test_input = [
|
||||||
-9,
|
-9,
|
||||||
100,
|
100,
|
||||||
Node(77345112),
|
Node(77345112),
|
||||||
|
@ -410,7 +410,7 @@ def test_singly_linked_list_2() -> None:
|
||||||
]
|
]
|
||||||
linked_list = LinkedList()
|
linked_list = LinkedList()
|
||||||
|
|
||||||
for i in input:
|
for i in test_input:
|
||||||
linked_list.insert_tail(i)
|
linked_list.insert_tail(i)
|
||||||
|
|
||||||
# Check if it's empty or not
|
# Check if it's empty or not
|
||||||
|
|
|
@ -15,8 +15,8 @@ class Deque:
|
||||||
----------
|
----------
|
||||||
append(val: Any) -> None
|
append(val: Any) -> None
|
||||||
appendleft(val: Any) -> None
|
appendleft(val: Any) -> None
|
||||||
extend(iter: Iterable) -> None
|
extend(iterable: Iterable) -> None
|
||||||
extendleft(iter: Iterable) -> None
|
extendleft(iterable: Iterable) -> None
|
||||||
pop() -> Any
|
pop() -> Any
|
||||||
popleft() -> Any
|
popleft() -> Any
|
||||||
Observers
|
Observers
|
||||||
|
@ -179,9 +179,9 @@ class Deque:
|
||||||
# make sure there were no errors
|
# make sure there were no errors
|
||||||
assert not self.is_empty(), "Error on appending value."
|
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)
|
Time complexity: O(n)
|
||||||
>>> our_deque_1 = Deque([1, 2, 3])
|
>>> our_deque_1 = Deque([1, 2, 3])
|
||||||
>>> our_deque_1.extend([4, 5])
|
>>> our_deque_1.extend([4, 5])
|
||||||
|
@ -205,12 +205,12 @@ class Deque:
|
||||||
>>> list(our_deque_2) == list(deque_collections_2)
|
>>> list(our_deque_2) == list(deque_collections_2)
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
for val in iter:
|
for val in iterable:
|
||||||
self.append(val)
|
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)
|
Time complexity: O(n)
|
||||||
>>> our_deque_1 = Deque([1, 2, 3])
|
>>> our_deque_1 = Deque([1, 2, 3])
|
||||||
>>> our_deque_1.extendleft([0, -1])
|
>>> our_deque_1.extendleft([0, -1])
|
||||||
|
@ -234,7 +234,7 @@ class Deque:
|
||||||
>>> list(our_deque_2) == list(deque_collections_2)
|
>>> list(our_deque_2) == list(deque_collections_2)
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
for val in iter:
|
for val in iterable:
|
||||||
self.appendleft(val)
|
self.appendleft(val)
|
||||||
|
|
||||||
def pop(self) -> Any:
|
def pop(self) -> Any:
|
||||||
|
|
|
@ -17,12 +17,12 @@ def next_greatest_element_slow(arr: list[float]) -> list[float]:
|
||||||
arr_size = len(arr)
|
arr_size = len(arr)
|
||||||
|
|
||||||
for i in range(arr_size):
|
for i in range(arr_size):
|
||||||
next: float = -1
|
next_element: float = -1
|
||||||
for j in range(i + 1, arr_size):
|
for j in range(i + 1, arr_size):
|
||||||
if arr[i] < arr[j]:
|
if arr[i] < arr[j]:
|
||||||
next = arr[j]
|
next_element = arr[j]
|
||||||
break
|
break
|
||||||
result.append(next)
|
result.append(next_element)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@ -36,12 +36,12 @@ def next_greatest_element_fast(arr: list[float]) -> list[float]:
|
||||||
"""
|
"""
|
||||||
result = []
|
result = []
|
||||||
for i, outer in enumerate(arr):
|
for i, outer in enumerate(arr):
|
||||||
next: float = -1
|
next_item: float = -1
|
||||||
for inner in arr[i + 1 :]:
|
for inner in arr[i + 1 :]:
|
||||||
if outer < inner:
|
if outer < inner:
|
||||||
next = inner
|
next_item = inner
|
||||||
break
|
break
|
||||||
result.append(next)
|
result.append(next_item)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -497,9 +497,9 @@ class IndexCalculation:
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=77
|
https://www.indexdatabase.de/db/i-single.php?id=77
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
max = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)])
|
max_value = 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)])
|
min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)])
|
||||||
return (max - min) / max
|
return (max_value - min_value) / max_value
|
||||||
|
|
||||||
def _if(self):
|
def _if(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -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)]
|
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
|
# sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes
|
||||||
# array
|
# 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
|
# 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)]
|
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
|
j = i + interval_length - 1
|
||||||
|
|
||||||
dp[i][j] = sys.maxsize # set the value to "infinity"
|
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
|
# Apply Knuth's optimization
|
||||||
# Loop without optimization: for r in range(i, j + 1):
|
# 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
|
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
|
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
|
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:
|
if dp[i][j] > cost:
|
||||||
dp[i][j] = cost
|
dp[i][j] = cost
|
||||||
|
|
|
@ -40,10 +40,10 @@ def search(
|
||||||
else: # to choose the least costliest action so as to move closer to the goal
|
else: # to choose the least costliest action so as to move closer to the goal
|
||||||
cell.sort()
|
cell.sort()
|
||||||
cell.reverse()
|
cell.reverse()
|
||||||
next = cell.pop()
|
next_cell = cell.pop()
|
||||||
x = next[2]
|
x = next_cell[2]
|
||||||
y = next[3]
|
y = next_cell[3]
|
||||||
g = next[1]
|
g = next_cell[1]
|
||||||
|
|
||||||
if x == goal[0] and y == goal[1]:
|
if x == goal[0] and y == goal[1]:
|
||||||
found = True
|
found = True
|
||||||
|
|
|
@ -56,8 +56,8 @@ def dijkstra(graph, start, end):
|
||||||
for v, c in graph[u]:
|
for v, c in graph[u]:
|
||||||
if v in visited:
|
if v in visited:
|
||||||
continue
|
continue
|
||||||
next = cost + c
|
next_item = cost + c
|
||||||
heapq.heappush(heap, (next, v))
|
heapq.heappush(heap, (next_item, v))
|
||||||
return -1
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -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
|
n = len(graph) # No of vertices in graph
|
||||||
low = [0] * n
|
low = [0] * n
|
||||||
visited = [False] * n
|
visited = [False] * n
|
||||||
|
|
||||||
def dfs(at, parent, bridges, id):
|
def dfs(at, parent, bridges, id_):
|
||||||
visited[at] = True
|
visited[at] = True
|
||||||
low[at] = id
|
low[at] = id_
|
||||||
id += 1
|
id_ += 1
|
||||||
for to in graph[at]:
|
for to in graph[at]:
|
||||||
if to == parent:
|
if to == parent:
|
||||||
pass
|
pass
|
||||||
elif not visited[to]:
|
elif not visited[to]:
|
||||||
dfs(to, at, bridges, id)
|
dfs(to, at, bridges, id_)
|
||||||
low[at] = min(low[at], low[to])
|
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))
|
bridges.append((at, to) if at < to else (to, at))
|
||||||
else:
|
else:
|
||||||
# This edge is a back edge and cannot be a bridge
|
# This edge is a back edge and cannot be a bridge
|
||||||
|
@ -96,7 +96,7 @@ def compute_bridges(graph: dict[int, list[int]]) -> list[tuple[int, int]]:
|
||||||
bridges: list[tuple[int, int]] = []
|
bridges: list[tuple[int, int]] = []
|
||||||
for i in range(n):
|
for i in range(n):
|
||||||
if not visited[i]:
|
if not visited[i]:
|
||||||
dfs(i, -1, bridges, id)
|
dfs(i, -1, bridges, id_)
|
||||||
return bridges
|
return bridges
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -13,7 +13,7 @@ from collections.abc import Iterator
|
||||||
class Vertex:
|
class Vertex:
|
||||||
"""Class Vertex."""
|
"""Class Vertex."""
|
||||||
|
|
||||||
def __init__(self, id):
|
def __init__(self, id_):
|
||||||
"""
|
"""
|
||||||
Arguments:
|
Arguments:
|
||||||
id - input an id to identify the vertex
|
id - input an id to identify the vertex
|
||||||
|
@ -21,7 +21,7 @@ class Vertex:
|
||||||
neighbors - a list of the vertices it is linked to
|
neighbors - a list of the vertices it is linked to
|
||||||
edges - a dict to store the edges's weight
|
edges - a dict to store the edges's weight
|
||||||
"""
|
"""
|
||||||
self.id = str(id)
|
self.id = str(id_)
|
||||||
self.key = None
|
self.key = None
|
||||||
self.pi = None
|
self.pi = None
|
||||||
self.neighbors = []
|
self.neighbors = []
|
||||||
|
|
|
@ -29,7 +29,7 @@ def djb2(s: str) -> int:
|
||||||
>>> djb2('scramble bits')
|
>>> djb2('scramble bits')
|
||||||
1609059040
|
1609059040
|
||||||
"""
|
"""
|
||||||
hash = 5381
|
hash_value = 5381
|
||||||
for x in s:
|
for x in s:
|
||||||
hash = ((hash << 5) + hash) + ord(x)
|
hash_value = ((hash_value << 5) + hash_value) + ord(x)
|
||||||
return hash & 0xFFFFFFFF
|
return hash_value & 0xFFFFFFFF
|
||||||
|
|
|
@ -31,7 +31,9 @@ def sdbm(plain_text: str) -> int:
|
||||||
>>> sdbm('scramble bits')
|
>>> sdbm('scramble bits')
|
||||||
730247649148944819640658295400555317318720608290373040936089
|
730247649148944819640658295400555317318720608290373040936089
|
||||||
"""
|
"""
|
||||||
hash = 0
|
hash_value = 0
|
||||||
for plain_chr in plain_text:
|
for plain_chr in plain_text:
|
||||||
hash = ord(plain_chr) + (hash << 6) + (hash << 16) - hash
|
hash_value = (
|
||||||
return hash
|
ord(plain_chr) + (hash_value << 6) + (hash_value << 16) - hash_value
|
||||||
|
)
|
||||||
|
return hash_value
|
||||||
|
|
|
@ -25,7 +25,7 @@ def armstrong_number(n: int) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Initialization of sum and number of digits.
|
# Initialization of sum and number of digits.
|
||||||
sum = 0
|
total = 0
|
||||||
number_of_digits = 0
|
number_of_digits = 0
|
||||||
temp = n
|
temp = n
|
||||||
# Calculation of digits of the number
|
# Calculation of digits of the number
|
||||||
|
@ -36,9 +36,9 @@ def armstrong_number(n: int) -> bool:
|
||||||
temp = n
|
temp = n
|
||||||
while temp > 0:
|
while temp > 0:
|
||||||
rem = temp % 10
|
rem = temp % 10
|
||||||
sum += rem**number_of_digits
|
total += rem**number_of_digits
|
||||||
temp //= 10
|
temp //= 10
|
||||||
return n == sum
|
return n == total
|
||||||
|
|
||||||
|
|
||||||
def pluperfect_number(n: int) -> bool:
|
def pluperfect_number(n: int) -> bool:
|
||||||
|
@ -55,7 +55,7 @@ def pluperfect_number(n: int) -> bool:
|
||||||
# Init a "histogram" of the digits
|
# Init a "histogram" of the digits
|
||||||
digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||||
digit_total = 0
|
digit_total = 0
|
||||||
sum = 0
|
total = 0
|
||||||
temp = n
|
temp = n
|
||||||
while temp > 0:
|
while temp > 0:
|
||||||
temp, rem = divmod(temp, 10)
|
temp, rem = divmod(temp, 10)
|
||||||
|
@ -63,9 +63,9 @@ def pluperfect_number(n: int) -> bool:
|
||||||
digit_total += 1
|
digit_total += 1
|
||||||
|
|
||||||
for (cnt, i) in zip(digit_histogram, range(len(digit_histogram))):
|
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:
|
def narcissistic_number(n: int) -> bool:
|
||||||
|
|
|
@ -67,7 +67,7 @@ def _subsum(
|
||||||
@param precision: same as precision in main function
|
@param precision: same as precision in main function
|
||||||
@return: floating-point number whose integer part is not important
|
@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):
|
for sum_index in range(digit_pos_to_extract + precision):
|
||||||
denominator = 8 * sum_index + denominator_addend
|
denominator = 8 * sum_index + denominator_addend
|
||||||
if sum_index < digit_pos_to_extract:
|
if sum_index < digit_pos_to_extract:
|
||||||
|
@ -79,8 +79,8 @@ def _subsum(
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index)
|
exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index)
|
||||||
sum += exponential_term / denominator
|
total += exponential_term / denominator
|
||||||
return sum
|
return total
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -14,13 +14,13 @@ def negative_exist(arr: list) -> int:
|
||||||
[-2, 0, 0, 0, 0]
|
[-2, 0, 0, 0, 0]
|
||||||
"""
|
"""
|
||||||
arr = arr or [0]
|
arr = arr or [0]
|
||||||
max = arr[0]
|
max_number = arr[0]
|
||||||
for i in arr:
|
for i in arr:
|
||||||
if i >= 0:
|
if i >= 0:
|
||||||
return 0
|
return 0
|
||||||
elif max <= i:
|
elif max_number <= i:
|
||||||
max = i
|
max_number = i
|
||||||
return max
|
return max_number
|
||||||
|
|
||||||
|
|
||||||
def kadanes(arr: list) -> int:
|
def kadanes(arr: list) -> int:
|
||||||
|
|
|
@ -2,7 +2,7 @@ import math
|
||||||
from collections.abc import Generator
|
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.
|
Return a list of all primes numbers up to max.
|
||||||
>>> list(slow_primes(0))
|
>>> list(slow_primes(0))
|
||||||
|
@ -20,7 +20,7 @@ def slow_primes(max: int) -> Generator[int, None, None]:
|
||||||
>>> list(slow_primes(10000))[-1]
|
>>> list(slow_primes(10000))[-1]
|
||||||
9973
|
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 i in (n for n in numbers if n > 1):
|
||||||
for j in range(2, i):
|
for j in range(2, i):
|
||||||
if (i % j) == 0:
|
if (i % j) == 0:
|
||||||
|
@ -29,7 +29,7 @@ def slow_primes(max: int) -> Generator[int, None, None]:
|
||||||
yield i
|
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.
|
Return a list of all primes numbers up to max.
|
||||||
>>> list(primes(0))
|
>>> list(primes(0))
|
||||||
|
@ -47,7 +47,7 @@ def primes(max: int) -> Generator[int, None, None]:
|
||||||
>>> list(primes(10000))[-1]
|
>>> list(primes(10000))[-1]
|
||||||
9973
|
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 i in (n for n in numbers if n > 1):
|
||||||
# only need to check for factors up to sqrt(i)
|
# only need to check for factors up to sqrt(i)
|
||||||
bound = int(math.sqrt(i)) + 1
|
bound = int(math.sqrt(i)) + 1
|
||||||
|
@ -58,7 +58,7 @@ def primes(max: int) -> Generator[int, None, None]:
|
||||||
yield i
|
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.
|
Return a list of all primes numbers up to max.
|
||||||
>>> list(fast_primes(0))
|
>>> list(fast_primes(0))
|
||||||
|
@ -76,9 +76,9 @@ def fast_primes(max: int) -> Generator[int, None, None]:
|
||||||
>>> list(fast_primes(10000))[-1]
|
>>> list(fast_primes(10000))[-1]
|
||||||
9973
|
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
|
# 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
|
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):
|
for i in (n for n in numbers if n > 1):
|
||||||
bound = int(math.sqrt(i)) + 1
|
bound = int(math.sqrt(i)) + 1
|
||||||
|
|
|
@ -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)
|
>>> sum_of_series(1, 10, 100)
|
||||||
49600.0
|
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
|
# formula for sum of series
|
||||||
return sum
|
return total
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|
|
@ -182,7 +182,7 @@ class TwoHiddenLayerNeuralNetwork:
|
||||||
loss = numpy.mean(numpy.square(output - self.feedforward()))
|
loss = numpy.mean(numpy.square(output - self.feedforward()))
|
||||||
print(f"Iteration {iteration} Loss: {loss}")
|
print(f"Iteration {iteration} Loss: {loss}")
|
||||||
|
|
||||||
def predict(self, input: numpy.ndarray) -> int:
|
def predict(self, input_arr: numpy.ndarray) -> int:
|
||||||
"""
|
"""
|
||||||
Predict's the output for the given input values using
|
Predict's the output for the given input values using
|
||||||
the trained neural network.
|
the trained neural network.
|
||||||
|
@ -201,7 +201,7 @@ class TwoHiddenLayerNeuralNetwork:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Input values for which the predictions are to be made.
|
# Input values for which the predictions are to be made.
|
||||||
self.array = input
|
self.array = input_arr
|
||||||
|
|
||||||
self.layer_between_input_and_first_hidden_layer = sigmoid(
|
self.layer_between_input_and_first_hidden_layer = sigmoid(
|
||||||
numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights)
|
numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights)
|
||||||
|
@ -264,7 +264,7 @@ def example() -> int:
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
# Input values.
|
# Input values.
|
||||||
input = numpy.array(
|
test_input = numpy.array(
|
||||||
(
|
(
|
||||||
[0, 0, 0],
|
[0, 0, 0],
|
||||||
[0, 0, 1],
|
[0, 0, 1],
|
||||||
|
@ -282,7 +282,9 @@ def example() -> int:
|
||||||
output = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.float64)
|
output = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.float64)
|
||||||
|
|
||||||
# Calling neural network class.
|
# 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.
|
# Calling training function.
|
||||||
# Set give_loss to True if you want to see loss in every iteration.
|
# Set give_loss to True if you want to see loss in every iteration.
|
||||||
|
|
|
@ -140,24 +140,24 @@ class CNN:
|
||||||
focus_list = np.asarray(focus1_list)
|
focus_list = np.asarray(focus1_list)
|
||||||
return focus_list, data_featuremap
|
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
|
# pooling process
|
||||||
size_map = len(featuremaps[0])
|
size_map = len(featuremaps[0])
|
||||||
size_pooled = int(size_map / size_pooling)
|
size_pooled = int(size_map / size_pooling)
|
||||||
featuremap_pooled = []
|
featuremap_pooled = []
|
||||||
for i_map in range(len(featuremaps)):
|
for i_map in range(len(featuremaps)):
|
||||||
map = featuremaps[i_map]
|
feature_map = featuremaps[i_map]
|
||||||
map_pooled = []
|
map_pooled = []
|
||||||
for i_focus in range(0, size_map, size_pooling):
|
for i_focus in range(0, size_map, size_pooling):
|
||||||
for j_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,
|
i_focus : i_focus + size_pooling,
|
||||||
j_focus : j_focus + size_pooling,
|
j_focus : j_focus + size_pooling,
|
||||||
]
|
]
|
||||||
if type == "average_pool":
|
if pooling_type == "average_pool":
|
||||||
# average pooling
|
# average pooling
|
||||||
map_pooled.append(np.average(focus))
|
map_pooled.append(np.average(focus))
|
||||||
elif type == "max_pooling":
|
elif pooling_type == "max_pooling":
|
||||||
# max pooling
|
# max pooling
|
||||||
map_pooled.append(np.max(focus))
|
map_pooled.append(np.max(focus))
|
||||||
map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled)
|
map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled)
|
||||||
|
|
|
@ -182,7 +182,7 @@ samples = [
|
||||||
[0.2012, 0.2611, 5.4631],
|
[0.2012, 0.2611, 5.4631],
|
||||||
]
|
]
|
||||||
|
|
||||||
exit = [
|
target = [
|
||||||
-1,
|
-1,
|
||||||
-1,
|
-1,
|
||||||
-1,
|
-1,
|
||||||
|
@ -222,7 +222,7 @@ if __name__ == "__main__":
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
|
|
||||||
network = Perceptron(
|
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()
|
network.training()
|
||||||
print("Finished training perceptron")
|
print("Finished training perceptron")
|
||||||
|
|
|
@ -71,7 +71,7 @@ def sum_digits(num: int) -> int:
|
||||||
return digit_sum
|
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
|
Returns the sum of the digits in the numerator of the max-th convergent of
|
||||||
the continued fraction for e.
|
the continued fraction for e.
|
||||||
|
@ -86,7 +86,7 @@ def solution(max: int = 100) -> int:
|
||||||
pre_numerator = 1
|
pre_numerator = 1
|
||||||
cur_numerator = 2
|
cur_numerator = 2
|
||||||
|
|
||||||
for i in range(2, max + 1):
|
for i in range(2, max_n + 1):
|
||||||
temp = pre_numerator
|
temp = pre_numerator
|
||||||
e_cont = 2 * i // 3 if i % 3 == 0 else 1
|
e_cont = 2 * i // 3 if i % 3 == 0 else 1
|
||||||
pre_numerator = cur_numerator
|
pre_numerator = cur_numerator
|
||||||
|
|
|
@ -72,7 +72,7 @@ def has_same_digits(num1: int, num2: int) -> bool:
|
||||||
return sorted(str(num1)) == sorted(str(num2))
|
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.
|
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_numerator = 1 # i
|
||||||
min_denominator = 0 # φ(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]
|
t = totients[i]
|
||||||
|
|
||||||
if i * min_denominator < min_numerator * t and has_same_digits(i, t):
|
if i * min_denominator < min_numerator * t and has_same_digits(i, t):
|
||||||
|
|
|
@ -20,21 +20,21 @@ def odd_even_sort(input_list: list) -> list:
|
||||||
>>> odd_even_sort([1 ,2 ,3 ,4])
|
>>> odd_even_sort([1 ,2 ,3 ,4])
|
||||||
[1, 2, 3, 4]
|
[1, 2, 3, 4]
|
||||||
"""
|
"""
|
||||||
sorted = False
|
is_sorted = False
|
||||||
while sorted is False: # Until all the indices are traversed keep looping
|
while is_sorted is False: # Until all the indices are traversed keep looping
|
||||||
sorted = True
|
is_sorted = True
|
||||||
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
|
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
|
||||||
if input_list[i] > input_list[i + 1]:
|
if input_list[i] > input_list[i + 1]:
|
||||||
|
|
||||||
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
|
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
|
||||||
# swapping if elements not in order
|
# 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
|
for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices
|
||||||
if input_list[i] > input_list[i + 1]:
|
if input_list[i] > input_list[i + 1]:
|
||||||
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
|
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
|
||||||
# swapping if elements not in order
|
# swapping if elements not in order
|
||||||
sorted = False
|
is_sorted = False
|
||||||
return input_list
|
return input_list
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -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)
|
Transforms a snake_case given string to camelCase (or PascalCase if indicated)
|
||||||
(defaults to not use Pascal)
|
(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 <class 'str'>
|
ValueError: Expected boolean as use_pascal parameter, found <class 'str'>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not isinstance(input, str):
|
if not isinstance(input_str, str):
|
||||||
raise ValueError(f"Expected string as input, found {type(input)}")
|
raise ValueError(f"Expected string as input, found {type(input_str)}")
|
||||||
if not isinstance(use_pascal, bool):
|
if not isinstance(use_pascal, bool):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Expected boolean as use_pascal parameter, found {type(use_pascal)}"
|
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
|
start_index = 0 if use_pascal else 1
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user