Skip to content

Commit 0469853

Browse files
CenTdemeern1pre-commit-ci[bot]dhruvmanila
authoredOct 16, 2022
Misc fixes across multiple algorithms (TheAlgorithms#6912)
Source: Snyk code quality Add scikit-fuzzy to requirements Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Dhruv Manilawala <[email protected]>
1 parent c94e215 commit 0469853

File tree

19 files changed

+40
-48
lines changed

19 files changed

+40
-48
lines changed
 

‎compression/huffman.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def parse_file(file_path: str) -> list[Letter]:
3131
c = f.read(1)
3232
if not c:
3333
break
34-
chars[c] = chars[c] + 1 if c in chars.keys() else 1
34+
chars[c] = chars[c] + 1 if c in chars else 1
3535
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)
3636

3737

‎data_structures/linked_list/is_palindrome.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def is_palindrome_dict(head):
5555
d = {}
5656
pos = 0
5757
while head:
58-
if head.val in d.keys():
58+
if head.val in d:
5959
d[head.val].append(pos)
6060
else:
6161
d[head.val] = [pos]

‎digital_image_processing/filters/local_binary_pattern.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)
6060
)
6161

6262

63-
if __name__ == "main":
63+
if __name__ == "__main__":
6464

6565
# Reading the image and converting it to grayscale.
6666
image = cv2.imread(

‎fuzzy_logic/fuzzy_operations.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,7 @@
88
- 3.5
99
"""
1010
import numpy as np
11-
12-
try:
13-
import skfuzzy as fuzz
14-
except ImportError:
15-
fuzz = None
11+
import skfuzzy as fuzz
1612

1713
if __name__ == "__main__":
1814
# Create universe of discourse in Python using linspace ()

‎graphs/dijkstra_algorithm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,13 @@ def add_edge(self, u, v, w):
8989
# Edge going from node u to v and v to u with weight w
9090
# u (w)-> v, v (w) -> u
9191
# Check if u already in graph
92-
if u in self.adjList.keys():
92+
if u in self.adjList:
9393
self.adjList[u].append((v, w))
9494
else:
9595
self.adjList[u] = [(v, w)]
9696

9797
# Assuming undirected graph
98-
if v in self.adjList.keys():
98+
if v in self.adjList:
9999
self.adjList[v].append((u, w))
100100
else:
101101
self.adjList[v] = [(u, w)]

‎graphs/directed_and_undirected_(weighted)_graph.py

-7
Original file line numberDiff line numberDiff line change
@@ -226,9 +226,6 @@ def has_cycle(self):
226226
break
227227
else:
228228
return True
229-
# TODO:The following code is unreachable.
230-
anticipating_nodes.add(stack[len_stack_minus_one])
231-
len_stack_minus_one -= 1
232229
if visited.count(node[1]) < 1:
233230
stack.append(node[1])
234231
visited.append(node[1])
@@ -454,10 +451,6 @@ def has_cycle(self):
454451
break
455452
else:
456453
return True
457-
# TODO: the following code is unreachable
458-
# is this meant to be called in the else ?
459-
anticipating_nodes.add(stack[len_stack_minus_one])
460-
len_stack_minus_one -= 1
461454
if visited.count(node[1]) < 1:
462455
stack.append(node[1])
463456
visited.append(node[1])

‎hashes/hamming_code.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,7 @@ def emitter_converter(size_par, data):
7979
['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1']
8080
"""
8181
if size_par + len(data) <= 2**size_par - (len(data) - 1):
82-
print("ERROR - size of parity don't match with size of data")
83-
exit(0)
82+
raise ValueError("size of parity don't match with size of data")
8483

8584
data_out = []
8685
parity = []

‎linear_algebra/src/test_linear_algebra.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def test_zero_vector(self) -> None:
8989
"""
9090
test for global function zero_vector()
9191
"""
92-
self.assertTrue(str(zero_vector(10)).count("0") == 10)
92+
self.assertEqual(str(zero_vector(10)).count("0"), 10)
9393

9494
def test_unit_basis_vector(self) -> None:
9595
"""

‎maths/extended_euclidean_algorithm.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,12 @@ def main():
7575
"""Call Extended Euclidean Algorithm."""
7676
if len(sys.argv) < 3:
7777
print("2 integer arguments required")
78-
exit(1)
78+
return 1
7979
a = int(sys.argv[1])
8080
b = int(sys.argv[2])
8181
print(extended_euclidean_algorithm(a, b))
82+
return 0
8283

8384

8485
if __name__ == "__main__":
85-
main()
86+
raise SystemExit(main())

‎maths/jaccard_similarity.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"""
1515

1616

17-
def jaccard_similariy(set_a, set_b, alternative_union=False):
17+
def jaccard_similarity(set_a, set_b, alternative_union=False):
1818
"""
1919
Finds the jaccard similarity between two sets.
2020
Essentially, its intersection over union.
@@ -35,18 +35,18 @@ def jaccard_similariy(set_a, set_b, alternative_union=False):
3535
Examples:
3636
>>> set_a = {'a', 'b', 'c', 'd', 'e'}
3737
>>> set_b = {'c', 'd', 'e', 'f', 'h', 'i'}
38-
>>> jaccard_similariy(set_a, set_b)
38+
>>> jaccard_similarity(set_a, set_b)
3939
0.375
4040
41-
>>> jaccard_similariy(set_a, set_a)
41+
>>> jaccard_similarity(set_a, set_a)
4242
1.0
4343
44-
>>> jaccard_similariy(set_a, set_a, True)
44+
>>> jaccard_similarity(set_a, set_a, True)
4545
0.5
4646
4747
>>> set_a = ['a', 'b', 'c', 'd', 'e']
4848
>>> set_b = ('c', 'd', 'e', 'f', 'h', 'i')
49-
>>> jaccard_similariy(set_a, set_b)
49+
>>> jaccard_similarity(set_a, set_b)
5050
0.375
5151
"""
5252

@@ -67,14 +67,15 @@ def jaccard_similariy(set_a, set_b, alternative_union=False):
6767

6868
if alternative_union:
6969
union = len(set_a) + len(set_b)
70+
return len(intersection) / union
7071
else:
7172
union = set_a + [element for element in set_b if element not in set_a]
73+
return len(intersection) / len(union)
7274

7375
return len(intersection) / len(union)
7476

7577

7678
if __name__ == "__main__":
77-
7879
set_a = {"a", "b", "c", "d", "e"}
7980
set_b = {"c", "d", "e", "f", "h", "i"}
80-
print(jaccard_similariy(set_a, set_b))
81+
print(jaccard_similarity(set_a, set_b))

‎matrix/matrix_class.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ def add_column(self, column: list[int], position: int | None = None) -> None:
286286
# MATRIX OPERATIONS
287287
def __eq__(self, other: object) -> bool:
288288
if not isinstance(other, Matrix):
289-
raise TypeError("A Matrix can only be compared with another Matrix")
289+
return NotImplemented
290290
return self.rows == other.rows
291291

292292
def __ne__(self, other: object) -> bool:

‎project_euler/problem_001/sol7.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ def solution(n: int = 1000) -> int:
2626

2727
result = 0
2828
for i in range(n):
29-
if i % 3 == 0:
30-
result += i
31-
elif i % 5 == 0:
29+
if i % 3 == 0 or i % 5 == 0:
3230
result += i
3331
return result
3432

‎project_euler/problem_042/solution42.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,11 @@ def solution():
3434
words = f.readline()
3535

3636
words = [word.strip('"') for word in words.strip("\r\n").split(",")]
37-
words = list(
38-
filter(
39-
lambda word: word in TRIANGULAR_NUMBERS,
40-
(sum(ord(x) - 64 for x in word) for word in words),
41-
)
42-
)
37+
words = [
38+
word
39+
for word in [sum(ord(x) - 64 for x in word) for word in words]
40+
if word in TRIANGULAR_NUMBERS
41+
]
4342
return len(words)
4443

4544

‎project_euler/problem_067/sol1.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,12 @@ def solution():
2828
with open(triangle) as f:
2929
triangle = f.readlines()
3030

31-
a = (x.rstrip("\r\n").split(" ") for x in triangle)
32-
a = [list(map(int, x)) for x in a]
31+
a = []
32+
for line in triangle:
33+
numbers_from_line = []
34+
for number in line.strip().split(" "):
35+
numbers_from_line.append(int(number))
36+
a.append(numbers_from_line)
3337

3438
for i in range(1, len(a)):
3539
for j in range(len(a[i])):

‎project_euler/problem_089/sol1.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,9 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:
125125

126126
savings = 0
127127

128-
file1 = open(os.path.dirname(__file__) + roman_numerals_filename)
129-
lines = file1.readlines()
128+
with open(os.path.dirname(__file__) + roman_numerals_filename) as file1:
129+
lines = file1.readlines()
130+
130131
for line in lines:
131132
original = line.strip()
132133
num = parse_roman_numerals(original)

‎requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pandas
99
pillow
1010
qiskit
1111
requests
12-
# scikit-fuzzy # Causing broken builds
12+
scikit-fuzzy
1313
sklearn
1414
statsmodels
1515
sympy

‎scheduling/first_come_first_served.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,15 @@ def calculate_average_waiting_time(waiting_times: list[int]) -> float:
7979
# ensure that we actually have processes
8080
if len(processes) == 0:
8181
print("Zero amount of processes")
82-
exit()
82+
raise SystemExit(0)
8383

8484
# duration time of all processes
8585
duration_times = [19, 8, 9]
8686

8787
# ensure we can match each id to a duration time
8888
if len(duration_times) != len(processes):
8989
print("Unable to match all id's with their duration time")
90-
exit()
90+
raise SystemExit(0)
9191

9292
# get the waiting times and the turnaround times
9393
waiting_times = calculate_waiting_times(duration_times)

‎scheduling/multi_level_feedback_queue.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ def multi_level_feedback_queue(self) -> deque[Process]:
276276
queue = deque([P1, P2, P3, P4])
277277

278278
if len(time_slices) != number_of_queues - 1:
279-
exit()
279+
raise SystemExit(0)
280280

281281
doctest.testmod(extraglobs={"queue": deque([P1, P2, P3, P4])})
282282

‎web_programming/emails_from_url.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def emails_from_url(url: str = "https://github.com") -> list[str]:
9393
except ValueError:
9494
pass
9595
except ValueError:
96-
exit(-1)
96+
raise SystemExit(1)
9797

9898
# Finally return a sorted list of email addresses with no duplicates.
9999
return sorted(valid_emails)

0 commit comments

Comments
 (0)
Please sign in to comment.