Skip to content

Commit f32d611

Browse files
authored
clean of unnecessary checks, imports, calls (TheAlgorithms#7993)
1 parent a25c53e commit f32d611

27 files changed

+44
-57
lines changed

backtracking/rat_in_maze.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,12 @@ def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]])
8888
solutions[i][j] = 1
8989
return True
9090

91-
lower_flag = (not (i < 0)) and (not (j < 0)) # Check lower bounds
91+
lower_flag = (not i < 0) and (not j < 0) # Check lower bounds
9292
upper_flag = (i < size) and (j < size) # Check upper bounds
9393

9494
if lower_flag and upper_flag:
9595
# check for already visited and block points.
96-
block_flag = (not (solutions[i][j])) and (not (maze[i][j]))
96+
block_flag = (not solutions[i][j]) and (not maze[i][j])
9797
if block_flag:
9898
# check visited
9999
solutions[i][j] = 1

boolean_algebra/not_gate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,4 @@ def test_not_gate() -> None:
3434

3535
if __name__ == "__main__":
3636
print(not_gate(0))
37-
print(not_gate(1))
37+
print(not_gate(1))

cellular_automata/nagel_schrekenberg.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ def construct_highway(
4545

4646
highway = [[-1] * number_of_cells] # Create a highway without any car
4747
i = 0
48-
if initial_speed < 0:
49-
initial_speed = 0
48+
initial_speed = max(initial_speed, 0)
5049
while i < number_of_cells:
5150
highway[0][i] = (
5251
randint(0, max_speed) if random_speed else initial_speed

ciphers/mixed_keyword_cypher.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
4242
s = []
4343
for _ in range(len_temp):
4444
s.append(temp[k])
45-
if not (k < 25):
45+
if k >= 25:
4646
break
4747
k += 1
4848
modalpha.append(s)
@@ -52,7 +52,7 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
5252
k = 0
5353
for j in range(len_temp):
5454
for m in modalpha:
55-
if not (len(m) - 1 >= j):
55+
if not len(m) - 1 >= j:
5656
break
5757
d[alpha[k]] = m[j]
5858
if not k < 25:

compression/huffman.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:
5656
Recursively traverse the Huffman Tree to set each
5757
Letter's bitstring dictionary, and return the list of Letters
5858
"""
59-
if type(root) is Letter:
59+
if isinstance(root, Letter):
6060
root.bitstring[root.letter] = bitstring
6161
return [root]
6262
treenode: TreeNode = root # type: ignore

data_structures/heap/min_heap.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def insert(self, node):
121121
self.sift_up(len(self.heap) - 1)
122122

123123
def is_empty(self):
124-
return True if len(self.heap) == 0 else False
124+
return len(self.heap) == 0
125125

126126
def decrease_key(self, node, new_value):
127127
assert (

digital_image_processing/test_digital_image_processing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from digital_image_processing import convert_to_negative as cn
1111
from digital_image_processing import sepia as sp
1212
from digital_image_processing.dithering import burkes as bs
13-
from digital_image_processing.edge_detection import canny as canny
13+
from digital_image_processing.edge_detection import canny
1414
from digital_image_processing.filters import convolve as conv
1515
from digital_image_processing.filters import gaussian_filter as gg
1616
from digital_image_processing.filters import local_binary_pattern as lbp

dynamic_programming/fizz_buzz.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,9 @@ def fizz_buzz(number: int, iterations: int) -> str:
3333
...
3434
ValueError: iterations must be defined as integers
3535
"""
36-
37-
if not type(iterations) == int:
36+
if not isinstance(iterations, int):
3837
raise ValueError("iterations must be defined as integers")
39-
if not type(number) == int or not number >= 1:
38+
if not isinstance(number, int) or not number >= 1:
4039
raise ValueError(
4140
"""starting number must be
4241
and integer and be more than 0"""

dynamic_programming/max_sub_array.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,7 @@ def max_sub_array(nums: list[int]) -> int:
6262
current = 0
6363
for i in nums:
6464
current += i
65-
if current < 0:
66-
current = 0
65+
current = max(current, 0)
6766
best = max(best, current)
6867
return best
6968

graphs/directed_and_undirected_(weighted)_graph.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def cycle_nodes(self):
167167
and not on_the_way_back
168168
):
169169
len_stack = len(stack) - 1
170-
while True and len_stack >= 0:
170+
while len_stack >= 0:
171171
if stack[len_stack] == node[1]:
172172
anticipating_nodes.add(node[1])
173173
break
@@ -220,7 +220,7 @@ def has_cycle(self):
220220
and not on_the_way_back
221221
):
222222
len_stack_minus_one = len(stack) - 1
223-
while True and len_stack_minus_one >= 0:
223+
while len_stack_minus_one >= 0:
224224
if stack[len_stack_minus_one] == node[1]:
225225
anticipating_nodes.add(node[1])
226226
break
@@ -392,7 +392,7 @@ def cycle_nodes(self):
392392
and not on_the_way_back
393393
):
394394
len_stack = len(stack) - 1
395-
while True and len_stack >= 0:
395+
while len_stack >= 0:
396396
if stack[len_stack] == node[1]:
397397
anticipating_nodes.add(node[1])
398398
break
@@ -445,7 +445,7 @@ def has_cycle(self):
445445
and not on_the_way_back
446446
):
447447
len_stack_minus_one = len(stack) - 1
448-
while True and len_stack_minus_one >= 0:
448+
while len_stack_minus_one >= 0:
449449
if stack[len_stack_minus_one] == node[1]:
450450
anticipating_nodes.add(node[1])
451451
break

