Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
[pre-commit.ci] pre-commit autoupdate by pre-commit-ci[bot] · Pull Request #9013 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate by pre-commit-ci[bot] · Pull Request #9013 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate by pre-commit-ci[bot] · Pull Request #9013 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' [pre-commit.ci] pre-commit autoupdate by pre-commit-ci[bot] · Pull Request #9013 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate by pre-commit-ci[bot] · Pull Request #9013 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [pre-commit.ci] pre-commit autoupdate by pre-commit-ci[bot] · Pull Request #9013 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); [pre-commit.ci] pre-commit autoupdate by pre-commit-ci[bot] · Pull Request #9013 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff

Expand All@@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.1"
rev: "1.1.0"
hooks:
- id: pyproject-fmt

Expand Down
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
Expand Down
4 changes: 2 additions & 2 deletions arithmetic_analysis/jacobi_iteration_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:

is_diagonally_dominant = True

for i in range(0, rows):
for i in range(rows):
total = 0
for j in range(0, cols - 1):
for j in range(cols - 1):
if i == j:
continue
else:
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/secant_method.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
"""
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
for _ in range(repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1

Expand Down
2 changes: 1 addition & 1 deletion backtracking/hamiltonian_cycle.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,7 @@ 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_ver in range(0, len(graph)):
for next_ver in range(len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
if n in {grid[row][i], grid[i][column]}:
return False

for i in range(3):
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/reverse_bits.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
)
raise TypeError(msg)
bit_string = ""
for _ in range(0, 32):
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,7 @@ def decrypt_message(
for i in range(0, len(message) + 1, period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)

for j in range(0, len(a)):
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])

for each in decrypted_numeric:
Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,10 @@ class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
self.segment_tree = [0 for i in range(4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
self.lazy = [0 for i in range(4 * size)]
self.flag = [0 for i in range(4 * size)] # flag for lazy update

def left(self, idx: int) -> int:
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/circular_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -125,7 +125,7 @@ def test_circular_linked_list() -> None:
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7))
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))

assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
Expand Down
6 changes: 3 additions & 3 deletions data_structures/linked_list/doubly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,7 +98,7 @@ def insert_at_nth(self, index: int, data):
self.tail = new_node
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
Expand DownExpand Up@@ -149,7 +149,7 @@ def delete_at_nth(self, index: int):
self.tail.next = None
else:
temp = self.head
for _ in range(0, index):
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
Expand DownExpand Up@@ -215,7 +215,7 @@ def test_doubly_linked_list() -> None:

linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/is_palindrome.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ def is_palindrome_dict(head):
middle += 1
else:
step = 0
for i in range(0, len(v)):
for i in range(len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
Expand Down
8 changes: 4 additions & 4 deletions data_structures/linked_list/singly_linked_list.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -370,19 +370,19 @@ def test_singly_linked_list() -> None:

linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert str(linked_list) == "->".join(str(i) for i in range(12))

assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))

assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
assert all(linked_list[i] == i + 1 for i in range(9)) is True

for i in range(0, 9):
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
assert all(linked_list[i] == -i for i in range(9)) is True

linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stock_span_problem.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ def calculation_span(price, s):

# A utility function to print elements of array
def print_array(arr, n):
for i in range(0, n):
for i in range(n):
print(arr[i], end=" ")


Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/bilateral_filter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,8 +31,8 @@ def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:
def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
arr = np.zeros((kernel_size, kernel_size))
for i in range(0, kernel_size):
for j in range(0, kernel_size):
for i in range(kernel_size):
for j in range(kernel_size):
arr[i, j] = math.sqrt(
abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2
)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/convolve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,8 +11,8 @@ def im2col(image, block_size):
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
for i in range(dst_height):
for j in range(dst_width):
window = ravel(image[i : i + block_size[0], j : j + block_size[1]])
image_array[row, :] = window
row += 1
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/filters/local_binary_pattern.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,8 +71,8 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)

# Iterating through the image and calculating the
# local binary pattern value for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = local_binary_value(image, i, j)

cv2.imshow("local binary pattern", lbp_image)
Expand Down
4 changes: 2 additions & 2 deletions digital_image_processing/test_digital_image_processing.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -118,8 +118,8 @@ def test_local_binary_pattern():

# Iterating through the image and calculating the local binary pattern value
# for each pixel.
for i in range(0, image.shape[0]):
for j in range(0, image.shape[1]):
for i in range(image.shape[0]):
for j in range(image.shape[1]):
lbp_image[i][j] = lbp.local_binary_value(image, i, j)

assert lbp_image.any()
4 changes: 2 additions & 2 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -131,7 +131,7 @@ def strassen(matrix1: list, matrix2: list) -> list:

# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
Expand All@@ -146,7 +146,7 @@ def strassen(matrix1: list, matrix2: list) -> list:
final_matrix = actual_strassen(new_matrix1, new_matrix2)

# Removing the additional zeros
for i in range(0, maxim):
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
Expand Down
10 changes: 5 additions & 5 deletions dynamic_programming/floyd_warshall.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,19 +5,19 @@ class Graph:
def __init__(self, n=0): # a graph with Node 0,1,...,N-1
self.n = n
self.w = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # adjacency matrix for weight
self.dp = [
[math.inf for j in range(0, n)] for i in range(0, n)
[math.inf for j in range(n)] for i in range(n)
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
self.dp[u][v] = w

def floyd_warshall(self):
for k in range(0, self.n):
for i in range(0, self.n):
for j in range(0, self.n):
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,7 +53,7 @@ def xorshift(x, y):
key = machine_time % m

# Evolution (Time Length)
for _ in range(0, t):
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
Expand Down
4 changes: 2 additions & 2 deletions hashes/hamming_code.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,7 +135,7 @@ def emitter_converter(size_par, data):

# Mount the message
cont_bp = 0 # parity bit counter
for x in range(0, size_par + len(data)):
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand DownExpand Up@@ -228,7 +228,7 @@ def receptor_converter(size_par, data):

# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(0, size_par + len(data_output)):
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha1.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(0, 80):
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
Expand Down
2 changes: 1 addition & 1 deletion hashes/sha256.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def final_hash(self) -> None:

a, b, c, d, e, f, g, h = self.hashes

for index in range(0, 64):
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/gradient_descent.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@ def run_gradient_descent():
while True:
j += 1
temp_parameter_vector = [0, 0, 0, 0]
for i in range(0, len(parameter_vector)):
for i in range(len(parameter_vector)):
cost_derivative = get_cost_derivative(i - 1)
temp_parameter_vector[i] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/linear_regression.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ def run_linear_regression(data_x, data_y):

theta = np.zeros((1, no_features))

for i in range(0, iterations):
for i in range(iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
Expand DownExpand Up@@ -107,7 +107,7 @@ def main():
theta = run_linear_regression(data_x, data_y)
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
for i in range(len_result):
print(f"{theta[0, i]:.5f}")


Expand Down
4 changes: 2 additions & 2 deletions machine_learning/lstm/lstm_prediction.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,10 @@
train_x, train_y = [], []
test_x, test_y = [], []

for i in range(0, len(train_data) - forward_days - look_back + 1):
for i in range(len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
for i in range(len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
x_train = np.array(train_x)
Expand Down
2 changes: 1 addition & 1 deletion maths/entropy.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ def analyze_text(text: str) -> tuple[dict, dict]:

# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
for i in range(len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
Expand Down
2 changes: 1 addition & 1 deletion maths/eulers_totient.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ def totient(n: int) -> list:
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
Expand Down
2 changes: 1 addition & 1 deletion maths/greedy_coin_change.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,7 +81,7 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
):
n = int(input("Enter the number of denominations you want to add: ").strip())

for i in range(0, n):
for i in range(n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
Expand Down
4 changes: 2 additions & 2 deletions maths/persistence.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ def multiplicative_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 1
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total *= numbers[i]

num_string = str(total)
Expand DownExpand Up@@ -67,7 +67,7 @@ def additive_persistence(num: int) -> int:
numbers = [int(i) for i in num_string]

total = 0
for i in range(0, len(numbers)):
for i in range(len(numbers)):
total += numbers[i]

num_string = str(total)
Expand Down
Loading