graphs/multi_heuristic_astar.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import heapq
2+
import sys
23

34
import numpy as np
45

@@ -116,7 +117,7 @@ def do_something(back_pointer, goal, start):
116117
print(x, end=" ")
117118
x = back_pointer[x]
118119
print(x)
119-
quit()
120+
sys.exit()
120121

121122

122123
def valid(p: TPos):

linear_algebra/src/lib.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def component(self, i: int) -> float:
129129
input: index (0-indexed)
130130
output: the i-th component of the vector.
131131
"""
132-
if type(i) is int and -len(self.__components) <= i < len(self.__components):
132+
if isinstance(i, int) and -len(self.__components) <= i < len(self.__components):
133133
return self.__components[i]
134134
else:
135135
raise Exception("index out of range")

machine_learning/sequential_minimum_optimization.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -388,16 +388,10 @@ def _norm(self, data):
388388
return (data - self._min) / (self._max - self._min)
389389

390390
def _is_unbound(self, index):
391-
if 0.0 < self.alphas[index] < self._c:
392-
return True
393-
else:
394-
return False
391+
return bool(0.0 < self.alphas[index] < self._c)
395392

396393
def _is_support(self, index):
397-
if self.alphas[index] > 0:
398-
return True
399-
else:
400-
return False
394+
return bool(self.alphas[index] > 0)
401395

402396
@property
403397
def unbound(self):

maths/find_min.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@ def find_min(nums: list[int | float]) -> int | float:
2424
raise ValueError("find_min() arg is an empty sequence")
2525
min_num = nums[0]
2626
for num in nums:
27-
if min_num > num:
28-
min_num = num
27+
min_num = min(min_num, num)
2928
return min_num
3029

3130

maths/kadanes.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,8 @@ def kadanes(arr: list) -> int:
4949

5050
for i in arr:
5151
max_till_element += i
52-
if max_sum <= max_till_element:
53-
max_sum = max_till_element
54-
if max_till_element < 0:
55-
max_till_element = 0
52+
max_sum = max(max_sum, max_till_element)
53+
max_till_element = max(max_till_element, 0)
5654
return max_sum
5755

5856

maths/largest_subarray_sum.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,8 @@ def max_sub_array_sum(a: list, size: int = 0):
1111
max_ending_here = 0
1212
for i in range(0, size):
1313
max_ending_here = max_ending_here + a[i]
14-
if max_so_far < max_ending_here:
15-
max_so_far = max_ending_here
16-
if max_ending_here < 0:
17-
max_ending_here = 0
14+
max_so_far = max(max_so_far, max_ending_here)
15+
max_ending_here = max(max_ending_here, 0)
1816
return max_so_far
1917

2018

maths/series/geometric_series.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def geometric_series(
5252
power = 1
5353
multiple = common_ratio_r
5454
for _ in range(int(nth_term)):
55-
if series == []:
55+
if not series:
5656
series.append(start_term_a)
5757
else:
5858
power += 1

networking_flow/ford_fulkerson.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def bfs(graph, s, t, parent):
2121
visited[ind] = True
2222
parent[ind] = u
2323

24-
return True if visited[t] else False
24+
return visited[t]
2525

2626

2727
def ford_fulkerson(graph, source, sink):

networking_flow/minimum_cut.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def bfs(graph, s, t, parent):
2424
visited[ind] = True
2525
parent[ind] = u
2626

27-
return True if visited[t] else False
27+
return visited[t]
2828

2929

3030
def mincut(graph, source, sink):

other/password.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,9 @@ def is_strong_password(password: str, min_length: int = 8) -> bool:
8989
num = any(char in digits for char in password)
9090
spec_char = any(char in punctuation for char in password)
9191

92-
if upper and lower and num and spec_char:
93-
return True
94-
95-
else:
96-
# Passwords should contain UPPERCASE, lowerase
97-
# numbers, and special characters
98-
return False
92+
return upper and lower and num and spec_char
93+
# Passwords should contain UPPERCASE, lowerase
94+
# numbers, and special characters
9995

10096

10197
def main():

project_euler/problem_025/sol1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def fibonacci(n: int) -> int:
4343
144
4444
4545
"""
46-
if n == 1 or type(n) is not int:
46+
if n == 1 or not isinstance(n, int):
4747
return 0
4848
elif n == 2:
4949
return 1

project_euler/problem_036/sol1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def is_palindrome(n: int | str) -> bool:
3232
False
3333
"""
3434
n = str(n)
35-
return True if n == n[::-1] else False
35+
return n == n[::-1]
3636

3737

3838
def solution(n: int = 1000000):

quantum/q_fourier_transform.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts
5555
...
5656
ValueError: number of qubits must be exact integer.
5757
"""
58-
if type(number_of_qubits) == str:
58+
if isinstance(number_of_qubits, str):
5959
raise TypeError("number of qubits must be a integer.")
60-
if not number_of_qubits > 0:
60+
if number_of_qubits <= 0:
6161
raise ValueError("number of qubits must be > 0.")
6262
if math.floor(number_of_qubits) != number_of_qubits:
6363
raise ValueError("number of qubits must be exact integer.")

quantum/q_full_adder.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,11 @@ def quantum_full_adder(
6060
...
6161
ValueError: inputs must be less or equal to 2.
6262
"""
63-
if (type(input_1) == str) or (type(input_2) == str) or (type(carry_in) == str):
63+
if (
64+
isinstance(input_1, str)
65+
or isinstance(input_2, str)
66+
or isinstance(carry_in, str)
67+
):
6468
raise TypeError("inputs must be integers.")
6569

6670
if (input_1 < 0) or (input_2 < 0) or (carry_in < 0):

quantum/superdense_coding.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def superdense_coding(bit_1: int = 1, bit_2: int = 1) -> qiskit.result.counts.Co
5353
...
5454
ValueError: inputs must be less or equal to 1.
5555
"""
56-
if (type(bit_1) == str) or (type(bit_2) == str):
56+
if isinstance(bit_1, str) or isinstance(bit_2, str):
5757
raise TypeError("inputs must be integers.")
5858
if (bit_1 < 0) or (bit_2 < 0):
5959
raise ValueError("inputs must be positive.")

sorts/msd_radix_sort.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def _msd_radix_sort_inplace(
133133
j = end_index - 1
134134
while i <= j:
135135
changed = False
136-
if not ((list_of_ints[i] >> bit_position) & 1):
136+
if not (list_of_ints[i] >> bit_position) & 1:
137137
# found zero at the beginning
138138
i += 1
139139
changed = True

strings/aho_corasick.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def search_in(self, string: str) -> dict[str, list[int]]:
8484
else:
8585
current_state = next_state
8686
for key in self.adlist[current_state]["output"]:
87-
if not (key in result):
87+
if key not in result:
8888
result[key] = []
8989
result[key].append(i - len(key) + 1)
9090
return result

0 commit comments

Comments
 (0)